{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2026-09-17T07:31:17.125705Z","iopub.execute_input":"2026-09-17T07:31:17.126207Z","iopub.status.idle":"2026-09-17T07:31:17.133923Z","shell.execute_reply.started":"2026-09-17T07:31:17.126161Z","shell.execute_reply":"2026-09-17T07:31:17.132988Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:17.135287Z","iopub.execute_input":"2026-09-17T07:31:17.135818Z","iopub.status.idle":"2026-09-17T07:31:18.176527Z","shell.execute_reply.started":"2026-09-17T07:31:17.135783Z","shell.execute_reply":"2026-09-17T07:31:18.175243Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:18.178261Z","iopub.execute_input":"2026-09-17T07:31:18.178683Z","iopub.status.idle":"2026-09-17T07:31:19.183694Z","shell.execute_reply.started":"2026-09-17T07:31:18.178654Z","shell.execute_reply":"2026-09-17T07:31:19.182609Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:19.187019Z","iopub.execute_input":"2026-09-17T07:31:19.187384Z","iopub.status.idle":"2026-09-17T07:31:28.169951Z","shell.execute_reply.started":"2026-09-17T07:31:19.187356Z","shell.execute_reply":"2026-09-17T07:31:28.169244Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:28.171452Z","iopub.execute_input":"2026-09-17T07:31:28.171853Z","iopub.status.idle":"2026-09-17T07:31:29.176402Z","shell.execute_reply.started":"2026-09-17T07:31:28.171825Z","shell.execute_reply":"2026-09-17T07:31:29.175414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:29.178132Z","iopub.execute_input":"2026-09-17T07:31:29.178556Z","iopub.status.idle":"2026-09-17T07:31:30.223296Z","shell.execute_reply.started":"2026-09-17T07:31:29.178514Z","shell.execute_reply":"2026-09-17T07:31:30.221996Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:30.225149Z","iopub.execute_input":"2026-09-17T07:31:30.225531Z","iopub.status.idle":"2026-09-17T07:31:31.330073Z","shell.execute_reply.started":"2026-09-17T07:31:30.225493Z","shell.execute_reply":"2026-09-17T07:31:31.328902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:31.331636Z","iopub.execute_input":"2026-09-17T07:31:31.332075Z","iopub.status.idle":"2026-09-17T07:31:32.386951Z","shell.execute_reply.started":"2026-09-17T07:31:31.332046Z","shell.execute_reply":"2026-09-17T07:31:32.386007Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:32.388444Z","iopub.execute_input":"2026-09-17T07:31:32.388707Z","iopub.status.idle":"2026-09-17T07:31:33.481309Z","shell.execute_reply.started":"2026-09-17T07:31:32.388682Z","shell.execute_reply":"2026-09-17T07:31:33.480311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:33.485864Z","iopub.execute_input":"2026-09-17T07:31:33.486185Z","iopub.status.idle":"2026-09-17T07:31:33.490791Z","shell.execute_reply.started":"2026-09-17T07:31:33.486156Z","shell.execute_reply":"2026-09-17T07:31:33.489774Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:33.492073Z","iopub.execute_input":"2026-09-17T07:31:33.492431Z","iopub.status.idle":"2026-09-17T07:31:33.503196Z","shell.execute_reply.started":"2026-09-17T07:31:33.492396Z","shell.execute_reply":"2026-09-17T07:31:33.502466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:33.504360Z","iopub.execute_input":"2026-09-17T07:31:33.505244Z","iopub.status.idle":"2026-09-17T07:31:34.536563Z","shell.execute_reply.started":"2026-09-17T07:31:33.505208Z","shell.execute_reply":"2026-09-17T07:31:34.535242Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:34.538538Z","iopub.execute_input":"2026-09-17T07:31:34.538994Z","iopub.status.idle":"2026-09-17T07:31:35.640905Z","shell.execute_reply.started":"2026-09-17T07:31:34.538948Z","shell.execute_reply":"2026-09-17T07:31:35.639947Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:35.642261Z","iopub.execute_input":"2026-09-17T07:31:35.642555Z","iopub.status.idle":"2026-09-17T07:31:36.682483Z","shell.execute_reply.started":"2026-09-17T07:31:35.642527Z","shell.execute_reply":"2026-09-17T07:31:36.681531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\n# from matplotlib import pyplot as plt\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:36.684057Z","iopub.execute_input":"2026-09-17T07:31:36.684381Z","iopub.status.idle":"2026-09-17T07:31:37.621169Z","shell.execute_reply.started":"2026-09-17T07:31:36.684348Z","shell.execute_reply":"2026-09-17T07:31:37.620411Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:37.622238Z","iopub.execute_input":"2026-09-17T07:31:37.622583Z","iopub.status.idle":"2026-09-17T07:31:38.554604Z","shell.execute_reply.started":"2026-09-17T07:31:37.622558Z","shell.execute_reply":"2026-09-17T07:31:38.553567Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:38.555809Z","iopub.execute_input":"2026-09-17T07:31:38.556182Z","iopub.status.idle":"2026-09-17T07:31:39.571993Z","shell.execute_reply.started":"2026-09-17T07:31:38.556156Z","shell.execute_reply":"2026-09-17T07:31:39.570487Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow\nprint(tensorflow.__version__)\n\nimport keras\nprint(keras.__version__)\n\nimport tensorflow.keras\nprint(tensorflow.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:39.574009Z","iopub.execute_input":"2026-09-17T07:31:39.574730Z","iopub.status.idle":"2026-09-17T07:31:39.580751Z","shell.execute_reply.started":"2026-09-17T07:31:39.574670Z","shell.execute_reply":"2026-09-17T07:31:39.579779Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:39.581963Z","iopub.execute_input":"2026-09-17T07:31:39.582607Z","iopub.status.idle":"2026-09-17T07:31:39.590053Z","shell.execute_reply.started":"2026-09-17T07:31:39.582579Z","shell.execute_reply":"2026-09-17T07:31:39.589379Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:39.591092Z","iopub.execute_input":"2026-09-17T07:31:39.591341Z","iopub.status.idle":"2026-09-17T07:31:39.599904Z","shell.execute_reply.started":"2026-09-17T07:31:39.591320Z","shell.execute_reply":"2026-09-17T07:31:39.599104Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:39.600853Z","iopub.execute_input":"2026-09-17T07:31:39.601548Z","iopub.status.idle":"2026-09-17T07:31:39.610552Z","shell.execute_reply.started":"2026-09-17T07:31:39.601515Z","shell.execute_reply":"2026-09-17T07:31:39.609772Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:39.611453Z","iopub.execute_input":"2026-09-17T07:31:39.612016Z","iopub.status.idle":"2026-09-17T07:31:40.696014Z","shell.execute_reply.started":"2026-09-17T07:31:39.611968Z","shell.execute_reply":"2026-09-17T07:31:40.695025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:40.697441Z","iopub.execute_input":"2026-09-17T07:31:40.698589Z","iopub.status.idle":"2026-09-17T07:31:41.712463Z","shell.execute_reply.started":"2026-09-17T07:31:40.698548Z","shell.execute_reply":"2026-09-17T07:31:41.711238Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:41.714301Z","iopub.execute_input":"2026-09-17T07:31:41.714764Z","iopub.status.idle":"2026-09-17T07:31:42.758107Z","shell.execute_reply.started":"2026-09-17T07:31:41.714698Z","shell.execute_reply":"2026-09-17T07:31:42.756887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test #validation","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:42.759701Z","iopub.execute_input":"2026-09-17T07:31:42.760473Z","iopub.status.idle":"2026-09-17T07:31:43.766858Z","shell.execute_reply.started":"2026-09-17T07:31:42.760444Z","shell.execute_reply":"2026-09-17T07:31:43.765930Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:43.768377Z","iopub.execute_input":"2026-09-17T07:31:43.769026Z","iopub.status.idle":"2026-09-17T07:31:46.718876Z","shell.execute_reply.started":"2026-09-17T07:31:43.768997Z","shell.execute_reply":"2026-09-17T07:31:46.717796Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:46.720096Z","iopub.execute_input":"2026-09-17T07:31:46.720370Z","iopub.status.idle":"2026-09-17T07:31:46.725390Z","shell.execute_reply.started":"2026-09-17T07:31:46.720347Z","shell.execute_reply":"2026-09-17T07:31:46.724508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:46.734937Z","iopub.execute_input":"2026-09-17T07:31:46.735255Z","iopub.status.idle":"2026-09-17T07:31:48.922443Z","shell.execute_reply.started":"2026-09-17T07:31:46.735234Z","shell.execute_reply":"2026-09-17T07:31:48.921341Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:48.923818Z","iopub.execute_input":"2026-09-17T07:31:48.924113Z","iopub.status.idle":"2026-09-17T07:31:51.112351Z","shell.execute_reply.started":"2026-09-17T07:31:48.924086Z","shell.execute_reply":"2026-09-17T07:31:51.111354Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:51.113909Z","iopub.execute_input":"2026-09-17T07:31:51.114256Z","iopub.status.idle":"2026-09-17T07:31:59.483107Z","shell.execute_reply.started":"2026-09-17T07:31:51.114226Z","shell.execute_reply":"2026-09-17T07:31:59.482011Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-17T07:31:59.484418Z","iopub.execute_input":"2026-09-17T07:31:59.485047Z","iopub.status.idle":"2026-09-17T07:31:59.489444Z","shell.execute_reply.started":"2026-09-17T07:31:59.485016Z","shell.execute_reply":"2026-09-17T07:31:59.488509Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.490492Z","iopub.execute_input":"2026-09-17T07:31:59.490879Z","iopub.status.idle":"2026-09-17T07:31:59.501855Z","shell.execute_reply.started":"2026-09-17T07:31:59.490853Z","shell.execute_reply":"2026-09-17T07:31:59.501100Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.503129Z","iopub.execute_input":"2026-09-17T07:31:59.503912Z","iopub.status.idle":"2026-09-17T07:31:59.511192Z","shell.execute_reply.started":"2026-09-17T07:31:59.503887Z","shell.execute_reply":"2026-09-17T07:31:59.510409Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.512612Z","iopub.execute_input":"2026-09-17T07:31:59.513310Z","iopub.status.idle":"2026-09-17T07:31:59.527643Z","shell.execute_reply.started":"2026-09-17T07:31:59.513284Z","shell.execute_reply":"2026-09-17T07:31:59.526689Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,\n                 (3, 3),\n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.528814Z","iopub.execute_input":"2026-09-17T07:31:59.529156Z","iopub.status.idle":"2026-09-17T07:31:59.594271Z","shell.execute_reply.started":"2026-09-17T07:31:59.529133Z","shell.execute_reply":"2026-09-17T07:31:59.593343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,\n                 (3, 3),\n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(2, activation='softmax'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.595341Z","iopub.execute_input":"2026-09-17T07:31:59.595658Z","iopub.status.idle":"2026-09-17T07:31:59.650489Z","shell.execute_reply.started":"2026-09-17T07:31:59.595636Z","shell.execute_reply":"2026-09-17T07:31:59.649687Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Dropout\nfrom tensorflow.keras.optimizers import SGD\n\n# define cnn model using Transfer Learning\ndef define_model_1():\n    base_model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    for layer in base_model.layers:\n        layer.trainable = False\n        \n\n    model = Sequential()\n    model.add(base_model)\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dropout(0.5))  \n    model.add(Dense(1, activation='sigmoid'))\n    \n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.651796Z","iopub.execute_input":"2026-09-17T07:31:59.652126Z","iopub.status.idle":"2026-09-17T07:31:59.661057Z","shell.execute_reply.started":"2026-09-17T07:31:59.652094Z","shell.execute_reply":"2026-09-17T07:31:59.660036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:31:59.662268Z","iopub.execute_input":"2026-09-17T07:31:59.662936Z","iopub.status.idle":"2026-09-17T07:32:00.080108Z","shell.execute_reply.started":"2026-09-17T07:31:59.662902Z","shell.execute_reply":"2026-09-17T07:32:00.079393Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    pyplot.show()\n    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png') \n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:32:00.082800Z","iopub.execute_input":"2026-09-17T07:32:00.083027Z","iopub.status.idle":"2026-09-17T07:32:00.089216Z","shell.execute_reply.started":"2026-09-17T07:32:00.083006Z","shell.execute_reply":"2026-09-17T07:32:00.088183Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n    model = define_model_1()\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\n    \n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    \n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=1)\n    \n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    summarize_diagnostics(history)\n    \n    return model, test_it\n\nmodel_1, test_it = run_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T07:32:00.090548Z","iopub.execute_input":"2026-09-17T07:32:00.091037Z","iopub.status.idle":"2026-09-17T08:05:49.443262Z","shell.execute_reply.started":"2026-09-17T07:32:00.091012Z","shell.execute_reply":"2026-09-17T08:05:49.442518Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:05:49.445600Z","iopub.execute_input":"2026-09-17T08:05:49.445975Z","iopub.status.idle":"2026-09-17T08:05:49.852513Z","shell.execute_reply.started":"2026-09-17T08:05:49.445948Z","shell.execute_reply":"2026-09-17T08:05:49.851650Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\ntype(datagen)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:05:49.853586Z","iopub.execute_input":"2026-09-17T08:05:49.853943Z","iopub.status.idle":"2026-09-17T08:05:49.859590Z","shell.execute_reply.started":"2026-09-17T08:05:49.853919Z","shell.execute_reply":"2026-09-17T08:05:49.858571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:05:49.860651Z","iopub.execute_input":"2026-09-17T08:05:49.860914Z","iopub.status.idle":"2026-09-17T08:05:50.906474Z","shell.execute_reply.started":"2026-09-17T08:05:49.860893Z","shell.execute_reply":"2026-09-17T08:05:50.905092Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hyperparameter => changable\nIMAGE_SIZE = (224, 224)\nBATCH_SIZE = 64\nEPOCHS = 20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:19.438576Z","iopub.execute_input":"2026-09-17T08:11:19.439249Z","iopub.status.idle":"2026-09-17T08:11:19.443104Z","shell.execute_reply.started":"2026-09-17T08:11:19.439215Z","shell.execute_reply":"2026-09-17T08:11:19.442224Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIZE, \n        target_size=IMAGE_SIZE\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:22.602871Z","iopub.execute_input":"2026-09-17T08:11:22.603690Z","iopub.status.idle":"2026-09-17T08:11:23.093385Z","shell.execute_reply.started":"2026-09-17T08:11:22.603653Z","shell.execute_reply":"2026-09-17T08:11:23.092675Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_it), len(train_it.classes), train_it.classes[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:27.664046Z","iopub.execute_input":"2026-09-17T08:11:27.664822Z","iopub.status.idle":"2026-09-17T08:11:27.670690Z","shell.execute_reply.started":"2026-09-17T08:11:27.664786Z","shell.execute_reply":"2026-09-17T08:11:27.669688Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIZE,\n        target_size=IMAGE_SIZE\n)\ntype(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:31.200901Z","iopub.execute_input":"2026-09-17T08:11:31.201567Z","iopub.status.idle":"2026-09-17T08:11:31.474967Z","shell.execute_reply.started":"2026-09-17T08:11:31.201536Z","shell.execute_reply":"2026-09-17T08:11:31.474171Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(val_it), len(val_it.classes), val_it.classes[-10:]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:36.602859Z","iopub.execute_input":"2026-09-17T08:11:36.603484Z","iopub.status.idle":"2026-09-17T08:11:36.610086Z","shell.execute_reply.started":"2026-09-17T08:11:36.603451Z","shell.execute_reply":"2026-09-17T08:11:36.609103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit(\n    train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=EPOCHS,\n    verbose=2,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:11:40.106677Z","iopub.execute_input":"2026-09-17T08:11:40.107207Z","iopub.status.idle":"2026-09-17T08:45:01.331785Z","shell.execute_reply.started":"2026-09-17T08:11:40.107175Z","shell.execute_reply":"2026-09-17T08:45:01.330965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:49:08.563658Z","iopub.execute_input":"2026-09-17T08:49:08.564194Z","iopub.status.idle":"2026-09-17T08:49:09.231232Z","shell.execute_reply.started":"2026-09-17T08:49:08.564163Z","shell.execute_reply":"2026-09-17T08:49:09.230531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:49:13.492951Z","iopub.execute_input":"2026-09-17T08:49:13.493672Z","iopub.status.idle":"2026-09-17T08:49:37.348363Z","shell.execute_reply.started":"2026-09-17T08:49:13.493636Z","shell.execute_reply":"2026-09-17T08:49:37.347507Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:49:46.394825Z","iopub.execute_input":"2026-09-17T08:49:46.395621Z","iopub.status.idle":"2026-09-17T08:49:47.399582Z","shell.execute_reply.started":"2026-09-17T08:49:46.395591Z","shell.execute_reply":"2026-09-17T08:49:47.398661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:49:49.938258Z","iopub.execute_input":"2026-09-17T08:49:49.938821Z","iopub.status.idle":"2026-09-17T08:49:49.946231Z","shell.execute_reply.started":"2026-09-17T08:49:49.938785Z","shell.execute_reply":"2026-09-17T08:49:49.945226Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:02.766439Z","iopub.execute_input":"2026-09-17T08:50:02.767321Z","iopub.status.idle":"2026-09-17T08:50:02.799790Z","shell.execute_reply.started":"2026-09-17T08:50:02.767287Z","shell.execute_reply":"2026-09-17T08:50:02.799120Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:49:58.620314Z","iopub.execute_input":"2026-09-17T08:49:58.621147Z","iopub.status.idle":"2026-09-17T08:49:58.627667Z","shell.execute_reply.started":"2026-09-17T08:49:58.621109Z","shell.execute_reply":"2026-09-17T08:49:58.626512Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_files[:5], type(image_files), len(image_files)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:06.230203Z","iopub.execute_input":"2026-09-17T08:50:06.230522Z","iopub.status.idle":"2026-09-17T08:50:06.237125Z","shell.execute_reply.started":"2026-09-17T08:50:06.230498Z","shell.execute_reply":"2026-09-17T08:50:06.236206Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:10.898098Z","iopub.execute_input":"2026-09-17T08:50:10.898895Z","iopub.status.idle":"2026-09-17T08:50:10.918176Z","shell.execute_reply.started":"2026-09-17T08:50:10.898855Z","shell.execute_reply":"2026-09-17T08:50:10.917387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:14.936706Z","iopub.execute_input":"2026-09-17T08:50:14.937492Z","iopub.status.idle":"2026-09-17T08:50:14.944647Z","shell.execute_reply.started":"2026-09-17T08:50:14.937459Z","shell.execute_reply":"2026-09-17T08:50:14.943878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:18.184953Z","iopub.execute_input":"2026-09-17T08:50:18.185780Z","iopub.status.idle":"2026-09-17T08:50:18.195641Z","shell.execute_reply.started":"2026-09-17T08:50:18.185701Z","shell.execute_reply":"2026-09-17T08:50:18.194560Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:22.266908Z","iopub.execute_input":"2026-09-17T08:50:22.267540Z","iopub.status.idle":"2026-09-17T08:50:22.274448Z","shell.execute_reply.started":"2026-09-17T08:50:22.267507Z","shell.execute_reply":"2026-09-17T08:50:22.273496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (200, 200)\n\n# datagen = ImageDataGenerator(rescale=1.0/255.0,\n#                             horizontal_flip=True,)\n# print(IMAGE_SIZE)\n# # prepare iterators\n# train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n#     class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n#     class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen_test = ImageDataGenerator(rescale=1./255,\n                                 vertical_flip=True)\n\n# Create the data generator using the DataFrame\ntest_it = datagen_test.flow_from_dataframe(\n    dataframe=df,\n    x_col='filename',\n    y_col=None,            # No labels for testing, so set to None\n    target_size=IMAGE_SIZE,\n    batch_size=64,\n    class_mode=None,       # Since there are no labels\n    # shuffle=True,         # Usually testing data should not be shuffled\n    shuffle=False,\n)\n\ntype(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:27.089188Z","iopub.execute_input":"2026-09-17T08:50:27.089897Z","iopub.status.idle":"2026-09-17T08:50:27.172872Z","shell.execute_reply.started":"2026-09-17T08:50:27.089865Z","shell.execute_reply":"2026-09-17T08:50:27.172132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\ndef plot_exmaple(images, labels):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))  # Fixed: set_title instead of title\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:32.299254Z","iopub.execute_input":"2026-09-17T08:50:32.299559Z","iopub.status.idle":"2026-09-17T08:50:32.306963Z","shell.execute_reply.started":"2026-09-17T08:50:32.299535Z","shell.execute_reply":"2026-09-17T08:50:32.306025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\nprint(train_images.shape, len(train_labels))\nplot_exmaple(train_images, train_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:36.311600Z","iopub.execute_input":"2026-09-17T08:50:36.312400Z","iopub.status.idle":"2026-09-17T08:50:41.138555Z","shell.execute_reply.started":"2026-09-17T08:50:36.312371Z","shell.execute_reply":"2026-09-17T08:50:41.137089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)\nval_labels[:8]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:50:49.308800Z","iopub.execute_input":"2026-09-17T08:50:49.309124Z","iopub.status.idle":"2026-09-17T08:50:54.584787Z","shell.execute_reply.started":"2026-09-17T08:50:49.309098Z","shell.execute_reply":"2026-09-17T08:50:54.583292Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images, indices):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(indices[i]))  # ตั้งค่า title ด้วย index จาก list/array indices\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:05.470383Z","iopub.execute_input":"2026-09-17T08:51:05.471245Z","iopub.status.idle":"2026-09-17T08:51:05.476678Z","shell.execute_reply.started":"2026-09-17T08:51:05.471212Z","shell.execute_reply":"2026-09-17T08:51:05.475619Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__() \n\nindices = list(range(len(test_images)))\n\nplot_exmaple_test(test_images, indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:08.633506Z","iopub.execute_input":"2026-09-17T08:51:08.634403Z","iopub.status.idle":"2026-09-17T08:51:13.580103Z","shell.execute_reply.started":"2026-09-17T08:51:08.634372Z","shell.execute_reply":"2026-09-17T08:51:13.578508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\npreds = model_1.predict(test_it, verbose=1)\ntype(preds), preds.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:24.177809Z","iopub.execute_input":"2026-09-17T08:51:24.178137Z","iopub.status.idle":"2026-09-17T08:51:24.735939Z","shell.execute_reply.started":"2026-09-17T08:51:24.178112Z","shell.execute_reply":"2026-09-17T08:51:24.733877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:31.173553Z","iopub.execute_input":"2026-09-17T08:51:31.173910Z","iopub.status.idle":"2026-09-17T08:51:31.199975Z","shell.execute_reply.started":"2026-09-17T08:51:31.173881Z","shell.execute_reply":"2026-09-17T08:51:31.198783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\n\n# 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\nsample_indices = np.random.choice(len(test_images), size=10, replace=False)\nsample_images = test_images[sample_indices]\n\n# 2. Predict \npredictions = model_1.predict(sample_images)\npredicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\nfig, axes = plt.subplots(2, 5, figsize=(15, 6))\naxes = axes.flatten()\n\nfor i, ax in enumerate(axes):\n    ax.imshow(sample_images[i])\n    # แสดง Index เดิม และ Class ที่ทายได้\n    ax.set_title(f\"Idx: {sample_indices[i]}\\nPred: {predicted_classes[i]}\")\n    ax.axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:57.648885Z","iopub.execute_input":"2026-09-17T08:51:57.649873Z","iopub.status.idle":"2026-09-17T08:51:59.372524Z","shell.execute_reply.started":"2026-09-17T08:51:57.649841Z","shell.execute_reply":"2026-09-17T08:51:59.371146Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# end of 2026-09-06\n#stop here","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.492860Z","iopub.status.idle":"2026-09-17T08:06:00.493186Z","shell.execute_reply.started":"2026-09-17T08:06:00.493041Z","shell.execute_reply":"2026-09-17T08:06:00.493057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.494670Z","iopub.status.idle":"2026-09-17T08:06:00.494991Z","shell.execute_reply.started":"2026-09-17T08:06:00.494860Z","shell.execute_reply":"2026-09-17T08:06:00.494875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.496258Z","iopub.status.idle":"2026-09-17T08:06:00.496574Z","shell.execute_reply.started":"2026-09-17T08:06:00.496435Z","shell.execute_reply":"2026-09-17T08:06:00.496450Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nimport tensorflow as tf\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.optimizers import SGD\n\ndef define_model_vgg16():\n    # โหลด VGG16 แบบไม่เอาชั้น Classifier เดิม\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    # ล็อกชั้นเดิมไว้ไม่ให้เทรนซ้ำ (Freeze layers)\n    for layer in model.layers:\n        layer.trainable = False\n        \n    # เพิ่มชั้นจำแนกผลใหม่สำหรับหมา/แมว (Output 1 โหนด + Sigmoid)\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    \n    model = Model(inputs=model.inputs, outputs=output)\n    \n    # แก้ไข lr เป็น learning_rate\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# --- สั่งสร้างโมเดลและแสดงโครงสร้างออกจอ ---\nmodel = define_model_vgg16()\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.498229Z","iopub.status.idle":"2026-09-17T08:06:00.498490Z","shell.execute_reply.started":"2026-09-17T08:06:00.498366Z","shell.execute_reply":"2026-09-17T08:06:00.498379Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model = VGG16(include_top=False, input_shape=(224, 224, 3))\n# mark loaded layers as not trainable\n# for layer in model.layers:\n#     layer.trainable = False\n\n# print(model.layers[-1].output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.499757Z","iopub.status.idle":"2026-09-17T08:06:00.500079Z","shell.execute_reply.started":"2026-09-17T08:06:00.499936Z","shell.execute_reply":"2026-09-17T08:06:00.499951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_feature_extractor = VGG16(include_top=False, input_shape=(224, 224, 3))\n# model_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.501165Z","iopub.status.idle":"2026-09-17T08:06:00.501424Z","shell.execute_reply.started":"2026-09-17T08:06:00.501297Z","shell.execute_reply":"2026-09-17T08:06:00.501310Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model_16_feature_extractor.layers):\n# \t\tprint(index, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.503134Z","iopub.status.idle":"2026-09-17T08:06:00.503399Z","shell.execute_reply.started":"2026-09-17T08:06:00.503267Z","shell.execute_reply":"2026-09-17T08:06:00.503286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_top = VGG16(include_top=True, input_shape=(224, 224, 3))\n# model_16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.504975Z","iopub.status.idle":"2026-09-17T08:06:00.505339Z","shell.execute_reply.started":"2026-09-17T08:06:00.505187Z","shell.execute_reply":"2026-09-17T08:06:00.505203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.507014Z","iopub.status.idle":"2026-09-17T08:06:00.507437Z","shell.execute_reply.started":"2026-09-17T08:06:00.507213Z","shell.execute_reply":"2026-09-17T08:06:00.507234Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.508489Z","iopub.status.idle":"2026-09-17T08:06:00.508987Z","shell.execute_reply.started":"2026-09-17T08:06:00.508737Z","shell.execute_reply":"2026-09-17T08:06:00.508765Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     print(index, layer.name, layer.trainable)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.511191Z","iopub.status.idle":"2026-09-17T08:06:00.511506Z","shell.execute_reply.started":"2026-09-17T08:06:00.511367Z","shell.execute_reply":"2026-09-17T08:06:00.511382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     layer.trainable = True\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.512667Z","iopub.status.idle":"2026-09-17T08:06:00.513044Z","shell.execute_reply.started":"2026-09-17T08:06:00.512903Z","shell.execute_reply":"2026-09-17T08:06:00.512919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     if index >= 15:\n#         layer.trainable = True\n\n# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.514021Z","iopub.status.idle":"2026-09-17T08:06:00.514285Z","shell.execute_reply.started":"2026-09-17T08:06:00.514158Z","shell.execute_reply":"2026-09-17T08:06:00.514171Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ntest_imgs, test_labels = next(test_it) \n\npreds = model_1.predict(test_imgs[:10])\n\nplt.figure(figsize=(15, 6))\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(test_imgs[i])\n    \n    actual = \"Dog\" if test_labels[i] == 1 else \"Cat\"\n    pred = \"Dog\" if preds[i] > 0.5 else \"Cat\"\n    \n    color = \"green\" if actual == pred else \"red\"\n    plt.title(f\"Real: {actual}\\nPred: {pred}\", color=color)\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.515285Z","iopub.status.idle":"2026-09-17T08:06:00.515539Z","shell.execute_reply.started":"2026-09-17T08:06:00.515414Z","shell.execute_reply":"2026-09-17T08:06:00.515427Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.516434Z","iopub.status.idle":"2026-09-17T08:06:00.516796Z","shell.execute_reply.started":"2026-09-17T08:06:00.516602Z","shell.execute_reply":"2026-09-17T08:06:00.516617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nprint(id(vgg16_model))\nvgg16_model.reset_states()\nvgg16_model_history = vgg16_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.518197Z","iopub.status.idle":"2026-09-17T08:06:00.518459Z","shell.execute_reply.started":"2026-09-17T08:06:00.518332Z","shell.execute_reply":"2026-09-17T08:06:00.518346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. ตรวจสอบให้แน่ใจว่าได้ระบุ class_mode='binary' ตอนดึงข้อมูล\ntrain_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',\n    target_size=(224, 224),\n    batch_size=BATCH_SIZE,\n    class_mode='binary'  # <--- ต้องเป็น binary\n)\n\nval_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',\n    target_size=(224, 224),\n    batch_size=BATCH_SIZE,\n    class_mode='binary'  # <--- ต้องเป็น binary\n)\n\n# 2. รันการเทรนโมเดล\nvgg16_model_history = vgg16_model.fit(\n    train_it,\n    validation_data=val_it,\n    epochs=3,\n    verbose=1,\n    callbacks=[PlotLossesKeras()]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.520338Z","iopub.status.idle":"2026-09-17T08:06:00.520647Z","shell.execute_reply.started":"2026-09-17T08:06:00.520510Z","shell.execute_reply":"2026-09-17T08:06:00.520525Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(vgg16_model_history)\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.521903Z","iopub.status.idle":"2026-09-17T08:06:00.522221Z","shell.execute_reply.started":"2026-09-17T08:06:00.522078Z","shell.execute_reply":"2026-09-17T08:06:00.522093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        # layer.trainable = True #try to test\n    \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n    # output = Dense(1, activation='sigmoid')(flat1)\n    output = Dense(2, activation='softmax')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.523129Z","iopub.status.idle":"2026-09-17T08:06:00.523450Z","shell.execute_reply.started":"2026-09-17T08:06:00.523304Z","shell.execute_reply":"2026-09-17T08:06:00.523320Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.524790Z","iopub.status.idle":"2026-09-17T08:06:00.525280Z","shell.execute_reply.started":"2026-09-17T08:06:00.524998Z","shell.execute_reply":"2026-09-17T08:06:00.525040Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.527760Z","iopub.status.idle":"2026-09-17T08:06:00.528081Z","shell.execute_reply.started":"2026-09-17T08:06:00.527942Z","shell.execute_reply":"2026-09-17T08:06:00.527958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nfor w in model_inceptionv3.trainable_weights:\n    print(w.name, K.count_params(w))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.529288Z","iopub.status.idle":"2026-09-17T08:06:00.529547Z","shell.execute_reply.started":"2026-09-17T08:06:00.529421Z","shell.execute_reply":"2026-09-17T08:06:00.529434Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_inceptionv3.reset_states()\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:44.385458Z","iopub.execute_input":"2026-09-17T08:51:44.385785Z","iopub.status.idle":"2026-09-17T08:51:44.412504Z","shell.execute_reply.started":"2026-09-17T08:51:44.385759Z","shell.execute_reply":"2026-09-17T08:51:44.411056Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:51:41.418003Z","iopub.execute_input":"2026-09-17T08:51:41.418794Z","iopub.status.idle":"2026-09-17T08:51:41.425546Z","shell.execute_reply.started":"2026-09-17T08:51:41.418743Z","shell.execute_reply":"2026-09-17T08:51:41.424604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.534393Z","iopub.status.idle":"2026-09-17T08:06:00.534848Z","shell.execute_reply.started":"2026-09-17T08:06:00.534611Z","shell.execute_reply":"2026-09-17T08:06:00.534632Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.535811Z","iopub.status.idle":"2026-09-17T08:06:00.536225Z","shell.execute_reply.started":"2026-09-17T08:06:00.536004Z","shell.execute_reply":"2026-09-17T08:06:00.536026Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # mark loaded layers as not trainable\n# for index, layer in enumerate(model.layers[:15]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = False\n    \n# for index, layer in enumerate(model.layers[15:]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.537305Z","iopub.status.idle":"2026-09-17T08:06:00.537739Z","shell.execute_reply.started":"2026-09-17T08:06:00.537499Z","shell.execute_reply":"2026-09-17T08:06:00.537522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\n# best_model = 'vgg16_model.hdf5'\n# my_model.save(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.539433Z","iopub.status.idle":"2026-09-17T08:06:00.539867Z","shell.execute_reply.started":"2026-09-17T08:06:00.539633Z","shell.execute_reply":"2026-09-17T08:06:00.539655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.540797Z","iopub.status.idle":"2026-09-17T08:06:00.541217Z","shell.execute_reply.started":"2026-09-17T08:06:00.540992Z","shell.execute_reply":"2026-09-17T08:06:00.541013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5 first img: 1, 0, 1, 1, 0\nimages_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.542444Z","iopub.status.idle":"2026-09-17T08:06:00.542874Z","shell.execute_reply.started":"2026-09-17T08:06:00.542639Z","shell.execute_reply":"2026-09-17T08:06:00.542661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T08:06:00.544401Z","iopub.status.idle":"2026-09-17T08:06:00.544831Z","shell.execute_reply.started":"2026-09-17T08:06:00.544596Z","shell.execute_reply":"2026-09-17T08:06:00.544618Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}