{"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-12T13:44:47.017434Z","iopub.execute_input":"2026-09-12T13:44:47.018225Z","iopub.status.idle":"2026-09-12T13:44:47.024672Z","shell.execute_reply.started":"2026-09-12T13:44:47.018193Z","shell.execute_reply":"2026-09-12T13:44:47.023638Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:47.026393Z","iopub.execute_input":"2026-09-12T13:44:47.026688Z","iopub.status.idle":"2026-09-12T13:44:48.098174Z","shell.execute_reply.started":"2026-09-12T13:44:47.026665Z","shell.execute_reply":"2026-09-12T13:44:48.097074Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:48.100052Z","iopub.execute_input":"2026-09-12T13:44:48.100392Z","iopub.status.idle":"2026-09-12T13:44:49.151637Z","shell.execute_reply.started":"2026-09-12T13:44:48.100364Z","shell.execute_reply":"2026-09-12T13:44:49.150302Z"}},"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-12T13:44:49.153302Z","iopub.execute_input":"2026-09-12T13:44:49.153619Z","iopub.status.idle":"2026-09-12T13:44:59.205093Z","shell.execute_reply.started":"2026-09-12T13:44:49.153592Z","shell.execute_reply":"2026-09-12T13:44:59.204312Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:59.207154Z","iopub.execute_input":"2026-09-12T13:44:59.20745Z","iopub.status.idle":"2026-09-12T13:45:00.279833Z","shell.execute_reply.started":"2026-09-12T13:44:59.207426Z","shell.execute_reply":"2026-09-12T13:45:00.278403Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:00.281786Z","iopub.execute_input":"2026-09-12T13:45:00.282222Z","iopub.status.idle":"2026-09-12T13:45:01.423681Z","shell.execute_reply.started":"2026-09-12T13:45:00.282186Z","shell.execute_reply":"2026-09-12T13:45:01.422633Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:01.425346Z","iopub.execute_input":"2026-09-12T13:45:01.425687Z","iopub.status.idle":"2026-09-12T13:45:02.696459Z","shell.execute_reply.started":"2026-09-12T13:45:01.425656Z","shell.execute_reply":"2026-09-12T13:45:02.695451Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:02.697738Z","iopub.execute_input":"2026-09-12T13:45:02.69811Z","iopub.status.idle":"2026-09-12T13:45:03.787336Z","shell.execute_reply.started":"2026-09-12T13:45:02.698062Z","shell.execute_reply":"2026-09-12T13:45:03.785845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:03.789214Z","iopub.execute_input":"2026-09-12T13:45:03.789564Z","iopub.status.idle":"2026-09-12T13:45:04.944045Z","shell.execute_reply.started":"2026-09-12T13:45:03.789535Z","shell.execute_reply":"2026-09-12T13:45:04.942982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:04.945524Z","iopub.execute_input":"2026-09-12T13:45:04.94579Z","iopub.status.idle":"2026-09-12T13:45:04.950601Z","shell.execute_reply.started":"2026-09-12T13:45:04.945766Z","shell.execute_reply":"2026-09-12T13:45:04.949597Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:04.952247Z","iopub.execute_input":"2026-09-12T13:45:04.952582Z","iopub.status.idle":"2026-09-12T13:45:04.963046Z","shell.execute_reply.started":"2026-09-12T13:45:04.952558Z","shell.execute_reply":"2026-09-12T13:45:04.962064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:04.964458Z","iopub.execute_input":"2026-09-12T13:45:04.96535Z","iopub.status.idle":"2026-09-12T13:45:06.024318Z","shell.execute_reply.started":"2026-09-12T13:45:04.965324Z","shell.execute_reply":"2026-09-12T13:45:06.023315Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:06.025892Z","iopub.execute_input":"2026-09-12T13:45:06.026267Z","iopub.status.idle":"2026-09-12T13:45:07.161651Z","shell.execute_reply.started":"2026-09-12T13:45:06.026231Z","shell.execute_reply":"2026-09-12T13:45:07.160444Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:07.167303Z","iopub.execute_input":"2026-09-12T13:45:07.167685Z","iopub.status.idle":"2026-09-12T13:45:08.300359Z","shell.execute_reply.started":"2026-09-12T13:45:07.167655Z","shell.execute_reply":"2026-09-12T13:45:08.299318Z"}},"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-12T13:45:08.301807Z","iopub.execute_input":"2026-09-12T13:45:08.30264Z","iopub.status.idle":"2026-09-12T13:45:09.368945Z","shell.execute_reply.started":"2026-09-12T13:45:08.302609Z","shell.execute_reply":"2026-09-12T13:45:09.368045Z"},"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-12T13:45:09.370334Z","iopub.execute_input":"2026-09-12T13:45:09.370902Z","iopub.status.idle":"2026-09-12T13:45:10.414837Z","shell.execute_reply.started":"2026-09-12T13:45:09.370873Z","shell.execute_reply":"2026-09-12T13:45:10.413964Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:10.416415Z","iopub.execute_input":"2026-09-12T13:45:10.416806Z","iopub.status.idle":"2026-09-12T13:45:11.4626Z","shell.execute_reply.started":"2026-09-12T13:45:10.416768Z","shell.execute_reply":"2026-09-12T13:45:11.461517Z"}},"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-12T13:45:11.464185Z","iopub.execute_input":"2026-09-12T13:45:11.464543Z","iopub.status.idle":"2026-09-12T13:45:11.471325Z","shell.execute_reply.started":"2026-09-12T13:45:11.464514Z","shell.execute_reply":"2026-09-12T13:45:11.47021Z"}},"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-12T13:45:11.472695Z","iopub.execute_input":"2026-09-12T13:45:11.473051Z","iopub.status.idle":"2026-09-12T13:45:11.480496Z","shell.execute_reply.started":"2026-09-12T13:45:11.472985Z","shell.execute_reply":"2026-09-12T13:45:11.479653Z"},"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-12T13:45:11.481818Z","iopub.execute_input":"2026-09-12T13:45:11.482204Z","iopub.status.idle":"2026-09-12T13:45:11.490755Z","shell.execute_reply.started":"2026-09-12T13:45:11.482169Z","shell.execute_reply":"2026-09-12T13:45:11.48966Z"},"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-12T13:45:11.492072Z","iopub.execute_input":"2026-09-12T13:45:11.492473Z","iopub.status.idle":"2026-09-12T13:45:11.500909Z","shell.execute_reply.started":"2026-09-12T13:45:11.492441Z","shell.execute_reply":"2026-09-12T13:45:11.499826Z"},"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-12T13:45:11.502169Z","iopub.execute_input":"2026-09-12T13:45:11.502709Z","iopub.status.idle":"2026-09-12T13:45:12.638579Z","shell.execute_reply.started":"2026-09-12T13:45:11.502685Z","shell.execute_reply":"2026-09-12T13:45:12.637496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:12.640144Z","iopub.execute_input":"2026-09-12T13:45:12.640574Z","iopub.status.idle":"2026-09-12T13:45:13.68888Z","shell.execute_reply.started":"2026-09-12T13:45:12.640544Z","shell.execute_reply":"2026-09-12T13:45:13.687805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:13.690495Z","iopub.execute_input":"2026-09-12T13:45:13.690843Z","iopub.status.idle":"2026-09-12T13:45:14.757242Z","shell.execute_reply.started":"2026-09-12T13:45:13.690813Z","shell.execute_reply":"2026-09-12T13:45:14.756109Z"}},"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-12T13:45:14.758927Z","iopub.execute_input":"2026-09-12T13:45:14.759369Z","iopub.status.idle":"2026-09-12T13:45:15.820147Z","shell.execute_reply.started":"2026-09-12T13:45:14.759329Z","shell.execute_reply":"2026-09-12T13:45:15.81876Z"}},"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-12T13:45:15.821947Z","iopub.execute_input":"2026-09-12T13:45:15.82233Z","iopub.status.idle":"2026-09-12T13:45:19.610803Z","shell.execute_reply.started":"2026-09-12T13:45:15.822299Z","shell.execute_reply":"2026-09-12T13:45:19.609964Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:45:19.612086Z","iopub.execute_input":"2026-09-12T13:45:19.612393Z","iopub.status.idle":"2026-09-12T13:45:19.617205Z","shell.execute_reply.started":"2026-09-12T13:45:19.612368Z","shell.execute_reply":"2026-09-12T13:45:19.61617Z"}},"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-12T13:45:19.618553Z","iopub.execute_input":"2026-09-12T13:45:19.618795Z","iopub.status.idle":"2026-09-12T13:45:21.993911Z","shell.execute_reply.started":"2026-09-12T13:45:19.618773Z","shell.execute_reply":"2026-09-12T13:45:21.992448Z"},"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-12T13:45:21.995721Z","iopub.execute_input":"2026-09-12T13:45:21.996914Z","iopub.status.idle":"2026-09-12T13:45:24.194205Z","shell.execute_reply.started":"2026-09-12T13:45:21.996881Z","shell.execute_reply":"2026-09-12T13:45:24.193113Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-12T13:45:24.195784Z","iopub.execute_input":"2026-09-12T13:45:24.1966Z","iopub.status.idle":"2026-09-12T13:45:33.21285Z","shell.execute_reply.started":"2026-09-12T13:45:24.19657Z","shell.execute_reply":"2026-09-12T13:45:33.211368Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-12T13:45:33.21472Z","iopub.execute_input":"2026-09-12T13:45:33.215473Z","iopub.status.idle":"2026-09-12T13:45:33.219824Z","shell.execute_reply.started":"2026-09-12T13:45:33.215443Z","shell.execute_reply":"2026-09-12T13:45:33.218884Z"},"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-12T13:45:33.221272Z","iopub.execute_input":"2026-09-12T13:45:33.221931Z","iopub.status.idle":"2026-09-12T13:45:33.230749Z","shell.execute_reply.started":"2026-09-12T13:45:33.221908Z","shell.execute_reply":"2026-09-12T13:45:33.22979Z"}},"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 Dropout\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-12T14:45:31.862235Z","iopub.execute_input":"2026-09-12T14:45:31.862589Z","iopub.status.idle":"2026-09-12T14:45:31.868059Z","shell.execute_reply.started":"2026-09-12T14:45:31.862565Z","shell.execute_reply":"2026-09-12T14:45:31.866845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:37:49.04866Z","iopub.execute_input":"2026-09-12T15:37:49.049371Z","iopub.status.idle":"2026-09-12T15:37:49.05874Z","shell.execute_reply.started":"2026-09-12T15:37:49.049335Z","shell.execute_reply":"2026-09-12T15:37:49.057893Z"}},"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-12T15:37:58.674567Z","iopub.execute_input":"2026-09-12T15:37:58.675321Z","iopub.status.idle":"2026-09-12T15:37:58.742914Z","shell.execute_reply.started":"2026-09-12T15:37:58.675285Z","shell.execute_reply":"2026-09-12T15:37:58.740082Z"}},"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-12T15:38:02.269025Z","iopub.execute_input":"2026-09-12T15:38:02.269757Z","iopub.status.idle":"2026-09-12T15:38:02.338429Z","shell.execute_reply.started":"2026-09-12T15:38:02.269721Z","shell.execute_reply":"2026-09-12T15:38:02.337378Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(256, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dropout(0.2))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # compile model\n    opt = 'adam'\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:38:10.601503Z","iopub.execute_input":"2026-09-12T15:38:10.602449Z","iopub.status.idle":"2026-09-12T15:38:10.609153Z","shell.execute_reply.started":"2026-09-12T15:38:10.602412Z","shell.execute_reply":"2026-09-12T15:38:10.608288Z"}},"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-12T15:38:12.872324Z","iopub.execute_input":"2026-09-12T15:38:12.873062Z","iopub.status.idle":"2026-09-12T15:38:12.949244Z","shell.execute_reply.started":"2026-09-12T15:38:12.872982Z","shell.execute_reply":"2026-09-12T15:38:12.948201Z"}},"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-12T15:38:13.114141Z","iopub.execute_input":"2026-09-12T15:38:13.114882Z","iopub.status.idle":"2026-09-12T15:38:13.121637Z","shell.execute_reply.started":"2026-09-12T15:38:13.114849Z","shell.execute_reply":"2026-09-12T15:38:13.120475Z"}},"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-12T15:38:13.317404Z","iopub.execute_input":"2026-09-12T15:38:13.317775Z","iopub.status.idle":"2026-09-12T15:38:13.324636Z","shell.execute_reply.started":"2026-09-12T15:38:13.317748Z","shell.execute_reply":"2026-09-12T15:38:13.323539Z"}},"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-12T15:38:13.477431Z","iopub.execute_input":"2026-09-12T15:38:13.478252Z","iopub.status.idle":"2026-09-12T15:38:13.553659Z","shell.execute_reply.started":"2026-09-12T15:38:13.478216Z","shell.execute_reply":"2026-09-12T15:38:13.55266Z"}},"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-12T15:38:16.579231Z","iopub.execute_input":"2026-09-12T15:38:16.579657Z","iopub.status.idle":"2026-09-12T15:38:16.586519Z","shell.execute_reply.started":"2026-09-12T15:38:16.579626Z","shell.execute_reply":"2026-09-12T15:38:16.585458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:38:16.856856Z","iopub.execute_input":"2026-09-12T15:38:16.857757Z","iopub.status.idle":"2026-09-12T15:38:17.949747Z","shell.execute_reply.started":"2026-09-12T15:38:16.857722Z","shell.execute_reply":"2026-09-12T15:38:17.948269Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hyperparameter => changable\nIMAGE_SIZE = (200, 200)\nBATCH_SIZE = 64\nEPOCHS = 20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:38:17.952569Z","iopub.execute_input":"2026-09-12T15:38:17.952965Z","iopub.status.idle":"2026-09-12T15:38:17.957925Z","shell.execute_reply.started":"2026-09-12T15:38:17.952932Z","shell.execute_reply":"2026-09-12T15:38:17.956988Z"}},"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-12T15:38:17.959334Z","iopub.execute_input":"2026-09-12T15:38:17.96101Z","iopub.status.idle":"2026-09-12T15:38:18.478888Z","shell.execute_reply.started":"2026-09-12T15:38:17.960951Z","shell.execute_reply":"2026-09-12T15:38:18.477723Z"}},"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-12T15:38:18.480714Z","iopub.execute_input":"2026-09-12T15:38:18.481103Z","iopub.status.idle":"2026-09-12T15:38:18.48835Z","shell.execute_reply.started":"2026-09-12T15:38:18.481073Z","shell.execute_reply":"2026-09-12T15:38:18.487412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# BATCH_SIZE = 32\n# IMAGE_SIZE = (150, 150)\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_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-12T15:38:19.521767Z","iopub.execute_input":"2026-09-12T15:38:19.522443Z","iopub.status.idle":"2026-09-12T15:38:19.70652Z","shell.execute_reply.started":"2026-09-12T15:38:19.522407Z","shell.execute_reply":"2026-09-12T15:38:19.705287Z"}},"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-12T15:38:19.885772Z","iopub.execute_input":"2026-09-12T15:38:19.88659Z","iopub.status.idle":"2026-09-12T15:38:19.893763Z","shell.execute_reply.started":"2026-09-12T15:38:19.886553Z","shell.execute_reply":"2026-09-12T15:38:19.89278Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nx_batch, y_batch = next(iter(train_it))\nprint(\"Batch input shape:\", x_batch.shape)\nmodel_1.reset_states()\nmodel_1.summary()\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-12T15:38:20.650164Z","iopub.execute_input":"2026-09-12T15:38:20.650953Z","iopub.status.idle":"2026-09-12T15:53:27.457285Z","shell.execute_reply.started":"2026-09-12T15:38:20.650919Z","shell.execute_reply":"2026-09-12T15:53:27.456151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"del model_1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:37:36.087418Z","iopub.execute_input":"2026-09-12T15:37:36.087743Z","iopub.status.idle":"2026-09-12T15:37:36.092544Z","shell.execute_reply.started":"2026-09-12T15:37:36.087717Z","shell.execute_reply":"2026-09-12T15:37:36.091436Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. ดึงข้อมูลตัวอย่างมา 1 Batch จาก val_it\nx_val, y_val = next(iter(val_it))\n\n# 2. ให้โมเดลทำนายผล\npredictions = model_1.predict(x_val)\n\n# 3. แปลงคลาสจากตัวเลขเป็นข้อความ\nclass_labels = {v: k for k, v in val_it.class_indices.items()} # {0: 'cats', 1: 'dogs'}\n\n# 4. วาดกราฟแสดงผล 10 ภาพแรก\nplt.figure(figsize=(15, 6))\n\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(x_val[i])\n    \n    # ดึงค่า True และ Predicted Label\n    true_label = class_labels[int(y_val[i])]\n    pred_prob = predictions[i][0]\n    pred_label = class_labels[1 if pred_prob > 0.5 else 0]\n    \n    # กำหนดสีข้อความ: ทายถูก = สีเขียว, ทายผิด = สีแดง\n    color = 'green' if true_label == pred_label else 'red'\n    \n    plt.title(f\"Pred: {pred_label}\\nTrue: {true_label}\", color=color)\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:13:28.053283Z","iopub.execute_input":"2026-09-12T16:13:28.053977Z","iopub.status.idle":"2026-09-12T16:13:29.770959Z","shell.execute_reply.started":"2026-09-12T16:13:28.053931Z","shell.execute_reply":"2026-09-12T16:13:29.769935Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:13:58.082964Z","iopub.execute_input":"2026-09-12T16:13:58.083334Z","iopub.status.idle":"2026-09-12T16:13:58.454543Z","shell.execute_reply.started":"2026-09-12T16:13:58.083305Z","shell.execute_reply":"2026-09-12T16:13:58.453754Z"}},"outputs":[],"execution_count":null},{"cell_type":"raw","source":"# evaluate model\n_, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"execution":{"iopub.status.busy":"2026-09-11T14:59:13.682803Z","iopub.execute_input":"2026-09-11T14:59:13.683586Z","iopub.status.idle":"2026-09-11T14:59:14.358752Z","shell.execute_reply.started":"2026-09-11T14:59:13.683554Z","shell.execute_reply":"2026-09-11T14:59:14.357399Z"}}},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:02.642282Z","iopub.execute_input":"2026-09-12T16:14:02.643113Z","iopub.status.idle":"2026-09-12T16:14:03.720591Z","shell.execute_reply.started":"2026-09-12T16:14:02.643077Z","shell.execute_reply":"2026-09-12T16:14:03.719265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:03.793421Z","iopub.execute_input":"2026-09-12T16:14:03.794329Z","iopub.status.idle":"2026-09-12T16:14:03.80253Z","shell.execute_reply.started":"2026-09-12T16:14:03.794259Z","shell.execute_reply":"2026-09-12T16:14:03.80123Z"}},"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-12T16:14:05.122649Z","iopub.execute_input":"2026-09-12T16:14:05.123161Z","iopub.status.idle":"2026-09-12T16:14:05.163577Z","shell.execute_reply.started":"2026-09-12T16:14:05.123126Z","shell.execute_reply":"2026-09-12T16:14:05.162869Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:06.517441Z","iopub.execute_input":"2026-09-12T16:14:06.51777Z","iopub.status.idle":"2026-09-12T16:14:06.525341Z","shell.execute_reply.started":"2026-09-12T16:14:06.517744Z","shell.execute_reply":"2026-09-12T16:14:06.524257Z"}},"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-12T16:14:07.04234Z","iopub.execute_input":"2026-09-12T16:14:07.043218Z","iopub.status.idle":"2026-09-12T16:14:07.049528Z","shell.execute_reply.started":"2026-09-12T16:14:07.04318Z","shell.execute_reply":"2026-09-12T16:14:07.048542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:08.162287Z","iopub.execute_input":"2026-09-12T16:14:08.163161Z","iopub.status.idle":"2026-09-12T16:14:08.195757Z","shell.execute_reply.started":"2026-09-12T16:14:08.163125Z","shell.execute_reply":"2026-09-12T16:14:08.194944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:09.313579Z","iopub.execute_input":"2026-09-12T16:14:09.314321Z","iopub.status.idle":"2026-09-12T16:14:09.321281Z","shell.execute_reply.started":"2026-09-12T16:14:09.314288Z","shell.execute_reply":"2026-09-12T16:14:09.320291Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:09.722832Z","iopub.execute_input":"2026-09-12T16:14:09.723193Z","iopub.status.idle":"2026-09-12T16:14:09.735619Z","shell.execute_reply.started":"2026-09-12T16:14:09.723165Z","shell.execute_reply":"2026-09-12T16:14:09.734538Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:10.697741Z","iopub.execute_input":"2026-09-12T16:14:10.698519Z","iopub.status.idle":"2026-09-12T16:14:10.706582Z","shell.execute_reply.started":"2026-09-12T16:14:10.69848Z","shell.execute_reply":"2026-09-12T16:14:10.705529Z"}},"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-12T16:14:12.042963Z","iopub.execute_input":"2026-09-12T16:14:12.043934Z","iopub.status.idle":"2026-09-12T16:14:12.132243Z","shell.execute_reply.started":"2026-09-12T16:14:12.0439Z","shell.execute_reply":"2026-09-12T16:14:12.131431Z"}},"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-12T16:14:14.478342Z","iopub.execute_input":"2026-09-12T16:14:14.478673Z","iopub.status.idle":"2026-09-12T16:14:14.485431Z","shell.execute_reply.started":"2026-09-12T16:14:14.478648Z","shell.execute_reply":"2026-09-12T16:14:14.484434Z"}},"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-12T16:14:16.312676Z","iopub.execute_input":"2026-09-12T16:14:16.313051Z","iopub.status.idle":"2026-09-12T16:14:21.900542Z","shell.execute_reply.started":"2026-09-12T16:14:16.313022Z","shell.execute_reply":"2026-09-12T16:14:21.898937Z"}},"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-12T16:14:21.903204Z","iopub.execute_input":"2026-09-12T16:14:21.903671Z","iopub.status.idle":"2026-09-12T16:14:27.374692Z","shell.execute_reply.started":"2026-09-12T16:14:21.903625Z","shell.execute_reply":"2026-09-12T16:14:27.373384Z"}},"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-12T16:14:27.376447Z","iopub.execute_input":"2026-09-12T16:14:27.376905Z","iopub.status.idle":"2026-09-12T16:14:27.385258Z","shell.execute_reply.started":"2026-09-12T16:14:27.376865Z","shell.execute_reply":"2026-09-12T16:14:27.384193Z"}},"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-12T16:14:27.387112Z","iopub.execute_input":"2026-09-12T16:14:27.387576Z","iopub.status.idle":"2026-09-12T16:14:32.449848Z","shell.execute_reply.started":"2026-09-12T16:14:27.387549Z","shell.execute_reply":"2026-09-12T16:14:32.448662Z"}},"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-12T16:14:32.451148Z","iopub.execute_input":"2026-09-12T16:14:32.451565Z","iopub.status.idle":"2026-09-12T16:14:54.579075Z","shell.execute_reply.started":"2026-09-12T16:14:32.451516Z","shell.execute_reply":"2026-09-12T16:14:54.57805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:14:54.580394Z","iopub.execute_input":"2026-09-12T16:14:54.580807Z","iopub.status.idle":"2026-09-12T16:14:54.58821Z","shell.execute_reply.started":"2026-09-12T16:14:54.580747Z","shell.execute_reply":"2026-09-12T16:14:54.586966Z"}},"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-12T16:14:54.589616Z","iopub.execute_input":"2026-09-12T16:14:54.589908Z","iopub.status.idle":"2026-09-12T16:14:56.470191Z","shell.execute_reply.started":"2026-09-12T16:14:54.589885Z","shell.execute_reply":"2026-09-12T16:14:56.467912Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# end of 2026-09-06\nstop here","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:15:21.494369Z","iopub.execute_input":"2026-09-12T16:15:21.49517Z","iopub.status.idle":"2026-09-12T16:15:21.501231Z","shell.execute_reply.started":"2026-09-12T16:15:21.495135Z","shell.execute_reply":"2026-09-12T16:15:21.499958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:15:22.689164Z","iopub.execute_input":"2026-09-12T16:15:22.689546Z","iopub.status.idle":"2026-09-12T16:15:22.694357Z","shell.execute_reply.started":"2026-09-12T16:15:22.689514Z","shell.execute_reply":"2026-09-12T16:15:22.693221Z"}},"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-12T16:15:25.103406Z","iopub.execute_input":"2026-09-12T16:15:25.103739Z","iopub.status.idle":"2026-09-12T16:15:25.111119Z","shell.execute_reply.started":"2026-09-12T16:15:25.103713Z","shell.execute_reply":"2026-09-12T16:15:25.110076Z"}},"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-12T16:15:26.788426Z","iopub.execute_input":"2026-09-12T16:15:26.789363Z","iopub.status.idle":"2026-09-12T16:15:26.793492Z","shell.execute_reply.started":"2026-09-12T16:15:26.789322Z","shell.execute_reply":"2026-09-12T16:15:26.792344Z"}},"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-12T16:15:27.857819Z","iopub.execute_input":"2026-09-12T16:15:27.858677Z","iopub.status.idle":"2026-09-12T16:15:27.862554Z","shell.execute_reply.started":"2026-09-12T16:15:27.858639Z","shell.execute_reply":"2026-09-12T16:15:27.86155Z"}},"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-12T16:15:28.182418Z","iopub.execute_input":"2026-09-12T16:15:28.183194Z","iopub.status.idle":"2026-09-12T16:15:28.187227Z","shell.execute_reply.started":"2026-09-12T16:15:28.183159Z","shell.execute_reply":"2026-09-12T16:15:28.186195Z"}},"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-12T16:15:29.232501Z","iopub.execute_input":"2026-09-12T16:15:29.23359Z","iopub.status.idle":"2026-09-12T16:15:29.237511Z","shell.execute_reply.started":"2026-09-12T16:15:29.233552Z","shell.execute_reply":"2026-09-12T16:15:29.236412Z"}},"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-12T16:15:34.209714Z","iopub.execute_input":"2026-09-12T16:15:34.210237Z","iopub.status.idle":"2026-09-12T16:15:38.190253Z","shell.execute_reply.started":"2026-09-12T16:15:34.210202Z","shell.execute_reply":"2026-09-12T16:15:38.18924Z"}},"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-12T16:15:38.191684Z","iopub.execute_input":"2026-09-12T16:15:38.192206Z","iopub.status.idle":"2026-09-12T16:15:38.19778Z","shell.execute_reply.started":"2026-09-12T16:15:38.192179Z","shell.execute_reply":"2026-09-12T16:15:38.196807Z"}},"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-12T16:15:38.199136Z","iopub.execute_input":"2026-09-12T16:15:38.199579Z","iopub.status.idle":"2026-09-12T16:15:38.20576Z","shell.execute_reply.started":"2026-09-12T16:15:38.199535Z","shell.execute_reply":"2026-09-12T16:15:38.204852Z"}},"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-12T16:15:38.208284Z","iopub.execute_input":"2026-09-12T16:15:38.208736Z","iopub.status.idle":"2026-09-12T16:15:38.217046Z","shell.execute_reply.started":"2026-09-12T16:15:38.20871Z","shell.execute_reply":"2026-09-12T16:15:38.215876Z"}},"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-12T16:15:38.218386Z","iopub.execute_input":"2026-09-12T16:15:38.218936Z","iopub.status.idle":"2026-09-12T16:15:38.225181Z","shell.execute_reply.started":"2026-09-12T16:15:38.218899Z","shell.execute_reply":"2026-09-12T16:15:38.223976Z"}},"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-12T16:15:38.226291Z","iopub.execute_input":"2026-09-12T16:15:38.226582Z","iopub.status.idle":"2026-09-12T16:15:38.237786Z","shell.execute_reply.started":"2026-09-12T16:15:38.226558Z","shell.execute_reply":"2026-09-12T16:15:38.236709Z"}},"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-12T16:15:38.239129Z","iopub.execute_input":"2026-09-12T16:15:38.239554Z","iopub.status.idle":"2026-09-12T16:15:50.569633Z","shell.execute_reply.started":"2026-09-12T16:15:38.239529Z","shell.execute_reply":"2026-09-12T16:15:50.567361Z"}},"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-12T16:15:50.570804Z","iopub.status.idle":"2026-09-12T16:15:50.571225Z","shell.execute_reply.started":"2026-09-12T16:15:50.571044Z","shell.execute_reply":"2026-09-12T16:15:50.571064Z"}},"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-12T16:15:50.572518Z","iopub.status.idle":"2026-09-12T16:15:50.572871Z","shell.execute_reply.started":"2026-09-12T16:15:50.572711Z","shell.execute_reply":"2026-09-12T16:15:50.572728Z"}},"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-12T16:15:50.574647Z","iopub.status.idle":"2026-09-12T16:15:50.57505Z","shell.execute_reply.started":"2026-09-12T16:15:50.574849Z","shell.execute_reply":"2026-09-12T16:15:50.574865Z"},"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-12T16:15:50.576611Z","iopub.status.idle":"2026-09-12T16:15:50.577065Z","shell.execute_reply.started":"2026-09-12T16:15:50.576821Z","shell.execute_reply":"2026-09-12T16:15:50.576842Z"}},"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-12T16:15:50.578711Z","iopub.status.idle":"2026-09-12T16:15:50.579173Z","shell.execute_reply.started":"2026-09-12T16:15:50.578921Z","shell.execute_reply":"2026-09-12T16:15:50.578943Z"}},"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-12T16:15:50.580834Z","iopub.status.idle":"2026-09-12T16:15:50.581318Z","shell.execute_reply.started":"2026-09-12T16:15:50.581073Z","shell.execute_reply":"2026-09-12T16:15:50.581096Z"}},"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-12T16:15:50.58251Z","iopub.status.idle":"2026-09-12T16:15:50.582972Z","shell.execute_reply.started":"2026-09-12T16:15:50.58273Z","shell.execute_reply":"2026-09-12T16:15:50.582754Z"}},"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-12T16:15:50.584649Z","iopub.status.idle":"2026-09-12T16:15:50.584927Z","shell.execute_reply.started":"2026-09-12T16:15:50.584792Z","shell.execute_reply":"2026-09-12T16:15:50.584806Z"}},"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-12T16:15:50.586376Z","iopub.status.idle":"2026-09-12T16:15:50.586716Z","shell.execute_reply.started":"2026-09-12T16:15:50.58656Z","shell.execute_reply":"2026-09-12T16:15:50.586577Z"}},"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-12T16:15:50.588242Z","iopub.status.idle":"2026-09-12T16:15:50.588546Z","shell.execute_reply.started":"2026-09-12T16:15:50.588399Z","shell.execute_reply":"2026-09-12T16:15:50.588414Z"}},"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-12T16:15:50.589641Z","iopub.status.idle":"2026-09-12T16:15:50.58993Z","shell.execute_reply.started":"2026-09-12T16:15:50.589787Z","shell.execute_reply":"2026-09-12T16:15:50.589801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T16:15:50.590852Z","iopub.status.idle":"2026-09-12T16:15:50.591235Z","shell.execute_reply.started":"2026-09-12T16:15:50.591069Z","shell.execute_reply":"2026-09-12T16:15:50.591091Z"}},"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-12T16:15:50.592318Z","iopub.status.idle":"2026-09-12T16:15:50.592614Z","shell.execute_reply.started":"2026-09-12T16:15:50.59247Z","shell.execute_reply":"2026-09-12T16:15:50.592484Z"}},"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-12T16:15:50.594085Z","iopub.status.idle":"2026-09-12T16:15:50.594433Z","shell.execute_reply.started":"2026-09-12T16:15:50.594273Z","shell.execute_reply":"2026-09-12T16:15:50.59429Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}