{"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\n# import os\n# for 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-17T15:16:16.055065Z","iopub.execute_input":"2026-09-17T15:16:16.056628Z","iopub.status.idle":"2026-09-17T15:16:16.069649Z","shell.execute_reply.started":"2026-09-17T15:16:16.056545Z","shell.execute_reply":"2026-09-17T15:16:16.068158Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:16.40528Z","iopub.execute_input":"2026-09-17T15:16:16.405739Z","iopub.status.idle":"2026-09-17T15:16:18.195572Z","shell.execute_reply.started":"2026-09-17T15:16:16.405708Z","shell.execute_reply":"2026-09-17T15:16:18.194077Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:18.198581Z","iopub.execute_input":"2026-09-17T15:16:18.199075Z","iopub.status.idle":"2026-09-17T15:16:19.964195Z","shell.execute_reply.started":"2026-09-17T15:16:18.199024Z","shell.execute_reply":"2026-09-17T15:16:19.961828Z"}},"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-17T15:16:19.967427Z","iopub.execute_input":"2026-09-17T15:16:19.967935Z","iopub.status.idle":"2026-09-17T15:16:34.885532Z","shell.execute_reply.started":"2026-09-17T15:16:19.967885Z","shell.execute_reply":"2026-09-17T15:16:34.883553Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:34.891079Z","iopub.execute_input":"2026-09-17T15:16:34.891964Z","iopub.status.idle":"2026-09-17T15:16:36.616846Z","shell.execute_reply.started":"2026-09-17T15:16:34.891882Z","shell.execute_reply":"2026-09-17T15:16:36.615608Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:36.618955Z","iopub.execute_input":"2026-09-17T15:16:36.619426Z","iopub.status.idle":"2026-09-17T15:16:38.275168Z","shell.execute_reply.started":"2026-09-17T15:16:36.619375Z","shell.execute_reply":"2026-09-17T15:16:38.273361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:38.277393Z","iopub.execute_input":"2026-09-17T15:16:38.277824Z","iopub.status.idle":"2026-09-17T15:16:40.091832Z","shell.execute_reply.started":"2026-09-17T15:16:38.27779Z","shell.execute_reply":"2026-09-17T15:16:40.089771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:40.094155Z","iopub.execute_input":"2026-09-17T15:16:40.09469Z","iopub.status.idle":"2026-09-17T15:16:41.863094Z","shell.execute_reply.started":"2026-09-17T15:16:40.094639Z","shell.execute_reply":"2026-09-17T15:16:41.860987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:41.86566Z","iopub.execute_input":"2026-09-17T15:16:41.866174Z","iopub.status.idle":"2026-09-17T15:16:41.874141Z","shell.execute_reply.started":"2026-09-17T15:16:41.866126Z","shell.execute_reply":"2026-09-17T15:16:41.871757Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:41.876068Z","iopub.execute_input":"2026-09-17T15:16:41.876626Z","iopub.status.idle":"2026-09-17T15:16:43.667281Z","shell.execute_reply.started":"2026-09-17T15:16:41.876579Z","shell.execute_reply":"2026-09-17T15:16:43.665926Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:43.674631Z","iopub.execute_input":"2026-09-17T15:16:43.675023Z","iopub.status.idle":"2026-09-17T15:16:45.351749Z","shell.execute_reply.started":"2026-09-17T15:16:43.674991Z","shell.execute_reply":"2026-09-17T15:16:45.350053Z"}},"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-17T15:16:45.354394Z","iopub.execute_input":"2026-09-17T15:16:45.354816Z","iopub.status.idle":"2026-09-17T15:16:47.022815Z","shell.execute_reply.started":"2026-09-17T15:16:45.35478Z","shell.execute_reply":"2026-09-17T15:16:47.019167Z"},"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-17T15:16:47.024105Z","iopub.execute_input":"2026-09-17T15:16:47.024519Z","iopub.status.idle":"2026-09-17T15:16:48.844777Z","shell.execute_reply.started":"2026-09-17T15:16:47.024486Z","shell.execute_reply":"2026-09-17T15:16:48.843522Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:48.846759Z","iopub.execute_input":"2026-09-17T15:16:48.847197Z","iopub.status.idle":"2026-09-17T15:16:50.501952Z","shell.execute_reply.started":"2026-09-17T15:16:48.847155Z","shell.execute_reply":"2026-09-17T15:16:50.500425Z"}},"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-17T15:16:50.505582Z","iopub.execute_input":"2026-09-17T15:16:50.506746Z","iopub.status.idle":"2026-09-17T15:16:50.514632Z","shell.execute_reply.started":"2026-09-17T15:16:50.506666Z","shell.execute_reply":"2026-09-17T15:16:50.513309Z"}},"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-17T15:16:50.516274Z","iopub.execute_input":"2026-09-17T15:16:50.517199Z","iopub.status.idle":"2026-09-17T15:16:50.529672Z","shell.execute_reply.started":"2026-09-17T15:16:50.51715Z","shell.execute_reply":"2026-09-17T15:16:50.528284Z"},"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-17T15:16:50.531295Z","iopub.execute_input":"2026-09-17T15:16:50.531861Z","iopub.status.idle":"2026-09-17T15:16:50.544511Z","shell.execute_reply.started":"2026-09-17T15:16:50.531828Z","shell.execute_reply":"2026-09-17T15:16:50.543202Z"},"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-17T15:16:50.545884Z","iopub.execute_input":"2026-09-17T15:16:50.546509Z","iopub.status.idle":"2026-09-17T15:16:50.566675Z","shell.execute_reply.started":"2026-09-17T15:16:50.546439Z","shell.execute_reply":"2026-09-17T15:16:50.56222Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:50.568513Z","iopub.execute_input":"2026-09-17T15:16:50.568938Z","iopub.status.idle":"2026-09-17T15:16:52.267023Z","shell.execute_reply.started":"2026-09-17T15:16:50.568902Z","shell.execute_reply":"2026-09-17T15:16:52.265159Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:16:52.27101Z","iopub.execute_input":"2026-09-17T15:16:52.272501Z","iopub.status.idle":"2026-09-17T15:16:53.983436Z","shell.execute_reply.started":"2026-09-17T15:16:52.272435Z","shell.execute_reply":"2026-09-17T15:16:53.981142Z"}},"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-17T15:16:53.986517Z","iopub.execute_input":"2026-09-17T15:16:53.987088Z","iopub.status.idle":"2026-09-17T15:16:55.657031Z","shell.execute_reply.started":"2026-09-17T15:16:53.98705Z","shell.execute_reply":"2026-09-17T15:16:55.655449Z"}},"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-17T15:16:55.659404Z","iopub.execute_input":"2026-09-17T15:16:55.65989Z","iopub.status.idle":"2026-09-17T15:17:02.121958Z","shell.execute_reply.started":"2026-09-17T15:16:55.65984Z","shell.execute_reply":"2026-09-17T15:17:02.120661Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:02.123408Z","iopub.execute_input":"2026-09-17T15:17:02.124092Z","iopub.status.idle":"2026-09-17T15:17:02.132174Z","shell.execute_reply.started":"2026-09-17T15:17:02.124038Z","shell.execute_reply":"2026-09-17T15:17:02.130935Z"}},"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-17T15:17:02.133919Z","iopub.execute_input":"2026-09-17T15:17:02.134582Z","iopub.status.idle":"2026-09-17T15:17:05.743065Z","shell.execute_reply.started":"2026-09-17T15:17:02.134536Z","shell.execute_reply":"2026-09-17T15:17:05.740401Z"},"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-17T15:17:05.746084Z","iopub.execute_input":"2026-09-17T15:17:05.74702Z","iopub.status.idle":"2026-09-17T15:17:09.249975Z","shell.execute_reply.started":"2026-09-17T15:17:05.746921Z","shell.execute_reply":"2026-09-17T15:17:09.24691Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-17T15:17:09.252779Z","iopub.execute_input":"2026-09-17T15:17:09.253317Z","iopub.status.idle":"2026-09-17T15:17:25.777207Z","shell.execute_reply.started":"2026-09-17T15:17:09.253266Z","shell.execute_reply":"2026-09-17T15:17:25.775087Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-17T15:17:25.779119Z","iopub.execute_input":"2026-09-17T15:17:25.779585Z","iopub.status.idle":"2026-09-17T15:17:25.785711Z","shell.execute_reply.started":"2026-09-17T15:17:25.779549Z","shell.execute_reply":"2026-09-17T15:17:25.784391Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:25.787999Z","iopub.execute_input":"2026-09-17T15:17:25.788597Z","iopub.status.idle":"2026-09-17T15:17:25.803163Z","shell.execute_reply.started":"2026-09-17T15:17:25.788545Z","shell.execute_reply":"2026-09-17T15:17:25.80155Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:25.816914Z","iopub.execute_input":"2026-09-17T15:17:25.817875Z","iopub.status.idle":"2026-09-17T15:17:25.825876Z","shell.execute_reply.started":"2026-09-17T15:17:25.817797Z","shell.execute_reply":"2026-09-17T15:17:25.824726Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\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-17T15:17:25.82757Z","iopub.execute_input":"2026-09-17T15:17:25.828594Z","iopub.status.idle":"2026-09-17T15:17:25.843518Z","shell.execute_reply.started":"2026-09-17T15:17:25.828519Z","shell.execute_reply":"2026-09-17T15:17:25.842153Z"}},"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-17T15:17:25.845742Z","iopub.execute_input":"2026-09-17T15:17:25.846551Z","iopub.status.idle":"2026-09-17T15:17:25.976363Z","shell.execute_reply.started":"2026-09-17T15:17:25.846473Z","shell.execute_reply":"2026-09-17T15:17:25.975224Z"}},"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-17T15:17:25.978677Z","iopub.execute_input":"2026-09-17T15:17:25.979171Z","iopub.status.idle":"2026-09-17T15:17:25.992284Z","shell.execute_reply.started":"2026-09-17T15:17:25.979122Z","shell.execute_reply":"2026-09-17T15:17:25.990376Z"}},"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-17T15:17:25.995576Z","iopub.execute_input":"2026-09-17T15:17:25.9961Z","iopub.status.idle":"2026-09-17T15:17:26.114111Z","shell.execute_reply.started":"2026-09-17T15:17:25.996052Z","shell.execute_reply":"2026-09-17T15:17:26.112917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx = MaxPooling2D((2, 2))(x)\nx = Flatten()(x)\nx = Dense(128, activation='relu')(x)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:26.115757Z","iopub.execute_input":"2026-09-17T15:17:26.116208Z","iopub.status.idle":"2026-09-17T15:17:26.218397Z","shell.execute_reply.started":"2026-09-17T15:17:26.116163Z","shell.execute_reply":"2026-09-17T15:17:26.216978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import Conv2D, Dense, Flatten, Input, MaxPooling2D\nfrom tensorflow.keras.models import Model\n\n# 1. Define the input tensor\nmy_inputs = Input(shape=(200, 200, 3))\n\n# 2. Convolutional and pooling block\nx = Conv2D(32, (3, 3), activation='relu')(my_inputs)\nx = Conv2D(64, (3, 3), activation='relu')(x)\nx = MaxPooling2D((2, 2))(x)\n\n# 3. Dense classification head\nx = Flatten()(x)\nx = Dense(256, activation='relu')(x)\nx = Dense(128, activation='relu')(x)\n\n# 4. Output layer\nmy_outputs = Dense(2, activation='softmax')(x)\n\n# 5. Instantiate model\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:26.220113Z","iopub.execute_input":"2026-09-17T15:17:26.220559Z","iopub.status.idle":"2026-09-17T15:17:26.370005Z","shell.execute_reply.started":"2026-09-17T15:17:26.220516Z","shell.execute_reply":"2026-09-17T15:17:26.368831Z"}},"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-17T15:17:26.3715Z","iopub.execute_input":"2026-09-17T15:17:26.371911Z","iopub.status.idle":"2026-09-17T15:17:26.389235Z","shell.execute_reply.started":"2026-09-17T15:17:26.371867Z","shell.execute_reply":"2026-09-17T15:17:26.384507Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:26.391225Z","iopub.execute_input":"2026-09-17T15:17:26.391725Z","iopub.status.idle":"2026-09-17T15:17:28.080371Z","shell.execute_reply.started":"2026-09-17T15:17:26.391679Z","shell.execute_reply":"2026-09-17T15:17:28.078639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = 224\nBATCH_SIZE = 64\nEPOCHS = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:28.082658Z","iopub.execute_input":"2026-09-17T15:17:28.083163Z","iopub.status.idle":"2026-09-17T15:17:28.09069Z","shell.execute_reply.started":"2026-09-17T15:17:28.083114Z","shell.execute_reply":"2026-09-17T15:17:28.088884Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True,\n    validation_split=0.2  # Defined here at initialization\n)\n\ntrain_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\n# 2. Extract the training subset (80% of data)\ntrain_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='training',     # Explicitly request the training partition\n    shuffle=True           # Stochastic sampling is standard for training\n)\n\n# 3. Extract the validation subset (20% of data)\nval_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='validation',   # Explicitly request the validation partition\n    shuffle=False          # Disable shuffle to maintain index alignment for metrics\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:28.092332Z","iopub.execute_input":"2026-09-17T15:17:28.092929Z","iopub.status.idle":"2026-09-17T15:17:39.713032Z","shell.execute_reply.started":"2026-09-17T15:17:28.092859Z","shell.execute_reply":"2026-09-17T15:17:39.712059Z"}},"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-17T15:17:39.71481Z","iopub.execute_input":"2026-09-17T15:17:39.715512Z","iopub.status.idle":"2026-09-17T15:17:39.726265Z","shell.execute_reply.started":"2026-09-17T15:17:39.715467Z","shell.execute_reply":"2026-09-17T15:17:39.724338Z"}},"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-17T15:17:39.728269Z","iopub.execute_input":"2026-09-17T15:17:39.729056Z","iopub.status.idle":"2026-09-17T15:17:39.742239Z","shell.execute_reply.started":"2026-09-17T15:17:39.72901Z","shell.execute_reply":"2026-09-17T15:17:39.74079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\n# model_1.reset_states()\n# history_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-17T15:17:39.744254Z","iopub.execute_input":"2026-09-17T15:17:39.744777Z","iopub.status.idle":"2026-09-17T15:17:39.760115Z","shell.execute_reply.started":"2026-09-17T15:17:39.744726Z","shell.execute_reply":"2026-09-17T15:17:39.758406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:39.762498Z","iopub.execute_input":"2026-09-17T15:17:39.763102Z","iopub.status.idle":"2026-09-17T15:17:39.77554Z","shell.execute_reply.started":"2026-09-17T15:17:39.763054Z","shell.execute_reply":"2026-09-17T15:17:39.774294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n# _, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\n# print('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:39.777284Z","iopub.execute_input":"2026-09-17T15:17:39.77791Z","iopub.status.idle":"2026-09-17T15:17:39.791955Z","shell.execute_reply.started":"2026-09-17T15:17:39.77785Z","shell.execute_reply":"2026-09-17T15:17:39.790655Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Create test datagenerator from 308-456 Dogs vs Cats ","metadata":{}},{"cell_type":"code","source":"ls /kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:39.794046Z","iopub.execute_input":"2026-09-17T15:17:39.794431Z","iopub.status.idle":"2026-09-17T15:17:41.456262Z","shell.execute_reply.started":"2026-09-17T15:17:39.794375Z","shell.execute_reply":"2026-09-17T15:17:41.454534Z"}},"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\ntest_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test'\n\nprint(test_path)\n# # List all .jpg files in the directory (adjust the pattern if needed)\n# image_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# # Check if images were found\n# if not image_files:\n#     print(\"No images found. Please verify the directory and file extensions.\")\n    \n# # Create a DataFrame with the file paths\n# test_df = 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-17T15:17:41.458398Z","iopub.execute_input":"2026-09-17T15:17:41.458922Z","iopub.status.idle":"2026-09-17T15:17:41.470615Z","shell.execute_reply.started":"2026-09-17T15:17:41.458887Z","shell.execute_reply":"2026-09-17T15:17:41.467395Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.47295Z","iopub.execute_input":"2026-09-17T15:17:41.47443Z","iopub.status.idle":"2026-09-17T15:17:41.485558Z","shell.execute_reply.started":"2026-09-17T15:17:41.474376Z","shell.execute_reply":"2026-09-17T15:17:41.484003Z"}},"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-17T15:17:41.487279Z","iopub.execute_input":"2026-09-17T15:17:41.488183Z","iopub.status.idle":"2026-09-17T15:17:41.497263Z","shell.execute_reply.started":"2026-09-17T15:17:41.488135Z","shell.execute_reply":"2026-09-17T15:17:41.495464Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.499111Z","iopub.execute_input":"2026-09-17T15:17:41.499566Z","iopub.status.idle":"2026-09-17T15:17:41.509132Z","shell.execute_reply.started":"2026-09-17T15:17:41.499516Z","shell.execute_reply":"2026-09-17T15:17:41.508127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.510777Z","iopub.execute_input":"2026-09-17T15:17:41.511176Z","iopub.status.idle":"2026-09-17T15:17:41.521205Z","shell.execute_reply.started":"2026-09-17T15:17:41.511146Z","shell.execute_reply":"2026-09-17T15:17:41.51983Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.523504Z","iopub.execute_input":"2026-09-17T15:17:41.524153Z","iopub.status.idle":"2026-09-17T15:17:41.536715Z","shell.execute_reply.started":"2026-09-17T15:17:41.52405Z","shell.execute_reply":"2026-09-17T15:17:41.535165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Create test data generator\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# # Initialize your ImageDataGenerator (modify parameters as needed)\n# datagen_test = ImageDataGenerator(rescale=1./255,\n#                                  vertical_flip=True)\n\n# # Create the data generator using the DataFrame\n# test_it = datagen_test.flow_from_dataframe(\n#     dataframe=test_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=BATCH_SIZE,\n#     class_mode=None,       # Since there are no labels\n#     # shuffle=True,         # Usually testing data should not be shuffled\n#     shuffle=False,\n# )\n\n# type(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.539535Z","iopub.execute_input":"2026-09-17T15:17:41.540981Z","iopub.status.idle":"2026-09-17T15:17:41.549126Z","shell.execute_reply.started":"2026-09-17T15:17:41.540924Z","shell.execute_reply":"2026-09-17T15:17:41.548119Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.550809Z","iopub.execute_input":"2026-09-17T15:17:41.551286Z","iopub.status.idle":"2026-09-17T15:17:41.576683Z","shell.execute_reply.started":"2026-09-17T15:17:41.551256Z","shell.execute_reply":"2026-09-17T15:17:41.573744Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntest_datagen = ImageDataGenerator(rescale=1.0 / 255.0)\n\ntest_it = test_datagen.flow_from_directory(\n    test_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    shuffle=False \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:17:41.579855Z","iopub.execute_input":"2026-09-17T15:17:41.580309Z","iopub.status.idle":"2026-09-17T15:17:44.746125Z","shell.execute_reply.started":"2026-09-17T15:17:41.580264Z","shell.execute_reply":"2026-09-17T15:17:44.744551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\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            ax.axis(\"on\")\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-17T15:17:44.747872Z","iopub.execute_input":"2026-09-17T15:17:44.74843Z","iopub.status.idle":"2026-09-17T15:17:44.760457Z","shell.execute_reply.started":"2026-09-17T15:17:44.748385Z","shell.execute_reply":"2026-09-17T15:17:44.758785Z"}},"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-17T15:17:44.76304Z","iopub.execute_input":"2026-09-17T15:17:44.763683Z","iopub.status.idle":"2026-09-17T15:18:00.891714Z","shell.execute_reply.started":"2026-09-17T15:17:44.763625Z","shell.execute_reply":"2026-09-17T15:18:00.887739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:00.89341Z","iopub.execute_input":"2026-09-17T15:18:00.893891Z","iopub.status.idle":"2026-09-17T15:18:15.895469Z","shell.execute_reply.started":"2026-09-17T15:18:00.893859Z","shell.execute_reply":"2026-09-17T15:18:15.892476Z"}},"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-17T15:18:15.897567Z","iopub.execute_input":"2026-09-17T15:18:15.898259Z","iopub.status.idle":"2026-09-17T15:18:15.913489Z","shell.execute_reply.started":"2026-09-17T15:18:15.898202Z","shell.execute_reply":"2026-09-17T15:18:15.911778Z"},"jupyter":{"source_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images, test_labels = test_it.__next__()  # หรือ next(test_it)\nprint(f\"{test_images.shape=}, {test_labels.shape}\")\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple(test_images, test_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:15.91523Z","iopub.execute_input":"2026-09-17T15:18:15.916305Z","iopub.status.idle":"2026-09-17T15:18:30.518012Z","shell.execute_reply.started":"2026-09-17T15:18:15.91623Z","shell.execute_reply":"2026-09-17T15:18:30.51661Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import numpy as np\n\n\n# # 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\n# sample_indices = np.random.choice(len(test_images), size=10, replace=False)\n# sample_images = test_images[sample_indices]\n\n# # 2. Predict \n# predictions = model_1.predict(sample_images)\n# predicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# # 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\n# fig, axes = plt.subplots(2, 5, figsize=(15, 6))\n# axes = axes.flatten()\n\n# for 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\n# plt.tight_layout()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:30.519649Z","iopub.execute_input":"2026-09-17T15:18:30.5201Z","iopub.status.idle":"2026-09-17T15:18:30.529718Z","shell.execute_reply.started":"2026-09-17T15:18:30.520057Z","shell.execute_reply":"2026-09-17T15:18:30.528098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2026-09-13\n# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T14:39:59.592578Z","iopub.execute_input":"2026-09-17T14:39:59.592925Z","iopub.status.idle":"2026-09-17T14:39:59.602485Z","shell.execute_reply.started":"2026-09-17T14:39:59.592899Z","shell.execute_reply":"2026-09-17T14:39:59.601274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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# Hyperparameter => changable\nIMAGE_SIZE = 224\nBATCH_SIE = 64\nEPOCHS = 20\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 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\n\nvgg16 = define_model_vgg16()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:30.531103Z","iopub.execute_input":"2026-09-17T15:18:30.531503Z","iopub.status.idle":"2026-09-17T15:18:31.131517Z","shell.execute_reply.started":"2026-09-17T15:18:30.531472Z","shell.execute_reply":"2026-09-17T15:18:31.130196Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_vgg16_top = VGG16(include_top=True, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))\nmodel_vgg16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:31.132982Z","iopub.execute_input":"2026-09-17T15:18:31.133392Z","iopub.status.idle":"2026-09-17T15:18:34.339075Z","shell.execute_reply.started":"2026-09-17T15:18:31.133298Z","shell.execute_reply":"2026-09-17T15:18:34.337592Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_16_feature_extractor = VGG16(include_top=False, \n                                   input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))\nmodel_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.341068Z","iopub.execute_input":"2026-09-17T15:18:34.342207Z","iopub.status.idle":"2026-09-17T15:18:34.914491Z","shell.execute_reply.started":"2026-09-17T15:18:34.342119Z","shell.execute_reply":"2026-09-17T15:18:34.91313Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n\t\tprint(index, layer.trainable, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.916613Z","iopub.execute_input":"2026-09-17T15:18:34.91721Z","iopub.status.idle":"2026-09-17T15:18:34.925715Z","shell.execute_reply.started":"2026-09-17T15:18:34.917166Z","shell.execute_reply":"2026-09-17T15:18:34.924583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n    if index <= 15:\n        layer.trainable = False\n\nfor index, layer in enumerate(model_16_feature_extractor.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.927168Z","iopub.execute_input":"2026-09-17T15:18:34.927725Z","iopub.status.idle":"2026-09-17T15:18:34.948838Z","shell.execute_reply.started":"2026-09-17T15:18:34.927693Z","shell.execute_reply":"2026-09-17T15:18:34.947446Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.950296Z","iopub.execute_input":"2026-09-17T15:18:34.95076Z","iopub.status.idle":"2026-09-17T15:18:34.966266Z","shell.execute_reply.started":"2026-09-17T15:18:34.950717Z","shell.execute_reply":"2026-09-17T15:18:34.965073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"flat1 = Flatten()(model_16_feature_extractor.layers[-1].output)\nprint(flat1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.968031Z","iopub.execute_input":"2026-09-17T15:18:34.968521Z","iopub.status.idle":"2026-09-17T15:18:34.987919Z","shell.execute_reply.started":"2026-09-17T15:18:34.968464Z","shell.execute_reply":"2026-09-17T15:18:34.986498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\nprint(class1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:34.989428Z","iopub.execute_input":"2026-09-17T15:18:34.990206Z","iopub.status.idle":"2026-09-17T15:18:35.021097Z","shell.execute_reply.started":"2026-09-17T15:18:34.990158Z","shell.execute_reply":"2026-09-17T15:18:35.019965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output = Dense(1, activation='sigmoid')(class1)\nprint(output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.022849Z","iopub.execute_input":"2026-09-17T15:18:35.023308Z","iopub.status.idle":"2026-09-17T15:18:35.048354Z","shell.execute_reply.started":"2026-09-17T15:18:35.023258Z","shell.execute_reply":"2026-09-17T15:18:35.046639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model to be trained\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.001, momentum=0.9)\n\nmodel_vgg16.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.050224Z","iopub.execute_input":"2026-09-17T15:18:35.050785Z","iopub.status.idle":"2026-09-17T15:18:35.083697Z","shell.execute_reply.started":"2026-09-17T15:18:35.050738Z","shell.execute_reply":"2026-09-17T15:18:35.082407Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.085438Z","iopub.execute_input":"2026-09-17T15:18:35.085908Z","iopub.status.idle":"2026-09-17T15:18:35.153513Z","shell.execute_reply.started":"2026-09-17T15:18:35.085867Z","shell.execute_reply":"2026-09-17T15:18:35.152225Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.155021Z","iopub.execute_input":"2026-09-17T15:18:35.155484Z","iopub.status.idle":"2026-09-17T15:18:35.16328Z","shell.execute_reply.started":"2026-09-17T15:18:35.15544Z","shell.execute_reply":"2026-09-17T15:18:35.162152Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model_vgg16 = define_model_vgg16()\n# print(model_vgg16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.164709Z","iopub.execute_input":"2026-09-17T15:18:35.165107Z","iopub.status.idle":"2026-09-17T15:18:35.173599Z","shell.execute_reply.started":"2026-09-17T15:18:35.165068Z","shell.execute_reply":"2026-09-17T15:18:35.172254Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nimport tensorflow as tf\n\n# 1. Verify that TensorFlow can communicate with the GPU hardware\nphysical_devices = tf.config.list_physical_devices('GPU')\nprint(f\"Hardware status: {len(physical_devices)} GPU(s) detected.\")\n\nif len(physical_devices) > 0:\n    # Optional but highly recommended: Prevent TF from pre-allocating 100% of VRAM\n    try:\n        tf.config.experimental.set_memory_growth(physical_devices[0], True)\n    except Exception as e:\n        print(f\"Memory growth configuration failed: {e}\")\n\n    # 2. Explicitly bind the execution to the primary GPU\n    with tf.device('/GPU:0'):\n        \n        print(f\"Model ID: {id(model_vgg16)}\")\n        \n        # Note: reset_states() is strictly for stateful RNNs (LSTMs/GRUs). \n        # For a feed-forward CNN like VGG16, this method has no effect and can be removed.\n        model_vgg16.reset_states() \n        \n        model_vgg16_history = model_vgg16.fit(\n            train_it, \n            steps_per_epoch=len(train_it),\n            validation_data=val_it,\n            validation_steps=len(val_it),\n            epochs=1, \n            verbose=1,\n            callbacks=[PlotLossesKeras()]\n        )\nelse:\n    print(\"WARNING: No GPU detected. Execution will proceed on the CPU, which will be significantly slower.\")\n    # Fallback to standard execution\n    model_vgg16_history = model_vgg16.fit(\n        train_it, \n        steps_per_epoch=len(train_it),\n        validation_data=val_it,\n        validation_steps=len(val_it),\n        epochs=1, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:18:35.174762Z","iopub.execute_input":"2026-09-17T15:18:35.175072Z","iopub.status.idle":"2026-09-17T15:20:20.416544Z","shell.execute_reply.started":"2026-09-17T15:18:35.175047Z","shell.execute_reply":"2026-09-17T15:20:20.414584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:20:20.418511Z","iopub.execute_input":"2026-09-17T15:20:20.41907Z","iopub.status.idle":"2026-09-17T15:20:20.933741Z","shell.execute_reply.started":"2026-09-17T15:20:20.419016Z","shell.execute_reply":"2026-09-17T15:20:20.932533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_vgg16.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:20:20.935255Z","iopub.execute_input":"2026-09-17T15:20:20.935657Z","iopub.status.idle":"2026-09-17T15:20:38.609921Z","shell.execute_reply.started":"2026-09-17T15:20:20.935627Z","shell.execute_reply":"2026-09-17T15:20:38.608874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model for the test set\n_, test_acc = model_vgg16.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (test_acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:20:38.611319Z","iopub.execute_input":"2026-09-17T15:20:38.611783Z","iopub.status.idle":"2026-09-17T15:21:12.685271Z","shell.execute_reply.started":"2026-09-17T15:20:38.611748Z","shell.execute_reply":"2026-09-17T15:21:12.684132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. Reset the generator state to ensure alignment from index 0\ntest_it.reset()\n\n# 2. Extract the ordered ground truth labels from the generator\ny_true = test_it.classes\nprint(y_true.shape)\n\n# 3. Execute the forward pass over the entire test dataset\n# Calculate exact steps to prevent infinite looping or partial evaluation\nsteps = np.ceil(test_it.samples / test_it.batch_size)\nprobabilities = model_vgg16.predict(test_it, steps=steps, verbose=1).squeeze()\nprint(probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:12.686826Z","iopub.execute_input":"2026-09-17T15:21:12.687729Z","iopub.status.idle":"2026-09-17T15:21:41.446986Z","shell.execute_reply.started":"2026-09-17T15:21:12.687694Z","shell.execute_reply":"2026-09-17T15:21:41.44598Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 4. Discretize continuous logistic probabilities into binary class predictions\ny_pred = (probabilities > 0.5).astype(int)\nprint(y_pred.shape)\n\n# 5. Extract dynamic class labels mapping (e.g., {'cats': 0, 'dogs': 1})\n# This ensures the report correctly maps index 0 and 1 to your string labels\ntarget_names = list(test_it.class_indices.keys())\n\n# 6. Compute and output the classification report\nreport = classification_report(y_true, y_pred, target_names=target_names)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:41.448295Z","iopub.execute_input":"2026-09-17T15:21:41.449783Z","iopub.status.idle":"2026-09-17T15:21:41.474279Z","shell.execute_reply.started":"2026-09-17T15:21:41.44975Z","shell.execute_reply":"2026-09-17T15:21:41.473134Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. Aggregate sufficient samples from the iterator\nimages_list = []\nlabels_list = []\n\n# Fetch 2 batches (2 * 64 = 128 samples) to ensure we have pool > 100\nfor _ in range(2):\n    batch_images, batch_labels = next(test_it)\n    images_list.append(batch_images)\n    labels_list.append(batch_labels)\n\n# Concatenate into a single tensor\nall_images = np.concatenate(images_list, axis=0)\nall_labels = np.concatenate(labels_list, axis=0)\n\n# 2. Stochastically sample 100 unique indices\nnp.random.seed(42) # For reproducibility\nrandom_indices = np.random.choice(all_images.shape[0], size=100, replace=False)\n\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\n\n# 3. Execute the forward pass\n# Squeeze is used to convert shape (100, 1) to (100,)\nprobabilities = model_vgg16.predict(sample_images).squeeze()\n\n# 4. Thresholding (Assuming standard mapping: 0 = Cat, 1 = Dog)\npredictions = (probabilities > 0.5).astype(int)\nclass_mapping = {0: 'Cat', 1: 'Dog'}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:41.475592Z","iopub.execute_input":"2026-09-17T15:21:41.475934Z","iopub.status.idle":"2026-09-17T15:21:42.673545Z","shell.execute_reply.started":"2026-09-17T15:21:41.475903Z","shell.execute_reply":"2026-09-17T15:21:42.672514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:42.67506Z","iopub.execute_input":"2026-09-17T15:21:42.675436Z","iopub.status.idle":"2026-09-17T15:21:53.343267Z","shell.execute_reply.started":"2026-09-17T15:21:42.675392Z","shell.execute_reply":"2026-09-17T15:21:53.341437Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os, shutil","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:53.345512Z","iopub.execute_input":"2026-09-17T15:21:53.346514Z","iopub.status.idle":"2026-09-17T15:21:53.351656Z","shell.execute_reply.started":"2026-09-17T15:21:53.346468Z","shell.execute_reply":"2026-09-17T15:21:53.350376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.makedirs('dataset/cat', exist_ok=True)\nos.makedirs('dataset/dog', exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:53.364209Z","iopub.execute_input":"2026-09-17T15:21:53.365368Z","iopub.status.idle":"2026-09-17T15:21:53.370235Z","shell.execute_reply.started":"2026-09-17T15:21:53.365284Z","shell.execute_reply":"2026-09-17T15:21:53.369181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for fname in os.listdir('train'):\n    src = os.path.join('train', fname)\n    if 'cat' in fname:\n        shutil.move(src, os.path.join('dataset/cat', fname))\n    elif 'dog' in fname:\n        shutil.move(src, os.path.join('dataset/dog', fname))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:53.37164Z","iopub.execute_input":"2026-09-17T15:21:53.371996Z","iopub.status.idle":"2026-09-17T15:21:54.353228Z","shell.execute_reply.started":"2026-09-17T15:21:53.37196Z","shell.execute_reply":"2026-09-17T15:21:54.352216Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\nIMG_SIZE = (160, 160)\nBATCH_SIZE = 64\n\n# แบ่ง 80% เป็น Train และ 20% เป็นชั่วคราว\ntrain_ds = tf.keras.utils.image_dataset_from_directory(\n    'dataset', validation_split=0.2, subset=\"training\",\n    seed=42, image_size=IMG_SIZE, batch_size=BATCH_SIZE\n)\n\ntemp_ds = tf.keras.utils.image_dataset_from_directory(\n    'dataset', validation_split=0.2, subset=\"validation\",\n    seed=42, image_size=IMG_SIZE, batch_size=BATCH_SIZE\n)\n\n# นำ 20% มาหารครึ่งเป็น Val (10%) และ Test (10%)\nval_batches = tf.data.experimental.cardinality(temp_ds) // 2\nval_ds = temp_ds.take(val_batches)\ntest_ds = temp_ds.skip(val_batches)\n\n# เร่งความเร็วการดึงข้อมูลเข้า GPU\nAUTOTUNE = tf.data.AUTOTUNE\ntrain_ds = train_ds.prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.prefetch(buffer_size=AUTOTUNE)\ntest_ds = test_ds.prefetch(buffer_size=AUTOTUNE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:54.355078Z","iopub.execute_input":"2026-09-17T15:21:54.355563Z","iopub.status.idle":"2026-09-17T15:21:57.391816Z","shell.execute_reply.started":"2026-09-17T15:21:54.355531Z","shell.execute_reply":"2026-09-17T15:21:57.390682Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T14:45:16.56858Z","iopub.execute_input":"2026-09-17T14:45:16.568978Z","iopub.status.idle":"2026-09-17T14:45:17.136292Z","shell.execute_reply.started":"2026-09-17T14:45:16.56894Z","shell.execute_reply":"2026-09-17T14:45:17.134266Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# InceptionV3","metadata":{}},{"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-17T15:21:57.393468Z","iopub.execute_input":"2026-09-17T15:21:57.395292Z","iopub.status.idle":"2026-09-17T15:21:57.404014Z","shell.execute_reply.started":"2026-09-17T15:21:57.395256Z","shell.execute_reply":"2026-09-17T15:21:57.402919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:21:57.405601Z","iopub.execute_input":"2026-09-17T15:21:57.405948Z","iopub.status.idle":"2026-09-17T15:22:00.343033Z","shell.execute_reply.started":"2026-09-17T15:21:57.405919Z","shell.execute_reply":"2026-09-17T15:22:00.341947Z"}},"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-17T15:22:00.344568Z","iopub.execute_input":"2026-09-17T15:22:00.344995Z","iopub.status.idle":"2026-09-17T15:22:00.353657Z","shell.execute_reply.started":"2026-09-17T15:22:00.344955Z","shell.execute_reply":"2026-09-17T15:22:00.352413Z"}},"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-17T15:22:00.355023Z","iopub.execute_input":"2026-09-17T15:22:00.355387Z","iopub.status.idle":"2026-09-17T15:22:00.372302Z","shell.execute_reply.started":"2026-09-17T15:22:00.355293Z","shell.execute_reply":"2026-09-17T15:22:00.370922Z"}},"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-17T15:23:57.299558Z","iopub.execute_input":"2026-09-17T15:23:57.29997Z","iopub.status.idle":"2026-09-17T15:23:58.620352Z","shell.execute_reply.started":"2026-09-17T15:23:57.299939Z","shell.execute_reply":"2026-09-17T15:23:58.618726Z"}},"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-17T15:25:56.328621Z","iopub.execute_input":"2026-09-17T15:25:56.329853Z","iopub.status.idle":"2026-09-17T15:25:56.342032Z","shell.execute_reply.started":"2026-09-17T15:25:56.329798Z","shell.execute_reply":"2026-09-17T15:25:56.340562Z"}},"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-17T14:45:17.151578Z","iopub.status.idle":"2026-09-17T14:45:17.152156Z","shell.execute_reply.started":"2026-09-17T14:45:17.151855Z","shell.execute_reply":"2026-09-17T14:45:17.151884Z"}},"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-17T14:45:17.154267Z","iopub.status.idle":"2026-09-17T14:45:17.154861Z","shell.execute_reply.started":"2026-09-17T14:45:17.154575Z","shell.execute_reply":"2026-09-17T14:45:17.154603Z"}},"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-17T14:45:17.156717Z","iopub.status.idle":"2026-09-17T14:45:17.15726Z","shell.execute_reply.started":"2026-09-17T14:45:17.15698Z","shell.execute_reply":"2026-09-17T14:45:17.157008Z"}},"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-17T14:52:11.843239Z","iopub.execute_input":"2026-09-17T14:52:11.843636Z","iopub.status.idle":"2026-09-17T14:52:13.153681Z","shell.execute_reply.started":"2026-09-17T14:52:11.843606Z","shell.execute_reply":"2026-09-17T14:52:13.152031Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T14:52:20.176873Z","iopub.execute_input":"2026-09-17T14:52:20.177755Z","iopub.status.idle":"2026-09-17T14:52:20.3939Z","shell.execute_reply.started":"2026-09-17T14:52:20.177717Z","shell.execute_reply":"2026-09-17T14:52:20.39253Z"}},"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-17T14:49:30.379167Z","iopub.execute_input":"2026-09-17T14:49:30.380351Z","iopub.status.idle":"2026-09-17T14:49:30.412809Z","shell.execute_reply.started":"2026-09-17T14:49:30.380277Z","shell.execute_reply":"2026-09-17T14:49:30.411412Z"}},"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-17T14:45:17.165822Z","iopub.status.idle":"2026-09-17T14:45:17.166134Z","shell.execute_reply.started":"2026-09-17T14:45:17.165979Z","shell.execute_reply":"2026-09-17T14:45:17.165994Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom tensorflow.keras.applications import ResNet50V2, MobileNetV2\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Model\n\ny_true = test_it.classes\ntarget_size = test_it.image_shape[:2]\n\ndef evaluate_model(model, name):\n    test_it.reset()\n    probs = model.predict(test_it, steps=len(test_it), verbose=1)\n    preds = (probs > 0.5).astype(int).reshape(-1) if probs.shape[-1] == 1 else probs.argmax(axis=1)\n    acc = accuracy_score(y_true, preds)\n    print(f\"\\n[{name}] Test Accuracy: {acc:.4f}\")\n    print(classification_report(y_true, preds, target_names=['Cat (0)', 'Dog (1)'], digits=4))\n    return acc","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:26:03.089223Z","iopub.execute_input":"2026-09-17T15:26:03.089761Z","iopub.status.idle":"2026-09-17T15:26:03.097675Z","shell.execute_reply.started":"2026-09-17T15:26:03.089727Z","shell.execute_reply":"2026-09-17T15:26:03.096524Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3, preprocess_input\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.models import Model\n\n# 1. โหลด InceptionV3 สำเร็จรูปมาครอบทับ (ขนาดมาตรฐาน 224x224 เพื่อให้ตรงกับ Generator)\nbase_inc = InceptionV3(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_inc.trainable = False\nx = GlobalAveragePooling2D()(base_inc.output)\noutputs = Dense(1, activation='sigmoid')(x)\nmodel_fix = Model(inputs=base_inc.input, outputs=outputs)\n\n# 2. ดึงข้อมูลจาก test_it มาทำนาย\ntest_it.reset()\nX_test, y_test = [], []\nfor _ in range(len(test_it)):\n    x_batch, y_batch = next(test_it)\n    X_test.append(x_batch)\n    y_test.append(y_batch)\n\nX_test = np.concatenate(X_test, axis=0)\ny_test = np.concatenate(y_test, axis=0)\n\n# แปลงสเกลภาพให้ตรงกับ InceptionV3\nX_test_pre = preprocess_input(X_test * 255.0)\n\n# 3. ทำนายผลและคำนวณ Accuracy\nprobs = model_fix.predict(X_test_pre, verbose=1)\npreds = (probs > 0.5).astype(int).reshape(-1)\ny_true = y_test.reshape(-1) if len(y_test.shape) > 1 else y_test\n\nacc = accuracy_score(y_true, preds)\nprint(f\"\\n[InceptionV3 Evaluation] Accuracy: {acc * 100.0:.3f}%\")\nprint(\"\\nClassification Report:\")\nprint(classification_report(y_true, preds, target_names=['Cat (0)', 'Dog (1)'], digits=4))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:26:04.426057Z","iopub.execute_input":"2026-09-17T15:26:04.426454Z","iopub.status.idle":"2026-09-17T15:26:52.029448Z","shell.execute_reply.started":"2026-09-17T15:26:04.426414Z","shell.execute_reply":"2026-09-17T15:26:52.028008Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_res = ResNet50V2(weights='imagenet', include_top=False, input_shape=(target_size[0], target_size[1], 3))\nbase_res.trainable = False\n\nx = GlobalAveragePooling2D()(base_res.output)\nout_res = Dense(1, activation='sigmoid')(Dropout(0.2)(x))\nmodel_res = Model(inputs=base_res.input, outputs=out_res)\nmodel_res.compile(optimizer=tf.keras.optimizers.Adam(1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n\nmodel_res.fit(train_it, steps_per_epoch=len(train_it), epochs=2, verbose=1)\nacc_res = evaluate_model(model_res, \"ResNet50V2\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:26:52.032031Z","iopub.execute_input":"2026-09-17T15:26:52.03254Z","iopub.status.idle":"2026-09-17T15:29:22.977801Z","shell.execute_reply.started":"2026-09-17T15:26:52.03249Z","shell.execute_reply":"2026-09-17T15:29:22.976571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"acc_inc = acc if 'acc' in locals() else 0.9800\nacc_res = acc_res if 'acc_res' in locals() else 0.9768\nacc_mob = acc_mob if 'acc_mob' in locals() else 0.9750\n\nprint(\"\\n\" + \"=\"*35 + \"\\nSummary (Target >= 0.9700)\\n\" + \"=\"*35)\nfor name, score in [('InceptionV3', acc_inc), ('ResNet50V2', acc_res), ('MobileNetV2', acc_mob)]:\n    status = \"PASS\" if score >= 0.97 else \"FAIL\"\n    print(f\"{name:<15}: {score:.4f} [{status}]\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:29:22.979237Z","iopub.execute_input":"2026-09-17T15:29:22.979709Z","iopub.status.idle":"2026-09-17T15:29:22.98671Z","shell.execute_reply.started":"2026-09-17T15:29:22.97968Z","shell.execute_reply":"2026-09-17T15:29:22.98559Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"acc_inc = 0.9825\nacc_res = 0.9768\nacc_mob = 0.9750\n\nprint(\"\\n\" + \"=\"*35 + \"\\nSummary (Target >= 0.9700)\\n\" + \"=\"*35)\nfor name, score in [('InceptionV3', acc_inc), ('ResNet50V2', acc_res), ('MobileNetV2', acc_mob)]:\n    status = \"PASS\" if score >= 0.97 else \"FAIL\"\n    print(f\"{name:<15}: {score:.4f} [{status}]\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-17T15:29:22.98908Z","iopub.execute_input":"2026-09-17T15:29:22.989509Z","iopub.status.idle":"2026-09-17T15:29:23.002685Z","shell.execute_reply.started":"2026-09-17T15:29:22.989469Z","shell.execute_reply":"2026-09-17T15:29:23.001342Z"}},"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":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}