{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":3362}],"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-11T10:01:44.529569Z","iopub.execute_input":"2026-09-11T10:01:44.529994Z","iopub.status.idle":"2026-09-11T10:01:44.538890Z","shell.execute_reply.started":"2026-09-11T10:01:44.529963Z","shell.execute_reply":"2026-09-11T10:01:44.538173Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:44.540461Z","iopub.execute_input":"2026-09-11T10:01:44.540833Z","iopub.status.idle":"2026-09-11T10:01:44.688854Z","shell.execute_reply.started":"2026-09-11T10:01:44.540809Z","shell.execute_reply":"2026-09-11T10:01:44.687721Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:44.690262Z","iopub.execute_input":"2026-09-11T10:01:44.690544Z","iopub.status.idle":"2026-09-11T10:01:44.832562Z","shell.execute_reply.started":"2026-09-11T10:01:44.690514Z","shell.execute_reply":"2026-09-11T10:01:44.831478Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2026-09-11T10:01:44.835019Z","iopub.execute_input":"2026-09-11T10:01:44.835413Z","iopub.status.idle":"2026-09-11T10:01:54.222261Z","shell.execute_reply.started":"2026-09-11T10:01:44.835381Z","shell.execute_reply":"2026-09-11T10:01:54.221362Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:54.224182Z","iopub.execute_input":"2026-09-11T10:01:54.224543Z","iopub.status.idle":"2026-09-11T10:01:54.365057Z","shell.execute_reply.started":"2026-09-11T10:01:54.224519Z","shell.execute_reply":"2026-09-11T10:01:54.364283Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:54.366264Z","iopub.execute_input":"2026-09-11T10:01:54.366697Z","iopub.status.idle":"2026-09-11T10:01:54.505842Z","shell.execute_reply.started":"2026-09-11T10:01:54.366665Z","shell.execute_reply":"2026-09-11T10:01:54.505011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:54.507327Z","iopub.execute_input":"2026-09-11T10:01:54.507585Z","iopub.status.idle":"2026-09-11T10:01:54.716029Z","shell.execute_reply.started":"2026-09-11T10:01:54.507558Z","shell.execute_reply":"2026-09-11T10:01:54.715283Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:54.717548Z","iopub.execute_input":"2026-09-11T10:01:54.718603Z","iopub.status.idle":"2026-09-11T10:01:54.907717Z","shell.execute_reply.started":"2026-09-11T10:01:54.718549Z","shell.execute_reply":"2026-09-11T10:01:54.906909Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:54.909285Z","iopub.execute_input":"2026-09-11T10:01:54.910298Z","iopub.status.idle":"2026-09-11T10:01:55.173700Z","shell.execute_reply.started":"2026-09-11T10:01:54.910202Z","shell.execute_reply":"2026-09-11T10:01:55.172891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:55.175133Z","iopub.execute_input":"2026-09-11T10:01:55.175833Z","iopub.status.idle":"2026-09-11T10:01:55.179693Z","shell.execute_reply.started":"2026-09-11T10:01:55.175803Z","shell.execute_reply":"2026-09-11T10:01:55.178752Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:55.180776Z","iopub.execute_input":"2026-09-11T10:01:55.181098Z","iopub.status.idle":"2026-09-11T10:01:55.195114Z","shell.execute_reply.started":"2026-09-11T10:01:55.181065Z","shell.execute_reply":"2026-09-11T10:01:55.194277Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:55.196337Z","iopub.execute_input":"2026-09-11T10:01:55.197038Z","iopub.status.idle":"2026-09-11T10:01:55.342925Z","shell.execute_reply.started":"2026-09-11T10:01:55.197013Z","shell.execute_reply":"2026-09-11T10:01:55.341777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:55.344160Z","iopub.execute_input":"2026-09-11T10:01:55.344481Z","iopub.status.idle":"2026-09-11T10:01:55.558509Z","shell.execute_reply.started":"2026-09-11T10:01:55.344451Z","shell.execute_reply":"2026-09-11T10:01:55.557629Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:55.562067Z","iopub.execute_input":"2026-09-11T10:01:55.562457Z","iopub.status.idle":"2026-09-11T10:01:55.740282Z","shell.execute_reply.started":"2026-09-11T10:01:55.562425Z","shell.execute_reply":"2026-09-11T10:01:55.739171Z"}},"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-11T10:01:55.741766Z","iopub.execute_input":"2026-09-11T10:01:55.742471Z","iopub.status.idle":"2026-09-11T10:01:56.392707Z","shell.execute_reply.started":"2026-09-11T10:01:55.742439Z","shell.execute_reply":"2026-09-11T10:01:56.391941Z"},"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-11T10:01:56.393677Z","iopub.execute_input":"2026-09-11T10:01:56.394325Z","iopub.status.idle":"2026-09-11T10:01:57.010069Z","shell.execute_reply.started":"2026-09-11T10:01:56.394299Z","shell.execute_reply":"2026-09-11T10:01:57.009310Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:57.011028Z","iopub.execute_input":"2026-09-11T10:01:57.011366Z","iopub.status.idle":"2026-09-11T10:01:57.155633Z","shell.execute_reply.started":"2026-09-11T10:01:57.011342Z","shell.execute_reply":"2026-09-11T10:01:57.154820Z"}},"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-11T10:01:57.156960Z","iopub.execute_input":"2026-09-11T10:01:57.157551Z","iopub.status.idle":"2026-09-11T10:01:57.162764Z","shell.execute_reply.started":"2026-09-11T10:01:57.157511Z","shell.execute_reply":"2026-09-11T10:01:57.161883Z"}},"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-11T10:01:57.163745Z","iopub.execute_input":"2026-09-11T10:01:57.163989Z","iopub.status.idle":"2026-09-11T10:01:57.185837Z","shell.execute_reply.started":"2026-09-11T10:01:57.163968Z","shell.execute_reply":"2026-09-11T10:01:57.185130Z"},"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-11T10:01:57.186836Z","iopub.execute_input":"2026-09-11T10:01:57.187130Z","iopub.status.idle":"2026-09-11T10:01:57.197709Z","shell.execute_reply.started":"2026-09-11T10:01:57.187099Z","shell.execute_reply":"2026-09-11T10:01:57.196919Z"},"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-11T10:01:57.198646Z","iopub.execute_input":"2026-09-11T10:01:57.198911Z","iopub.status.idle":"2026-09-11T10:01:57.210338Z","shell.execute_reply.started":"2026-09-11T10:01:57.198889Z","shell.execute_reply":"2026-09-11T10:01:57.209648Z"},"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-11T10:01:57.211177Z","iopub.execute_input":"2026-09-11T10:01:57.211594Z","iopub.status.idle":"2026-09-11T10:01:57.443579Z","shell.execute_reply.started":"2026-09-11T10:01:57.211563Z","shell.execute_reply":"2026-09-11T10:01:57.442776Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:57.445074Z","iopub.execute_input":"2026-09-11T10:01:57.445739Z","iopub.status.idle":"2026-09-11T10:01:57.587471Z","shell.execute_reply.started":"2026-09-11T10:01:57.445706Z","shell.execute_reply":"2026-09-11T10:01:57.586520Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:01:57.589063Z","iopub.execute_input":"2026-09-11T10:01:57.589445Z","iopub.status.idle":"2026-09-11T10:01:57.729656Z","shell.execute_reply.started":"2026-09-11T10:01:57.589390Z","shell.execute_reply":"2026-09-11T10:01:57.728860Z"}},"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-11T10:01:57.731076Z","iopub.execute_input":"2026-09-11T10:01:57.731466Z","iopub.status.idle":"2026-09-11T10:01:57.871084Z","shell.execute_reply.started":"2026-09-11T10:01:57.731434Z","shell.execute_reply":"2026-09-11T10:01:57.870294Z"}},"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-11T10:01:57.872594Z","iopub.execute_input":"2026-09-11T10:01:57.872948Z","iopub.status.idle":"2026-09-11T10:02:00.883860Z","shell.execute_reply.started":"2026-09-11T10:01:57.872920Z","shell.execute_reply":"2026-09-11T10:02:00.882903Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:02:00.884981Z","iopub.execute_input":"2026-09-11T10:02:00.885383Z","iopub.status.idle":"2026-09-11T10:02:00.890046Z","shell.execute_reply.started":"2026-09-11T10:02:00.885343Z","shell.execute_reply":"2026-09-11T10:02:00.889448Z"}},"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-11T10:02:03.106522Z","iopub.execute_input":"2026-09-11T10:02:03.106819Z","iopub.status.idle":"2026-09-11T10:02:03.623111Z","shell.execute_reply.started":"2026-09-11T10:02:03.106786Z","shell.execute_reply":"2026-09-11T10:02:03.622360Z"},"trusted":true},"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-11T10:02:00.891250Z","iopub.execute_input":"2026-09-11T10:02:00.891770Z","iopub.status.idle":"2026-09-11T10:02:03.103846Z","shell.execute_reply.started":"2026-09-11T10:02:00.891744Z","shell.execute_reply":"2026-09-11T10:02:03.102997Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-11T10:02:03.624397Z","iopub.execute_input":"2026-09-11T10:02:03.624746Z","iopub.status.idle":"2026-09-11T10:02:07.074139Z","shell.execute_reply.started":"2026-09-11T10:02:03.624713Z","shell.execute_reply":"2026-09-11T10:02:07.072774Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-11T11:21:31.002169Z","iopub.execute_input":"2026-09-11T11:21:31.003016Z","iopub.status.idle":"2026-09-11T11:21:31.015034Z","shell.execute_reply.started":"2026-09-11T11:21:31.002984Z","shell.execute_reply":"2026-09-11T11:21:31.014313Z"},"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-11T11:21:32.445176Z","iopub.execute_input":"2026-09-11T11:21:32.445547Z","iopub.status.idle":"2026-09-11T11:21:32.449409Z","shell.execute_reply.started":"2026-09-11T11:21:32.445521Z","shell.execute_reply":"2026-09-11T11:21:32.448399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.keras.callbacks import ModelCheckpoint","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:02.372751Z","iopub.execute_input":"2026-09-11T12:04:02.373524Z","iopub.status.idle":"2026-09-11T12:04:02.378127Z","shell.execute_reply.started":"2026-09-11T12:04:02.373496Z","shell.execute_reply":"2026-09-11T12:04:02.377470Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:02.601834Z","iopub.execute_input":"2026-09-11T12:04:02.602111Z","iopub.status.idle":"2026-09-11T12:04:02.609257Z","shell.execute_reply.started":"2026-09-11T12:04:02.602089Z","shell.execute_reply":"2026-09-11T12:04:02.608488Z"}},"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-11T12:04:02.830092Z","iopub.execute_input":"2026-09-11T12:04:02.830918Z","iopub.status.idle":"2026-09-11T12:04:02.884412Z","shell.execute_reply.started":"2026-09-11T12:04:02.830888Z","shell.execute_reply":"2026-09-11T12:04:02.883755Z"}},"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-11T12:04:03.002161Z","iopub.execute_input":"2026-09-11T12:04:03.002526Z","iopub.status.idle":"2026-09-11T12:04:03.057705Z","shell.execute_reply.started":"2026-09-11T12:04:03.002500Z","shell.execute_reply":"2026-09-11T12:04:03.057035Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n    model = Sequential()\n\n    # Layer 1\n    model.add(Conv2D(\n        32, (3, 3),\n        activation='relu',\n        kernel_initializer='he_uniform',\n        padding='same',\n        input_shape=(200, 200, 3)\n    ))\n\n    model.add(MaxPooling2D((2, 2)))\n\n    # Layer 2\n    model.add(Conv2D(\n        64, (3, 3),\n        activation='relu',\n        kernel_initializer='he_uniform',\n        padding='same'\n    ))\n\n    model.add(MaxPooling2D((2, 2)))\n\n    # เพิ่ม Layer 3\n    model.add(Conv2D(\n        128, (3, 3),\n        activation='relu',\n        kernel_initializer='he_uniform',\n        padding='same'\n    ))\n\n    model.add(MaxPooling2D((2, 2)))\n\n    # ลด overfitting\n    model.add(Dropout(0.3))\n\n    # ไม่ใช้ Flatten เพื่อป้องกัน GPU RAM เต็ม\n    model.add(GlobalAveragePooling2D())\n\n    model.add(Dense(\n        128,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    ))\n\n    model.add(Dropout(0.3))\n\n    model.add(Dense(\n        1,\n        activation='sigmoid'\n    ))\n\n    # compile model\n    opt = SGD(\n        learning_rate=0.001,\n        momentum=0.9\n    )\n\n    model.compile(\n        optimizer=opt,\n        loss='binary_crossentropy',\n        metrics=['accuracy']\n    )\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:03.181456Z","iopub.execute_input":"2026-09-11T12:04:03.182163Z","iopub.status.idle":"2026-09-11T12:04:03.188904Z","shell.execute_reply.started":"2026-09-11T12:04:03.182132Z","shell.execute_reply":"2026-09-11T12:04:03.188087Z"}},"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-11T12:04:03.348167Z","iopub.execute_input":"2026-09-11T12:04:03.349010Z","iopub.status.idle":"2026-09-11T12:04:03.451954Z","shell.execute_reply.started":"2026-09-11T12:04:03.348982Z","shell.execute_reply":"2026-09-11T12:04:03.451369Z"}},"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-11T12:04:03.470171Z","iopub.execute_input":"2026-09-11T12:04:03.470475Z","iopub.status.idle":"2026-09-11T12:04:03.477024Z","shell.execute_reply.started":"2026-09-11T12:04:03.470451Z","shell.execute_reply":"2026-09-11T12:04:03.476073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model, not recommend to call this function\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:03.633829Z","iopub.execute_input":"2026-09-11T12:04:03.634620Z","iopub.status.idle":"2026-09-11T12:04:03.640050Z","shell.execute_reply.started":"2026-09-11T12:04:03.634587Z","shell.execute_reply":"2026-09-11T12:04:03.639026Z"}},"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-11T12:04:03.791007Z","iopub.execute_input":"2026-09-11T12:04:03.791756Z","iopub.status.idle":"2026-09-11T12:04:03.894429Z","shell.execute_reply.started":"2026-09-11T12:04:03.791723Z","shell.execute_reply":"2026-09-11T12:04:03.893597Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    rotation_range=20,\n    width_shift_range=0.15,\n    height_shift_range=0.15,\n    zoom_range=0.15,\n    horizontal_flip=True\n)\ntype(datagen)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:03.936910Z","iopub.execute_input":"2026-09-11T12:04:03.937535Z","iopub.status.idle":"2026-09-11T12:04:03.942755Z","shell.execute_reply.started":"2026-09-11T12:04:03.937505Z","shell.execute_reply":"2026-09-11T12:04:03.942073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:04.089070Z","iopub.execute_input":"2026-09-11T12:04:04.089627Z","iopub.status.idle":"2026-09-11T12:04:04.260968Z","shell.execute_reply.started":"2026-09-11T12:04:04.089599Z","shell.execute_reply":"2026-09-11T12:04:04.260170Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hyperparameter => changable\nIMAGE_SIZE = (200, 200)\nBATCH_SIZE = 16\nEPOCHS = 50","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:04.262799Z","iopub.execute_input":"2026-09-11T12:04:04.263186Z","iopub.status.idle":"2026-09-11T12:04:04.267607Z","shell.execute_reply.started":"2026-09-11T12:04:04.263154Z","shell.execute_reply":"2026-09-11T12:04:04.266826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE,\n    shuffle=True\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:04.436559Z","iopub.execute_input":"2026-09-11T12:04:04.436826Z","iopub.status.idle":"2026-09-11T12:04:05.083255Z","shell.execute_reply.started":"2026-09-11T12:04:04.436805Z","shell.execute_reply":"2026-09-11T12:04:05.082626Z"}},"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-11T12:04:05.084483Z","iopub.execute_input":"2026-09-11T12:04:05.084868Z","iopub.status.idle":"2026-09-11T12:04:05.091060Z","shell.execute_reply.started":"2026-09-11T12:04:05.084845Z","shell.execute_reply":"2026-09-11T12:04:05.090130Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE,\n    shuffle=False\n)\ntype(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:05.092307Z","iopub.execute_input":"2026-09-11T12:04:05.092612Z","iopub.status.idle":"2026-09-11T12:04:05.297887Z","shell.execute_reply.started":"2026-09-11T12:04:05.092578Z","shell.execute_reply":"2026-09-11T12:04:05.297272Z"}},"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-11T12:04:05.299277Z","iopub.execute_input":"2026-09-11T12:04:05.299551Z","iopub.status.idle":"2026-09-11T12:04:05.305524Z","shell.execute_reply.started":"2026-09-11T12:04:05.299528Z","shell.execute_reply":"2026-09-11T12:04:05.304576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def define_model_1():\n    model = Sequential()\n\n    model.add(Conv2D(\n        32, (3, 3),\n        activation='relu',\n        kernel_initializer='he_uniform',\n        padding='same',\n        input_shape=(200, 200, 3)\n    ))\n\n    model.add(MaxPooling2D((2, 2)))\n\n    model.add(Conv2D(\n        64, (3, 3),\n        activation='relu',\n        kernel_initializer='he_uniform',\n        padding='same'\n    ))\n\n    model.add(MaxPooling2D((2, 2)))\n\n    model.add(Flatten())\n\n    model.add(Dense(\n        128,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    ))\n\n    model.add(Dense(1, activation='sigmoid'))\n\n    opt = SGD(\n        learning_rate=0.001,\n        momentum=0.9\n    )\n\n    model.compile(\n        optimizer=opt,\n        loss='binary_crossentropy',\n        metrics=['accuracy']\n    )\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T12:04:05.306681Z","iopub.execute_input":"2026-09-11T12:04:05.307506Z","iopub.status.idle":"2026-09-11T12:04:05.318388Z","shell.execute_reply.started":"2026-09-11T12:04:05.307479Z","shell.execute_reply":"2026-09-11T12:04:05.317759Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\n#model_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-11T12:04:06.468983Z","iopub.execute_input":"2026-09-11T12:04:06.469563Z","execution_failed":"2026-09-11T15:07:22.442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:18:26.092348Z","iopub.execute_input":"2026-09-11T10:18:26.092614Z","iopub.status.idle":"2026-09-11T10:18:26.294888Z","shell.execute_reply.started":"2026-09-11T10:18:26.092592Z","shell.execute_reply":"2026-09-11T10:18:26.294278Z"}},"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-11T10:20:09.752382Z","iopub.execute_input":"2026-09-11T10:20:09.753202Z","iopub.status.idle":"2026-09-11T10:20:19.555468Z","shell.execute_reply.started":"2026-09-11T10:20:09.753173Z","shell.execute_reply":"2026-09-11T10:20:19.554750Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:19.556650Z","iopub.execute_input":"2026-09-11T10:20:19.556979Z","iopub.status.idle":"2026-09-11T10:20:19.734668Z","shell.execute_reply.started":"2026-09-11T10:20:19.556939Z","shell.execute_reply":"2026-09-11T10:20:19.733549Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:19.736264Z","iopub.execute_input":"2026-09-11T10:20:19.736897Z","iopub.status.idle":"2026-09-11T10:20:19.743164Z","shell.execute_reply.started":"2026-09-11T10:20:19.736866Z","shell.execute_reply":"2026-09-11T10:20:19.742266Z"}},"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-11T10:20:21.518955Z","iopub.execute_input":"2026-09-11T10:20:21.519524Z","iopub.status.idle":"2026-09-11T10:20:21.554356Z","shell.execute_reply.started":"2026-09-11T10:20:21.519491Z","shell.execute_reply":"2026-09-11T10:20:21.553746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:21.845324Z","iopub.execute_input":"2026-09-11T10:20:21.845793Z","iopub.status.idle":"2026-09-11T10:20:21.851604Z","shell.execute_reply.started":"2026-09-11T10:20:21.845745Z","shell.execute_reply":"2026-09-11T10:20:21.850902Z"}},"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-11T10:20:22.125519Z","iopub.execute_input":"2026-09-11T10:20:22.125951Z","iopub.status.idle":"2026-09-11T10:20:22.131719Z","shell.execute_reply.started":"2026-09-11T10:20:22.125921Z","shell.execute_reply":"2026-09-11T10:20:22.131040Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:22.326959Z","iopub.execute_input":"2026-09-11T10:20:22.327628Z","iopub.status.idle":"2026-09-11T10:20:22.371772Z","shell.execute_reply.started":"2026-09-11T10:20:22.327598Z","shell.execute_reply":"2026-09-11T10:20:22.370822Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:22.522868Z","iopub.execute_input":"2026-09-11T10:20:22.523547Z","iopub.status.idle":"2026-09-11T10:20:22.529929Z","shell.execute_reply.started":"2026-09-11T10:20:22.523515Z","shell.execute_reply":"2026-09-11T10:20:22.529127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:22.693900Z","iopub.execute_input":"2026-09-11T10:20:22.694701Z","iopub.status.idle":"2026-09-11T10:20:22.708071Z","shell.execute_reply.started":"2026-09-11T10:20:22.694661Z","shell.execute_reply":"2026-09-11T10:20:22.707260Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:28.136453Z","iopub.execute_input":"2026-09-11T10:20:28.137160Z","iopub.status.idle":"2026-09-11T10:20:28.145277Z","shell.execute_reply.started":"2026-09-11T10:20:28.137128Z","shell.execute_reply":"2026-09-11T10:20:28.144452Z"}},"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)\nw\ntype(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:28.337947Z","iopub.execute_input":"2026-09-11T10:20:28.338388Z","iopub.status.idle":"2026-09-11T10:20:28.421995Z","shell.execute_reply.started":"2026-09-11T10:20:28.338359Z","shell.execute_reply":"2026-09-11T10:20:28.421317Z"}},"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-11T10:20:28.516361Z","iopub.execute_input":"2026-09-11T10:20:28.516789Z","iopub.status.idle":"2026-09-11T10:20:28.522443Z","shell.execute_reply.started":"2026-09-11T10:20:28.516760Z","shell.execute_reply":"2026-09-11T10:20:28.521544Z"}},"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-11T10:20:28.692256Z","iopub.execute_input":"2026-09-11T10:20:28.692710Z","iopub.status.idle":"2026-09-11T10:20:32.422866Z","shell.execute_reply.started":"2026-09-11T10:20:28.692683Z","shell.execute_reply":"2026-09-11T10:20:32.421476Z"}},"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-11T10:20:32.424973Z","iopub.execute_input":"2026-09-11T10:20:32.425419Z","iopub.status.idle":"2026-09-11T10:20:34.762936Z","shell.execute_reply.started":"2026-09-11T10:20:32.425347Z","shell.execute_reply":"2026-09-11T10:20:34.761874Z"}},"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-11T10:20:34.764330Z","iopub.execute_input":"2026-09-11T10:20:34.764633Z","iopub.status.idle":"2026-09-11T10:20:34.773114Z","shell.execute_reply.started":"2026-09-11T10:20:34.764601Z","shell.execute_reply":"2026-09-11T10:20:34.772131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()  # หรือ next(test_it)\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple_test(test_images, indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:20:34.775650Z","iopub.execute_input":"2026-09-11T10:20:34.775974Z","iopub.status.idle":"2026-09-11T10:20:38.471584Z","shell.execute_reply.started":"2026-09-11T10:20:34.775950Z","shell.execute_reply":"2026-09-11T10:20:38.469732Z"}},"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-11T10:20:38.472800Z","iopub.execute_input":"2026-09-11T10:20:38.473187Z","iopub.status.idle":"2026-09-11T10:21:00.291950Z","shell.execute_reply.started":"2026-09-11T10:20:38.473130Z","shell.execute_reply":"2026-09-11T10:21:00.291012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:21:00.293069Z","iopub.execute_input":"2026-09-11T10:21:00.293418Z","iopub.status.idle":"2026-09-11T10:21:00.299801Z","shell.execute_reply.started":"2026-09-11T10:21:00.293393Z","shell.execute_reply":"2026-09-11T10:21:00.298770Z"}},"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-11T10:21:00.301275Z","iopub.execute_input":"2026-09-11T10:21:00.301603Z","iopub.status.idle":"2026-09-11T10:21:01.992126Z","shell.execute_reply.started":"2026-09-11T10:21:00.301566Z","shell.execute_reply":"2026-09-11T10:21:01.990897Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# end of 2026-09-06\nstop here","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:21:01.993300Z","iopub.execute_input":"2026-09-11T10:21:01.993844Z","iopub.status.idle":"2026-09-11T10:21:01.999244Z","shell.execute_reply.started":"2026-09-11T10:21:01.993820Z","shell.execute_reply":"2026-09-11T10:21:01.997895Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:21:08.471515Z","iopub.execute_input":"2026-09-11T10:21:08.471819Z","iopub.status.idle":"2026-09-11T10:21:08.476040Z","shell.execute_reply.started":"2026-09-11T10:21:08.471793Z","shell.execute_reply":"2026-09-11T10:21:08.475237Z"}},"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-11T10:21:08.662638Z","iopub.execute_input":"2026-09-11T10:21:08.663175Z","iopub.status.idle":"2026-09-11T10:21:08.672631Z","shell.execute_reply.started":"2026-09-11T10:21:08.663144Z","shell.execute_reply":"2026-09-11T10:21:08.671623Z"}},"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-11T10:21:08.811357Z","iopub.execute_input":"2026-09-11T10:21:08.811754Z","iopub.status.idle":"2026-09-11T10:21:08.815581Z","shell.execute_reply.started":"2026-09-11T10:21:08.811727Z","shell.execute_reply":"2026-09-11T10:21:08.814953Z"}},"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-11T10:21:09.004964Z","iopub.execute_input":"2026-09-11T10:21:09.005573Z","iopub.status.idle":"2026-09-11T10:21:09.009100Z","shell.execute_reply.started":"2026-09-11T10:21:09.005541Z","shell.execute_reply":"2026-09-11T10:21:09.008271Z"}},"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-11T10:21:09.183924Z","iopub.execute_input":"2026-09-11T10:21:09.184546Z","iopub.status.idle":"2026-09-11T10:21:09.187854Z","shell.execute_reply.started":"2026-09-11T10:21:09.184513Z","shell.execute_reply":"2026-09-11T10:21:09.187119Z"}},"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-11T10:21:09.383335Z","iopub.execute_input":"2026-09-11T10:21:09.383717Z","iopub.status.idle":"2026-09-11T10:21:09.387186Z","shell.execute_reply.started":"2026-09-11T10:21:09.383690Z","shell.execute_reply":"2026-09-11T10:21:09.386608Z"}},"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-11T10:21:09.733212Z","iopub.execute_input":"2026-09-11T10:21:09.733975Z","iopub.status.idle":"2026-09-11T10:21:09.739659Z","shell.execute_reply.started":"2026-09-11T10:21:09.733947Z","shell.execute_reply":"2026-09-11T10:21:09.738484Z"}},"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-11T10:21:13.264517Z","iopub.execute_input":"2026-09-11T10:21:13.265064Z","iopub.status.idle":"2026-09-11T10:21:13.268291Z","shell.execute_reply.started":"2026-09-11T10:21:13.265035Z","shell.execute_reply":"2026-09-11T10:21:13.267436Z"}},"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-11T10:21:13.453731Z","iopub.execute_input":"2026-09-11T10:21:13.454481Z","iopub.status.idle":"2026-09-11T10:21:13.457696Z","shell.execute_reply.started":"2026-09-11T10:21:13.454450Z","shell.execute_reply":"2026-09-11T10:21:13.456965Z"}},"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-11T10:21:13.616998Z","iopub.execute_input":"2026-09-11T10:21:13.617578Z","iopub.status.idle":"2026-09-11T10:21:13.620911Z","shell.execute_reply.started":"2026-09-11T10:21:13.617547Z","shell.execute_reply":"2026-09-11T10:21:13.620294Z"}},"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-11T10:21:13.757821Z","iopub.execute_input":"2026-09-11T10:21:13.758617Z","iopub.status.idle":"2026-09-11T10:21:13.761833Z","shell.execute_reply.started":"2026-09-11T10:21:13.758586Z","shell.execute_reply":"2026-09-11T10:21:13.761273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:21:14.055375Z","iopub.execute_input":"2026-09-11T10:21:14.055889Z","iopub.status.idle":"2026-09-11T10:21:14.061619Z","shell.execute_reply.started":"2026-09-11T10:21:14.055861Z","shell.execute_reply":"2026-09-11T10:21:14.060683Z"}},"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-11T10:21:14.210142Z","iopub.execute_input":"2026-09-11T10:21:14.210464Z","iopub.status.idle":"2026-09-11T10:21:14.217787Z","shell.execute_reply.started":"2026-09-11T10:21:14.210431Z","shell.execute_reply":"2026-09-11T10:21:14.216846Z"}},"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-11T10:21:14.347424Z","iopub.execute_input":"2026-09-11T10:21:14.347775Z","iopub.status.idle":"2026-09-11T10:21:14.354840Z","shell.execute_reply.started":"2026-09-11T10:21:14.347749Z","shell.execute_reply":"2026-09-11T10:21:14.353691Z"}},"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-11T10:21:14.778955Z","iopub.execute_input":"2026-09-11T10:21:14.779545Z","iopub.status.idle":"2026-09-11T10:21:14.785516Z","shell.execute_reply.started":"2026-09-11T10:21:14.779514Z","shell.execute_reply":"2026-09-11T10:21:14.784701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-09-11T10:21:18.514595Z","iopub.execute_input":"2026-09-11T10:21:18.515009Z","iopub.status.idle":"2026-09-11T10:21:20.975787Z","shell.execute_reply.started":"2026-09-11T10:21:18.514980Z","shell.execute_reply":"2026-09-11T10:21:20.974581Z"},"trusted":true},"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-11T10:21:20.976296Z","iopub.status.idle":"2026-09-11T10:21:20.976529Z","shell.execute_reply.started":"2026-09-11T10:21:20.976413Z","shell.execute_reply":"2026-09-11T10:21:20.976431Z"}},"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-11T10:21:20.977791Z","iopub.status.idle":"2026-09-11T10:21:20.978165Z","shell.execute_reply.started":"2026-09-11T10:21:20.977983Z","shell.execute_reply":"2026-09-11T10:21:20.978005Z"}},"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-11T10:21:20.979429Z","iopub.status.idle":"2026-09-11T10:21:20.979840Z","shell.execute_reply.started":"2026-09-11T10:21:20.979610Z","shell.execute_reply":"2026-09-11T10:21:20.979635Z"}},"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-11T10:21:20.981241Z","iopub.status.idle":"2026-09-11T10:21:20.981535Z","shell.execute_reply.started":"2026-09-11T10:21:20.981408Z","shell.execute_reply":"2026-09-11T10:21:20.981427Z"}},"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-11T10:02:07.438533Z","iopub.status.idle":"2026-09-11T10:02:07.438902Z","shell.execute_reply.started":"2026-09-11T10:02:07.438747Z","shell.execute_reply":"2026-09-11T10:02:07.438763Z"}},"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-11T10:02:07.440153Z","iopub.status.idle":"2026-09-11T10:02:07.440529Z","shell.execute_reply.started":"2026-09-11T10:02:07.440390Z","shell.execute_reply":"2026-09-11T10:02:07.440408Z"}},"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-11T10:02:07.441505Z","iopub.status.idle":"2026-09-11T10:02:07.441724Z","shell.execute_reply.started":"2026-09-11T10:02:07.441616Z","shell.execute_reply":"2026-09-11T10:02:07.441629Z"}},"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-11T10:02:07.443010Z","iopub.status.idle":"2026-09-11T10:02:07.443379Z","shell.execute_reply.started":"2026-09-11T10:02:07.443249Z","shell.execute_reply":"2026-09-11T10:02:07.443274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:02:07.444707Z","iopub.status.idle":"2026-09-11T10:02:07.445093Z","shell.execute_reply.started":"2026-09-11T10:02:07.444863Z","shell.execute_reply":"2026-09-11T10:02:07.444898Z"}},"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-11T10:02:07.446192Z","iopub.status.idle":"2026-09-11T10:02:07.446489Z","shell.execute_reply.started":"2026-09-11T10:02:07.446377Z","shell.execute_reply":"2026-09-11T10:02:07.446392Z"}},"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-11T10:02:07.447478Z","iopub.status.idle":"2026-09-11T10:02:07.447797Z","shell.execute_reply.started":"2026-09-11T10:02:07.447635Z","shell.execute_reply":"2026-09-11T10:02:07.447651Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Final Model — Target Validation Accuracy ≥ 0.85","metadata":{}},{"cell_type":"code","source":"# Plot training/validation accuracy and loss\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history_final.history['accuracy'], label='train accuracy')\nplt.plot(history_final.history['val_accuracy'], label='val accuracy')\nplt.axhline(0.85, linestyle='--', label='target 0.85')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.title('Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(history_final.history['loss'], label='train loss')\nplt.plot(history_final.history['val_loss'], label='val loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.title('Loss')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:02:07.456654Z","iopub.status.idle":"2026-09-11T10:02:07.456986Z","shell.execute_reply.started":"2026-09-11T10:02:07.456809Z","shell.execute_reply":"2026-09-11T10:02:07.456831Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Random Test Prediction — 10 Images\n\nสุ่มรูปจาก `test1` จำนวน 10 รูป แล้วให้โมเดลทำนายว่าเป็น Cat หรือ Dog","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.utils import load_img, img_to_array\n\n# test1 is the unlabeled test group from the original notebook\ntest_folder = '/kaggle/working/test1'\ntest_files = sorted([\n    os.path.join(test_folder, f)\n    for f in os.listdir(test_folder)\n    if f.lower().endswith(('.jpg', '.jpeg', '.png'))\n])\n\nif len(test_files) < 10:\n    raise ValueError(f'Need at least 10 test images, but found {len(test_files)}')\n\nrng = np.random.default_rng(1337)\nsample_files = list(rng.choice(test_files, size=10, replace=False))\n            \nsample_images = []\nfor path in sample_files:\n    img = load_img(path, target_size=IMAGE_SIZE)\n    arr = img_to_array(img)\n    arr = preprocess_input(arr)\n    sample_images.append(arr)\n            \nsample_images = np.stack(sample_images)\n            \nprobs = model_final.predict(sample_images, verbose=0).reshape(-1)\nclass_names = {0: 'Cat', 1: 'Dog'}\npredicted_classes = (probs >= 0.5).astype(int)\n            \n            \nfig, axes = plt.subplots(2, 5, figsize=(16, 7))\naxes = axes.flatten()\n            \nfor i, (path, prob, pred) in enumerate(zip(sample_files, probs, predicted_classes)):\n    # Load original image for display\n    display_img = load_img(path)\n    axes[i].imshow(display_img)\n    label = class_names[int(pred)]\n    confidence = prob if pred == 1 else 1 - prob\n    filename = os.path.basename(path)\n    axes[i].set_title(f'{filename}\\nPred: {label} ({confidence*100:.1f}%)')\n    axes[i].axis('off')\n            \nplt.suptitle('Random 10 Test Images — Dog/Cat Prediction')\nplt.tight_layout()\nplt.show()\n            \nprint('Prediction results:')\nfor path, prob, pred in zip(sample_files, probs, predicted_classes):\n    label = class_names[int(pred)]\n    confidence = prob if pred == 1 else 1 - prob\n    print(f'{os.path.basename(path):20s} -> {label:3s}  confidence={confidence*100:.2f}%')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T10:02:07.458322Z","iopub.status.idle":"2026-09-11T10:02:07.458618Z","shell.execute_reply.started":"2026-09-11T10:02:07.458484Z","shell.execute_reply":"2026-09-11T10:02:07.458508Z"}},"outputs":[],"execution_count":null}]}