{"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","trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:44:54.543909Z","iopub.execute_input":"2026-09-16T01:44:54.544690Z","iopub.status.idle":"2026-09-16T01:44:54.549374Z","shell.execute_reply.started":"2026-09-16T01:44:54.544658Z","shell.execute_reply":"2026-09-16T01:44:54.548320Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:44:54.551039Z","iopub.execute_input":"2026-09-16T01:44:54.551376Z","iopub.status.idle":"2026-09-16T01:44:55.589035Z","shell.execute_reply.started":"2026-09-16T01:44:54.551353Z","shell.execute_reply":"2026-09-16T01:44:55.588078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:44:55.590658Z","iopub.execute_input":"2026-09-16T01:44:55.590964Z","iopub.status.idle":"2026-09-16T01:44:56.611413Z","shell.execute_reply.started":"2026-09-16T01:44:55.590939Z","shell.execute_reply":"2026-09-16T01:44:56.610235Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:44:56.614562Z","iopub.execute_input":"2026-09-16T01:44:56.614857Z","iopub.status.idle":"2026-09-16T01:45:05.902976Z","shell.execute_reply.started":"2026-09-16T01:44:56.614831Z","shell.execute_reply":"2026-09-16T01:45:05.902253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:05.904045Z","iopub.execute_input":"2026-09-16T01:45:05.904459Z","iopub.status.idle":"2026-09-16T01:45:06.924298Z","shell.execute_reply.started":"2026-09-16T01:45:05.904436Z","shell.execute_reply":"2026-09-16T01:45:06.923184Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:06.925957Z","iopub.execute_input":"2026-09-16T01:45:06.926320Z","iopub.status.idle":"2026-09-16T01:45:08.047981Z","shell.execute_reply.started":"2026-09-16T01:45:06.926290Z","shell.execute_reply":"2026-09-16T01:45:08.046659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:08.049860Z","iopub.execute_input":"2026-09-16T01:45:08.050270Z","iopub.status.idle":"2026-09-16T01:45:09.118701Z","shell.execute_reply.started":"2026-09-16T01:45:08.050233Z","shell.execute_reply":"2026-09-16T01:45:09.117794Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:09.120223Z","iopub.execute_input":"2026-09-16T01:45:09.120523Z","iopub.status.idle":"2026-09-16T01:45:10.232846Z","shell.execute_reply.started":"2026-09-16T01:45:09.120497Z","shell.execute_reply":"2026-09-16T01:45:10.231559Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:10.237481Z","iopub.execute_input":"2026-09-16T01:45:10.237857Z","iopub.status.idle":"2026-09-16T01:45:10.242363Z","shell.execute_reply.started":"2026-09-16T01:45:10.237830Z","shell.execute_reply":"2026-09-16T01:45:10.241233Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:10.243632Z","iopub.execute_input":"2026-09-16T01:45:10.244317Z","iopub.status.idle":"2026-09-16T01:45:11.348824Z","shell.execute_reply.started":"2026-09-16T01:45:10.244278Z","shell.execute_reply":"2026-09-16T01:45:11.347870Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:11.350268Z","iopub.execute_input":"2026-09-16T01:45:11.350566Z","iopub.status.idle":"2026-09-16T01:45:12.411522Z","shell.execute_reply.started":"2026-09-16T01:45:11.350541Z","shell.execute_reply":"2026-09-16T01:45:12.410553Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:12.413222Z","iopub.execute_input":"2026-09-16T01:45:12.413528Z","iopub.status.idle":"2026-09-16T01:45:13.419131Z","shell.execute_reply.started":"2026-09-16T01:45:12.413502Z","shell.execute_reply":"2026-09-16T01:45:13.418037Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:13.420443Z","iopub.execute_input":"2026-09-16T01:45:13.420734Z","iopub.status.idle":"2026-09-16T01:45:14.304196Z","shell.execute_reply.started":"2026-09-16T01:45:13.420710Z","shell.execute_reply":"2026-09-16T01:45:14.303187Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:14.305551Z","iopub.execute_input":"2026-09-16T01:45:14.305929Z","iopub.status.idle":"2026-09-16T01:45:15.337910Z","shell.execute_reply.started":"2026-09-16T01:45:14.305893Z","shell.execute_reply":"2026-09-16T01:45:15.336624Z"}},"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-16T01:45:15.339850Z","iopub.execute_input":"2026-09-16T01:45:15.340258Z","iopub.status.idle":"2026-09-16T01:45:15.346558Z","shell.execute_reply.started":"2026-09-16T01:45:15.340215Z","shell.execute_reply":"2026-09-16T01:45:15.345548Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:15.348013Z","iopub.execute_input":"2026-09-16T01:45:15.348412Z","iopub.status.idle":"2026-09-16T01:45:15.356892Z","shell.execute_reply.started":"2026-09-16T01:45:15.348380Z","shell.execute_reply":"2026-09-16T01:45:15.356167Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:15.358036Z","iopub.execute_input":"2026-09-16T01:45:15.359561Z","iopub.status.idle":"2026-09-16T01:45:15.368211Z","shell.execute_reply.started":"2026-09-16T01:45:15.359530Z","shell.execute_reply":"2026-09-16T01:45:15.367334Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:15.369461Z","iopub.execute_input":"2026-09-16T01:45:15.369872Z","iopub.status.idle":"2026-09-16T01:45:15.380604Z","shell.execute_reply.started":"2026-09-16T01:45:15.369841Z","shell.execute_reply":"2026-09-16T01:45:15.379844Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:15.382337Z","iopub.execute_input":"2026-09-16T01:45:15.382689Z","iopub.status.idle":"2026-09-16T01:45:16.409658Z","shell.execute_reply.started":"2026-09-16T01:45:15.382656Z","shell.execute_reply":"2026-09-16T01:45:16.408466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:16.411472Z","iopub.execute_input":"2026-09-16T01:45:16.411936Z","iopub.status.idle":"2026-09-16T01:45:17.445024Z","shell.execute_reply.started":"2026-09-16T01:45:16.411894Z","shell.execute_reply":"2026-09-16T01:45:17.444058Z"}},"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-16T01:45:17.446512Z","iopub.execute_input":"2026-09-16T01:45:17.446830Z","iopub.status.idle":"2026-09-16T01:45:18.473270Z","shell.execute_reply.started":"2026-09-16T01:45:17.446801Z","shell.execute_reply":"2026-09-16T01:45:18.472158Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:18.474770Z","iopub.execute_input":"2026-09-16T01:45:18.475228Z","iopub.status.idle":"2026-09-16T01:45:21.615158Z","shell.execute_reply.started":"2026-09-16T01:45:18.475200Z","shell.execute_reply":"2026-09-16T01:45:21.613898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:21.616536Z","iopub.execute_input":"2026-09-16T01:45:21.616843Z","iopub.status.idle":"2026-09-16T01:45:21.621415Z","shell.execute_reply.started":"2026-09-16T01:45:21.616819Z","shell.execute_reply":"2026-09-16T01:45:21.620483Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:21.629344Z","iopub.execute_input":"2026-09-16T01:45:21.629560Z","iopub.status.idle":"2026-09-16T01:45:23.859472Z","shell.execute_reply.started":"2026-09-16T01:45:21.629542Z","shell.execute_reply":"2026-09-16T01:45:23.858507Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:23.860965Z","iopub.execute_input":"2026-09-16T01:45:23.861294Z","iopub.status.idle":"2026-09-16T01:45:26.125116Z","shell.execute_reply.started":"2026-09-16T01:45:23.861267Z","shell.execute_reply":"2026-09-16T01:45:26.124163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:26.126624Z","iopub.execute_input":"2026-09-16T01:45:26.126934Z","iopub.status.idle":"2026-09-16T01:45:34.539954Z","shell.execute_reply.started":"2026-09-16T01:45:26.126908Z","shell.execute_reply":"2026-09-16T01:45:34.538891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:34.541997Z","iopub.execute_input":"2026-09-16T01:45:34.542472Z","iopub.status.idle":"2026-09-16T01:45:34.547921Z","shell.execute_reply.started":"2026-09-16T01:45:34.542435Z","shell.execute_reply":"2026-09-16T01:45:34.546917Z"}},"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-16T01:45:34.550166Z","iopub.execute_input":"2026-09-16T01:45:34.551074Z","iopub.status.idle":"2026-09-16T01:45:34.558895Z","shell.execute_reply.started":"2026-09-16T01:45:34.551039Z","shell.execute_reply":"2026-09-16T01:45:34.557868Z"}},"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-16T01:45:34.560156Z","iopub.execute_input":"2026-09-16T01:45:34.560413Z","iopub.status.idle":"2026-09-16T01:45:34.569226Z","shell.execute_reply.started":"2026-09-16T01:45:34.560393Z","shell.execute_reply":"2026-09-16T01:45:34.568322Z"}},"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',\n                     kernel_initializer='he_uniform',\n                     padding='same',\n                     input_shape=(200, 200, 3))\n             )\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-16T01:45:34.570399Z","iopub.execute_input":"2026-09-16T01:45:34.570719Z","iopub.status.idle":"2026-09-16T01:45:34.579287Z","shell.execute_reply.started":"2026-09-16T01:45:34.570698Z","shell.execute_reply":"2026-09-16T01:45:34.578193Z"}},"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-16T01:45:34.580426Z","iopub.execute_input":"2026-09-16T01:45:34.580773Z","iopub.status.idle":"2026-09-16T01:45:34.660038Z","shell.execute_reply.started":"2026-09-16T01:45:34.580743Z","shell.execute_reply":"2026-09-16T01:45:34.659046Z"}},"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-16T01:45:34.661219Z","iopub.execute_input":"2026-09-16T01:45:34.661555Z","iopub.status.idle":"2026-09-16T01:45:34.667909Z","shell.execute_reply.started":"2026-09-16T01:45:34.661532Z","shell.execute_reply":"2026-09-16T01:45:34.666830Z"}},"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-16T01:45:34.669027Z","iopub.execute_input":"2026-09-16T01:45:34.669325Z","iopub.status.idle":"2026-09-16T01:45:34.727687Z","shell.execute_reply.started":"2026-09-16T01:45:34.669305Z","shell.execute_reply":"2026-09-16T01:45:34.726926Z"}},"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\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\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-16T01:45:34.728776Z","iopub.execute_input":"2026-09-16T01:45:34.729086Z","iopub.status.idle":"2026-09-16T01:45:34.797921Z","shell.execute_reply.started":"2026-09-16T01:45:34.729047Z","shell.execute_reply":"2026-09-16T01:45:34.797013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API - new cell\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\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx1 = Conv2D(64, (3, 3), activation='relu')(x1)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\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-16T01:45:34.799067Z","iopub.execute_input":"2026-09-16T01:45:34.799720Z","iopub.status.idle":"2026-09-16T01:45:34.883216Z","shell.execute_reply.started":"2026-09-16T01:45:34.799697Z","shell.execute_reply":"2026-09-16T01:45:34.882410Z"}},"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-16T01:45:34.884523Z","iopub.execute_input":"2026-09-16T01:45:34.884869Z","iopub.status.idle":"2026-09-16T01:45:34.891574Z","shell.execute_reply.started":"2026-09-16T01:45:34.884838Z","shell.execute_reply":"2026-09-16T01:45:34.890581Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:34.892762Z","iopub.execute_input":"2026-09-16T01:45:34.893083Z","iopub.status.idle":"2026-09-16T01:45:35.916091Z","shell.execute_reply.started":"2026-09-16T01:45:34.893043Z","shell.execute_reply":"2026-09-16T01:45:35.915121Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = 224 #for vgg16\nBATCH_SIZE = 64\nEPOCHS = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:35.917781Z","iopub.execute_input":"2026-09-16T01:45:35.918162Z","iopub.status.idle":"2026-09-16T01:45:35.922720Z","shell.execute_reply.started":"2026-09-16T01:45:35.918087Z","shell.execute_reply":"2026-09-16T01:45:35.921857Z"}},"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-16T01:45:35.924156Z","iopub.execute_input":"2026-09-16T01:45:35.924599Z","iopub.status.idle":"2026-09-16T01:45:44.846806Z","shell.execute_reply.started":"2026-09-16T01:45:35.924575Z","shell.execute_reply":"2026-09-16T01:45:44.846126Z"}},"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-16T01:45:44.847903Z","iopub.execute_input":"2026-09-16T01:45:44.848465Z","iopub.status.idle":"2026-09-16T01:45:44.856468Z","shell.execute_reply.started":"2026-09-16T01:45:44.848440Z","shell.execute_reply":"2026-09-16T01:45:44.855659Z"}},"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-16T01:45:44.857426Z","iopub.execute_input":"2026-09-16T01:45:44.857714Z","iopub.status.idle":"2026-09-16T01:45:44.869554Z","shell.execute_reply.started":"2026-09-16T01:45:44.857694Z","shell.execute_reply":"2026-09-16T01:45:44.868482Z"}},"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-16T01:45:44.870755Z","iopub.execute_input":"2026-09-16T01:45:44.872417Z","iopub.status.idle":"2026-09-16T01:45:44.878569Z","shell.execute_reply.started":"2026-09-16T01:45:44.872393Z","shell.execute_reply":"2026-09-16T01:45:44.877655Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:44.879754Z","iopub.execute_input":"2026-09-16T01:45:44.880423Z","iopub.status.idle":"2026-09-16T01:45:44.887823Z","shell.execute_reply.started":"2026-09-16T01:45:44.880400Z","shell.execute_reply":"2026-09-16T01:45:44.887035Z"}},"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-16T01:45:44.889118Z","iopub.execute_input":"2026-09-16T01:45:44.889407Z","iopub.status.idle":"2026-09-16T01:45:44.896388Z","shell.execute_reply.started":"2026-09-16T01:45:44.889379Z","shell.execute_reply":"2026-09-16T01:45:44.895556Z"}},"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-16T01:45:44.897388Z","iopub.execute_input":"2026-09-16T01:45:44.897692Z","iopub.status.idle":"2026-09-16T01:45:45.922683Z","shell.execute_reply.started":"2026-09-16T01:45:44.897672Z","shell.execute_reply":"2026-09-16T01:45:45.921700Z"}},"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-16T01:45:45.925158Z","iopub.execute_input":"2026-09-16T01:45:45.926003Z","iopub.status.idle":"2026-09-16T01:45:45.931613Z","shell.execute_reply.started":"2026-09-16T01:45:45.925974Z","shell.execute_reply":"2026-09-16T01:45:45.930684Z"}},"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-16T01:45:45.932744Z","iopub.execute_input":"2026-09-16T01:45:45.933258Z","iopub.status.idle":"2026-09-16T01:45:45.942940Z","shell.execute_reply.started":"2026-09-16T01:45:45.933234Z","shell.execute_reply":"2026-09-16T01:45:45.942007Z"}},"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-16T01:45:45.944182Z","iopub.execute_input":"2026-09-16T01:45:45.944484Z","iopub.status.idle":"2026-09-16T01:45:45.953738Z","shell.execute_reply.started":"2026-09-16T01:45:45.944460Z","shell.execute_reply":"2026-09-16T01:45:45.952758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:45.954897Z","iopub.execute_input":"2026-09-16T01:45:45.955241Z","iopub.status.idle":"2026-09-16T01:45:45.963060Z","shell.execute_reply.started":"2026-09-16T01:45:45.955202Z","shell.execute_reply":"2026-09-16T01:45:45.962258Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:45.964388Z","iopub.execute_input":"2026-09-16T01:45:45.964956Z","iopub.status.idle":"2026-09-16T01:45:45.972639Z","shell.execute_reply.started":"2026-09-16T01:45:45.964931Z","shell.execute_reply":"2026-09-16T01:45:45.971711Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:45.974021Z","iopub.execute_input":"2026-09-16T01:45:45.974982Z","iopub.status.idle":"2026-09-16T01:45:45.980675Z","shell.execute_reply.started":"2026-09-16T01:45:45.974941Z","shell.execute_reply":"2026-09-16T01:45:45.979866Z"}},"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-16T01:45:45.981862Z","iopub.execute_input":"2026-09-16T01:45:45.982264Z","iopub.status.idle":"2026-09-16T01:45:45.990223Z","shell.execute_reply.started":"2026-09-16T01:45:45.982241Z","shell.execute_reply":"2026-09-16T01:45:45.989059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:45.991475Z","iopub.execute_input":"2026-09-16T01:45:45.992321Z","iopub.status.idle":"2026-09-16T01:45:45.999870Z","shell.execute_reply.started":"2026-09-16T01:45:45.992289Z","shell.execute_reply":"2026-09-16T01:45:45.999165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True\n)\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:45:46.001005Z","iopub.execute_input":"2026-09-16T01:45:46.001288Z","iopub.status.idle":"2026-09-16T01:45:53.294873Z","shell.execute_reply.started":"2026-09-16T01:45:46.001252Z","shell.execute_reply":"2026-09-16T01:45:53.294126Z"}},"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-16T01:45:53.296160Z","iopub.execute_input":"2026-09-16T01:45:53.296680Z","iopub.status.idle":"2026-09-16T01:45:53.303250Z","shell.execute_reply.started":"2026-09-16T01:45:53.296656Z","shell.execute_reply":"2026-09-16T01:45:53.302068Z"}},"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-16T01:45:53.304497Z","iopub.execute_input":"2026-09-16T01:45:53.304860Z","iopub.status.idle":"2026-09-16T01:46:02.731702Z","shell.execute_reply.started":"2026-09-16T01:45:53.304835Z","shell.execute_reply":"2026-09-16T01:46:02.730592Z"}},"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-16T01:46:02.732926Z","iopub.execute_input":"2026-09-16T01:46:02.733262Z","iopub.status.idle":"2026-09-16T01:46:11.352464Z","shell.execute_reply.started":"2026-09-16T01:46:02.733232Z","shell.execute_reply":"2026-09-16T01:46:11.351034Z"}},"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,"jupyter":{"source_hidden":true},"execution":{"iopub.status.busy":"2026-09-16T01:46:11.353626Z","iopub.execute_input":"2026-09-16T01:46:11.354322Z","iopub.status.idle":"2026-09-16T01:46:11.359727Z","shell.execute_reply.started":"2026-09-16T01:46:11.354295Z","shell.execute_reply":"2026-09-16T01:46:11.358862Z"}},"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-16T01:46:11.360752Z","iopub.execute_input":"2026-09-16T01:46:11.361013Z","iopub.status.idle":"2026-09-16T01:46:20.845070Z","shell.execute_reply.started":"2026-09-16T01:46:11.360991Z","shell.execute_reply":"2026-09-16T01:46:20.843336Z"}},"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-16T01:46:20.846424Z","iopub.execute_input":"2026-09-16T01:46:20.846721Z","iopub.status.idle":"2026-09-16T01:46:20.850913Z","shell.execute_reply.started":"2026-09-16T01:46:20.846696Z","shell.execute_reply":"2026-09-16T01:46:20.850165Z"}},"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-16T01:46:20.852195Z","iopub.execute_input":"2026-09-16T01:46:20.852844Z","iopub.status.idle":"2026-09-16T01:46:20.864496Z","shell.execute_reply.started":"2026-09-16T01:46:20.852775Z","shell.execute_reply":"2026-09-16T01:46:20.863414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it), id(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:20.865878Z","iopub.execute_input":"2026-09-16T01:46:20.866427Z","iopub.status.idle":"2026-09-16T01:46:20.876042Z","shell.execute_reply.started":"2026-09-16T01:46:20.866403Z","shell.execute_reply":"2026-09-16T01:46:20.875136Z"}},"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-16T01:46:20.877056Z","iopub.execute_input":"2026-09-16T01:46:20.877411Z","iopub.status.idle":"2026-09-16T01:46:21.237517Z","shell.execute_reply.started":"2026-09-16T01:46:20.877388Z","shell.execute_reply":"2026-09-16T01:46:21.236330Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_vgg16_top = VGG16(include_top=True,\n                        input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)\n                       )\nmodel_vgg16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:21.239128Z","iopub.execute_input":"2026-09-16T01:46:21.239496Z","iopub.status.idle":"2026-09-16T01:46:23.688555Z","shell.execute_reply.started":"2026-09-16T01:46:21.239461Z","shell.execute_reply":"2026-09-16T01:46:23.687545Z"}},"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)\n                                  )\nmodel_16_feature_extractor.summary() #feature extractor as a backbone","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:23.689893Z","iopub.execute_input":"2026-09-16T01:46:23.690266Z","iopub.status.idle":"2026-09-16T01:46:24.045995Z","shell.execute_reply.started":"2026-09-16T01:46:23.690233Z","shell.execute_reply":"2026-09-16T01:46:24.042787Z"}},"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-16T01:46:24.047154Z","iopub.execute_input":"2026-09-16T01:46:24.047422Z","iopub.status.idle":"2026-09-16T01:46:24.052620Z","shell.execute_reply.started":"2026-09-16T01:46:24.047400Z","shell.execute_reply":"2026-09-16T01:46:24.051574Z"}},"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-16T01:46:24.053771Z","iopub.execute_input":"2026-09-16T01:46:24.054315Z","iopub.status.idle":"2026-09-16T01:46:24.064036Z","shell.execute_reply.started":"2026-09-16T01:46:24.054283Z","shell.execute_reply":"2026-09-16T01:46:24.063050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:24.065263Z","iopub.execute_input":"2026-09-16T01:46:24.065910Z","iopub.status.idle":"2026-09-16T01:46:24.074896Z","shell.execute_reply.started":"2026-09-16T01:46:24.065880Z","shell.execute_reply":"2026-09-16T01:46:24.073916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use functional API\nflat1 = Flatten()(model_16_feature_extractor.layers[-1].output)\nprint(flat1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:24.083977Z","iopub.execute_input":"2026-09-16T01:46:24.084509Z","iopub.status.idle":"2026-09-16T01:46:24.093347Z","shell.execute_reply.started":"2026-09-16T01:46:24.084487Z","shell.execute_reply":"2026-09-16T01:46:24.092393Z"}},"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-16T01:46:24.094575Z","iopub.execute_input":"2026-09-16T01:46:24.094914Z","iopub.status.idle":"2026-09-16T01:46:24.114457Z","shell.execute_reply.started":"2026-09-16T01:46:24.094883Z","shell.execute_reply":"2026-09-16T01:46:24.113416Z"}},"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-16T01:46:24.115458Z","iopub.execute_input":"2026-09-16T01:46:24.115771Z","iopub.status.idle":"2026-09-16T01:46:24.130792Z","shell.execute_reply.started":"2026-09-16T01:46:24.115750Z","shell.execute_reply":"2026-09-16T01:46:24.130149Z"}},"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,\n                    loss='binary_crossentropy',\n                    metrics=['accuracy']\n                   )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:24.131740Z","iopub.execute_input":"2026-09-16T01:46:24.132034Z","iopub.status.idle":"2026-09-16T01:46:24.146996Z","shell.execute_reply.started":"2026-09-16T01:46:24.132006Z","shell.execute_reply":"2026-09-16T01:46:24.146048Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:24.148230Z","iopub.execute_input":"2026-09-16T01:46:24.148582Z","iopub.status.idle":"2026-09-16T01:46:24.192689Z","shell.execute_reply.started":"2026-09-16T01:46:24.148549Z","shell.execute_reply":"2026-09-16T01:46:24.191967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T01:46:24.193759Z","iopub.execute_input":"2026-09-16T01:46:24.194509Z","iopub.status.idle":"2026-09-16T01:46:24.199892Z","shell.execute_reply.started":"2026-09-16T01:46:24.194487Z","shell.execute_reply":"2026-09-16T01:46:24.198898Z"}},"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-16T01:46:24.200933Z","iopub.execute_input":"2026-09-16T01:46:24.201587Z","iopub.status.idle":"2026-09-16T01:46:24.209204Z","shell.execute_reply.started":"2026-09-16T01:46:24.201555Z","shell.execute_reply":"2026-09-16T01:46:24.208090Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ฝึกโมเดล1","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndata_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\nfiles = []\nlabels = []\n\nfor class_name in ['cats', 'dogs']:\n    class_path = os.path.join(data_path, class_name)\n\n    for file_name in os.listdir(class_path):\n        file_path = os.path.join(class_path, file_name)\n\n        if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):\n            files.append(file_path)\n            labels.append(class_name)\n\ndf_vgg = pd.DataFrame({\n    'filename': files,\n    'class': labels\n})\n\ntrain_vgg_df, temp_vgg_df = train_test_split(\n    df_vgg,\n    test_size=0.30,\n    random_state=42,\n    stratify=df_vgg['class']\n)\n\nval_vgg_df, test_vgg_df = train_test_split(\n    temp_vgg_df,\n    test_size=0.50,\n    random_state=42,\n    stratify=temp_vgg_df['class']\n)\n\nprint(\"Train:\", len(train_vgg_df))\nprint(\"Validation:\", len(val_vgg_df))\nprint(\"Test:\", len(test_vgg_df))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T04:01:41.126621Z","iopub.execute_input":"2026-09-16T04:01:41.127374Z","iopub.status.idle":"2026-09-16T04:01:41.197607Z","shell.execute_reply.started":"2026-09-16T04:01:41.127337Z","shell.execute_reply":"2026-09-16T04:01:41.196567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\n\ntrain_datagen_vgg1 = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    rotation_range=15,\n    zoom_range=0.15,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntest_datagen_vgg1 = ImageDataGenerator(\n    preprocessing_function=preprocess_input\n)\n\nvgg1_train = train_datagen_vgg1.flow_from_dataframe(\n    train_vgg_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=True\n)\n\nvgg1_val = test_datagen_vgg1.flow_from_dataframe(\n    val_vgg_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)\n\nvgg1_test = test_datagen_vgg1.flow_from_dataframe(\n    test_vgg_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T04:01:54.243655Z","iopub.execute_input":"2026-09-16T04:01:54.244432Z","iopub.status.idle":"2026-09-16T04:02:51.327734Z","shell.execute_reply.started":"2026-09-16T04:01:54.244396Z","shell.execute_reply":"2026-09-16T04:02:51.326981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\nbase_vgg1 = VGG16(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\n\n# ล็อก Pre-trained Model ไว้ก่อน\nbase_vgg1.trainable = False\n\nx = base_vgg1.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.5)(x)\noutput = Dense(1, activation='sigmoid')(x)\n\nmodel_vgg1 = Model(\n    inputs=base_vgg1.input,\n    outputs=output\n)\n\nmodel_vgg1.compile(\n    optimizer=Adam(learning_rate=0.0001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel_vgg1.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T04:03:15.227814Z","iopub.execute_input":"2026-09-16T04:03:15.228646Z","iopub.status.idle":"2026-09-16T04:03:15.658916Z","shell.execute_reply.started":"2026-09-16T04:03:15.228607Z","shell.execute_reply":"2026-09-16T04:03:15.657647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\ncallbacks_vgg1 = [\n    EarlyStopping(\n        monitor='val_accuracy',\n        patience=3,\n        restore_best_weights=True\n    ),\n    ReduceLROnPlateau(\n        monitor='val_loss',\n        factor=0.5,\n        patience=2,\n        min_lr=1e-7\n    )\n]\n\nhistory_vgg1 = model_vgg1.fit(\n    vgg1_train,\n    steps_per_epoch=len(vgg1_train),\n    validation_data=vgg1_val,\n    validation_steps=len(vgg1_val),\n    epochs=8,\n    callbacks=callbacks_vgg1,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T04:04:56.214435Z","iopub.execute_input":"2026-09-16T04:04:56.215104Z","iopub.status.idle":"2026-09-16T04:24:54.773085Z","shell.execute_reply.started":"2026-09-16T04:04:56.215069Z","shell.execute_reply":"2026-09-16T04:24:54.771972Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_vgg1.trainable = True\n\nfor layer in base_vgg1.layers[:-2]:\n    layer.trainable = False\n\nmodel_vgg1.compile(\n    optimizer=Adam(learning_rate=0.00001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nhistory_vgg1_fine = model_vgg1.fit(\n    vgg1_train,\n    validation_data=vgg1_val,\n    epochs=5,\n    callbacks=callbacks_vgg1,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T04:37:07.112369Z","iopub.execute_input":"2026-09-16T04:37:07.112859Z","iopub.status.idle":"2026-09-16T04:55:54.295743Z","shell.execute_reply.started":"2026-09-16T04:37:07.112823Z","shell.execute_reply":"2026-09-16T04:55:54.294963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report, accuracy_score\n\nvgg1_test.reset()\n\ny_prob_vgg1 = model_vgg1.predict(\n    vgg1_test,\n    verbose=1\n)\n\ny_pred_vgg1 = (y_prob_vgg1 >= 0.5).astype(int).ravel()\n\ny_true_vgg1 = vgg1_test.classes\n\naccuracy_vgg1 = accuracy_score(\n    y_true_vgg1,\n    y_pred_vgg1\n)\n\nprint(\"================================\")\nprint(\"MODEL 1: VGG16 TEST RESULT\")\nprint(\"================================\")\n\nprint(\"Test Accuracy:\", accuracy_vgg1)\nprint(\"Test Accuracy (%):\", accuracy_vgg1 * 100)\n\nprint(\"\\nClassification Report:\")\n\nprint(classification_report(\n    y_true_vgg1,\n    y_pred_vgg1,\n    target_names=list(vgg1_test.class_indices.keys()),\n    digits=4\n))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:01:52.051234Z","iopub.execute_input":"2026-09-16T05:01:52.051568Z","iopub.status.idle":"2026-09-16T05:02:14.643738Z","shell.execute_reply.started":"2026-09-16T05:01:52.051540Z","shell.execute_reply":"2026-09-16T05:02:14.642837Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ฝึกโมเดล2","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndata_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\nfiles = []\nlabels = []\n\nfor class_name in ['cats', 'dogs']:\n    class_path = os.path.join(data_path, class_name)\n\n    for file_name in os.listdir(class_path):\n        file_path = os.path.join(class_path, file_name)\n\n        if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):\n            files.append(file_path)\n            labels.append(class_name)\n\ndf_mobile2 = pd.DataFrame({\n    'filename': files,\n    'class': labels\n})\n\ntrain_mobile2_df, temp_mobile2_df = train_test_split(\n    df_mobile2,\n    test_size=0.30,\n    random_state=42,\n    stratify=df_mobile2['class']\n)\n\nval_mobile2_df, test_mobile2_df = train_test_split(\n    temp_mobile2_df,\n    test_size=0.50,\n    random_state=42,\n    stratify=temp_mobile2_df['class']\n)\n\nprint(\"Train:\", len(train_mobile2_df))\nprint(\"Validation:\", len(val_mobile2_df))\nprint(\"Test:\", len(test_mobile2_df))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:03:57.948394Z","iopub.execute_input":"2026-09-16T05:03:57.949465Z","iopub.status.idle":"2026-09-16T05:03:58.130651Z","shell.execute_reply.started":"2026-09-16T05:03:57.949427Z","shell.execute_reply":"2026-09-16T05:03:58.129616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n\ntrain_datagen_mobile2 = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    rotation_range=15,\n    zoom_range=0.15,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntest_datagen_mobile2 = ImageDataGenerator(\n    preprocessing_function=preprocess_input\n)\n\nmobile2_train = train_datagen_mobile2.flow_from_dataframe(\n    train_mobile2_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=True\n)\n\nmobile2_val = test_datagen_mobile2.flow_from_dataframe(\n    val_mobile2_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)\n\nmobile2_test = test_datagen_mobile2.flow_from_dataframe(\n    test_mobile2_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:04:17.683635Z","iopub.execute_input":"2026-09-16T05:04:17.684553Z","iopub.status.idle":"2026-09-16T05:05:33.791457Z","shell.execute_reply.started":"2026-09-16T05:04:17.684517Z","shell.execute_reply":"2026-09-16T05:05:33.790126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\nbase_mobile2 = MobileNetV2(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\n\nbase_mobile2.trainable = False\n\nx = base_mobile2.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.5)(x)\n\noutput = Dense(1, activation='sigmoid')(x)\n\nmodel_mobile2 = Model(\n    inputs=base_mobile2.input,\n    outputs=output\n)\n\nmodel_mobile2.compile(\n    optimizer=Adam(learning_rate=0.0001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel_mobile2.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:07:16.504488Z","iopub.execute_input":"2026-09-16T05:07:16.505464Z","iopub.status.idle":"2026-09-16T05:07:18.420676Z","shell.execute_reply.started":"2026-09-16T05:07:16.505424Z","shell.execute_reply":"2026-09-16T05:07:18.417273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\ncallbacks_mobile2 = [\n    EarlyStopping(\n        monitor='val_accuracy',\n        patience=3,\n        restore_best_weights=True\n    ),\n    ReduceLROnPlateau(\n        monitor='val_loss',\n        factor=0.5,\n        patience=2,\n        min_lr=1e-7\n    )\n]\n\nhistory_mobile2 = model_mobile2.fit(\n    mobile2_train,\n    steps_per_epoch=len(mobile2_train),\n    validation_data=mobile2_val,\n    validation_steps=len(mobile2_val),\n    epochs=8,\n    callbacks=callbacks_mobile2,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:07:40.725861Z","iopub.execute_input":"2026-09-16T05:07:40.726377Z","iopub.status.idle":"2026-09-16T05:23:54.743117Z","shell.execute_reply.started":"2026-09-16T05:07:40.726331Z","shell.execute_reply":"2026-09-16T05:23:54.742349Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import BatchNormalization\n\nbase_mobile2.trainable = True\n\nfor layer in base_mobile2.layers[:-20]:\n    layer.trainable = False\n\nfor layer in base_mobile2.layers:\n    if isinstance(layer, BatchNormalization):\n        layer.trainable = False\n\nmodel_mobile2.compile(\n    optimizer=Adam(learning_rate=0.00001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nhistory_mobile2_fine = model_mobile2.fit(\n    mobile2_train,\n    validation_data=mobile2_val,\n    epochs=5,\n    callbacks=callbacks_mobile2,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:34:07.378933Z","iopub.execute_input":"2026-09-16T05:34:07.379795Z","iopub.status.idle":"2026-09-16T05:50:05.311201Z","shell.execute_reply.started":"2026-09-16T05:34:07.379726Z","shell.execute_reply":"2026-09-16T05:50:05.310135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report, accuracy_score\n\nmobile2_test.reset()\n\ny_prob_mobile2 = model_mobile2.predict(\n    mobile2_test,\n    verbose=1\n)\n\ny_pred_mobile2 = (y_prob_mobile2 >= 0.5).astype(int).ravel()\n\ny_true_mobile2 = mobile2_test.classes\n\naccuracy_mobile2 = accuracy_score(\n    y_true_mobile2,\n    y_pred_mobile2\n)\n\nprint(\"================================\")\nprint(\"MODEL 2: MobileNetV2 TEST RESULT\")\nprint(\"================================\")\n\nprint(\"Test Accuracy:\", accuracy_mobile2)\nprint(\"Test Accuracy (%):\", accuracy_mobile2 * 100)\n\nprint(\"\\nClassification Report:\")\n\nprint(classification_report(\n    y_true_mobile2,\n    y_pred_mobile2,\n    target_names=list(mobile2_test.class_indices.keys()),\n    digits=4\n))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:50:29.132584Z","iopub.execute_input":"2026-09-16T05:50:29.133370Z","iopub.status.idle":"2026-09-16T05:50:40.337329Z","shell.execute_reply.started":"2026-09-16T05:50:29.133334Z","shell.execute_reply":"2026-09-16T05:50:40.336412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ฝึกโมเดล3","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndata_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\nfiles = []\nlabels = []\n\nfor class_name in ['cats', 'dogs']:\n    class_path = os.path.join(data_path, class_name)\n\n    for file_name in os.listdir(class_path):\n        file_path = os.path.join(class_path, file_name)\n\n        if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):\n            files.append(file_path)\n            labels.append(class_name)\n\ndf_resnet3 = pd.DataFrame({\n    'filename': files,\n    'class': labels\n})\n\ntrain_resnet3_df, temp_resnet3_df = train_test_split(\n    df_resnet3,\n    test_size=0.30,\n    random_state=42,\n    stratify=df_resnet3['class']\n)\n\nval_resnet3_df, test_resnet3_df = train_test_split(\n    temp_resnet3_df,\n    test_size=0.50,\n    random_state=42,\n    stratify=temp_resnet3_df['class']\n)\n\nprint(\"Train:\", len(train_resnet3_df))\nprint(\"Validation:\", len(val_resnet3_df))\nprint(\"Test:\", len(test_resnet3_df))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:51:54.949906Z","iopub.execute_input":"2026-09-16T05:51:54.950661Z","iopub.status.idle":"2026-09-16T05:51:55.024475Z","shell.execute_reply.started":"2026-09-16T05:51:54.950626Z","shell.execute_reply":"2026-09-16T05:51:55.023509Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\n\ntrain_datagen_resnet3 = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    rotation_range=15,\n    zoom_range=0.15,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\n\ntest_datagen_resnet3 = ImageDataGenerator(\n    preprocessing_function=preprocess_input\n)\n\nresnet3_train = train_datagen_resnet3.flow_from_dataframe(\n    train_resnet3_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=True\n)\n\nresnet3_val = test_datagen_resnet3.flow_from_dataframe(\n    val_resnet3_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)\n\nresnet3_test = test_datagen_resnet3.flow_from_dataframe(\n    test_resnet3_df,\n    x_col='filename',\n    y_col='class',\n    target_size=(224, 224),\n    class_mode='binary',\n    batch_size=32,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:52:05.520673Z","iopub.execute_input":"2026-09-16T05:52:05.521137Z","iopub.status.idle":"2026-09-16T05:52:37.236753Z","shell.execute_reply.started":"2026-09-16T05:52:05.521098Z","shell.execute_reply":"2026-09-16T05:52:37.235699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.optimizers import Adam\n\nbase_resnet3 = ResNet50(\n    weights='imagenet',\n    include_top=False,\n    input_shape=(224, 224, 3)\n)\n\nbase_resnet3.trainable = False\n\nx = base_resnet3.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(256, activation='relu')(x)\nx = Dropout(0.5)(x)\n\noutput = Dense(1, activation='sigmoid')(x)\n\nmodel_resnet3 = Model(\n    inputs=base_resnet3.input,\n    outputs=output\n)\n\nmodel_resnet3.compile(\n    optimizer=Adam(learning_rate=0.0001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nmodel_resnet3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:53:12.923681Z","iopub.execute_input":"2026-09-16T05:53:12.924481Z","iopub.status.idle":"2026-09-16T05:53:15.527936Z","shell.execute_reply.started":"2026-09-16T05:53:12.924445Z","shell.execute_reply":"2026-09-16T05:53:15.519786Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n\ncallbacks_resnet3 = [\n    EarlyStopping(\n        monitor='val_accuracy',\n        patience=3,\n        restore_best_weights=True\n    ),\n    ReduceLROnPlateau(\n        monitor='val_loss',\n        factor=0.5,\n        patience=2,\n        min_lr=1e-7\n    )\n]\n\nhistory_resnet3 = model_resnet3.fit(\n    resnet3_train,\n    steps_per_epoch=len(resnet3_train),\n    validation_data=resnet3_val,\n    validation_steps=len(resnet3_val),\n    epochs=8,\n    callbacks=callbacks_resnet3,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T05:53:29.781598Z","iopub.execute_input":"2026-09-16T05:53:29.782445Z","iopub.status.idle":"2026-09-16T06:09:36.033458Z","shell.execute_reply.started":"2026-09-16T05:53:29.782407Z","shell.execute_reply":"2026-09-16T06:09:36.032467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import BatchNormalization\n\nbase_resnet3.trainable = True\n\nfor layer in base_resnet3.layers[:-20]:\n    layer.trainable = False\n\nfor layer in base_resnet3.layers:\n    if isinstance(layer, BatchNormalization):\n        layer.trainable = False\n\nmodel_resnet3.compile(\n    optimizer=Adam(learning_rate=0.00001),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nhistory_resnet3_fine = model_resnet3.fit(\n    resnet3_train,\n    validation_data=resnet3_val,\n    epochs=5,\n    callbacks=callbacks_resnet3,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T06:21:49.274933Z","iopub.execute_input":"2026-09-16T06:21:49.275750Z","iopub.status.idle":"2026-09-16T06:38:46.929403Z","shell.execute_reply.started":"2026-09-16T06:21:49.275715Z","shell.execute_reply":"2026-09-16T06:38:46.928282Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report, accuracy_score\n\nresnet3_test.reset()\n\ny_prob_resnet3 = model_resnet3.predict(\n    resnet3_test,\n    verbose=1\n)\n\ny_pred_resnet3 = (y_prob_resnet3 >= 0.5).astype(int).ravel()\n\ny_true_resnet3 = resnet3_test.classes\n\naccuracy_resnet3 = accuracy_score(\n    y_true_resnet3,\n    y_pred_resnet3\n)\n\nprint(\"================================\")\nprint(\"MODEL 3: ResNet50 TEST RESULT\")\nprint(\"================================\")\n\nprint(\"Test Accuracy:\", accuracy_resnet3)\nprint(\"Test Accuracy (%):\", accuracy_resnet3 * 100)\n\nprint(\"\\nClassification Report:\")\n\nprint(classification_report(\n    y_true_resnet3,\n    y_pred_resnet3,\n    target_names=list(resnet3_test.class_indices.keys()),\n    digits=4\n))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T06:41:53.134075Z","iopub.execute_input":"2026-09-16T06:41:53.134432Z","iopub.status.idle":"2026-09-16T06:42:08.221325Z","shell.execute_reply.started":"2026-09-16T06:41:53.134403Z","shell.execute_reply":"2026-09-16T06:42:08.220276Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Learning Curves\n\nfrom matplotlib import pyplot\n\npyplot.figure(figsize=(10, 8))\n\n# plot loss\npyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history_vgg1.history['loss'], color='blue', label='train')\npyplot.plot(history_vgg1.history['val_loss'], color='orange', label='validation')\npyplot.legend()\n\n# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history_vgg1.history['accuracy'], color='blue', label='train')\npyplot.plot(history_vgg1.history['val_accuracy'], color='orange', label='validation')\npyplot.legend()\n\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:38:15.876850Z","iopub.execute_input":"2026-09-16T07:38:15.877345Z","iopub.status.idle":"2026-09-16T07:38:16.455802Z","shell.execute_reply.started":"2026-09-16T07:38:15.877312Z","shell.execute_reply":"2026-09-16T07:38:16.454668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n\nsummarize_diagnostics(history_vgg1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T06:53:25.757119Z","iopub.execute_input":"2026-09-16T06:53:25.757977Z","iopub.status.idle":"2026-09-16T06:53:26.214170Z","shell.execute_reply.started":"2026-09-16T06:53:25.757928Z","shell.execute_reply":"2026-09-16T06:53:26.213135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_vgg1.evaluate(vgg1_val, steps=len(vgg1_val), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:41:32.662562Z","iopub.execute_input":"2026-09-16T07:41:32.662913Z","iopub.status.idle":"2026-09-16T07:41:45.837349Z","shell.execute_reply.started":"2026-09-16T07:41:32.662863Z","shell.execute_reply":"2026-09-16T07:41:45.836410Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model for the test set\n_, test_acc = model_vgg1.evaluate(vgg1_val, steps=len(vgg1_val), verbose=1)\nprint('Test: > %.3f' % (test_acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:42:09.263352Z","iopub.execute_input":"2026-09-16T07:42:09.264196Z","iopub.status.idle":"2026-09-16T07:42:21.804137Z","shell.execute_reply.started":"2026-09-16T07:42:09.264158Z","shell.execute_reply":"2026-09-16T07:42:21.803262Z"}},"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\nvgg1_val.reset()\n\n# 2. Extract the ordered ground truth labels from the generator\ny_true = np.array(vgg1_val.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(vgg1_val.samples / vgg1_val.batch_size)\nprobabilities = model_vgg1.predict(vgg1_val, steps=steps, verbose=1).squeeze()\nprint(probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:49:37.845813Z","iopub.execute_input":"2026-09-16T07:49:37.846368Z","iopub.status.idle":"2026-09-16T07:49:52.869798Z","shell.execute_reply.started":"2026-09-16T07:49:37.846336Z","shell.execute_reply":"2026-09-16T07:49:52.868957Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:49:55.538750Z","iopub.execute_input":"2026-09-16T07:49:55.539156Z","iopub.status.idle":"2026-09-16T07:49:55.546341Z","shell.execute_reply.started":"2026-09-16T07:49:55.539126Z","shell.execute_reply":"2026-09-16T07:49:55.545305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:49:57.908089Z","iopub.execute_input":"2026-09-16T07:49:57.908978Z","iopub.status.idle":"2026-09-16T07:49:57.914924Z","shell.execute_reply.started":"2026-09-16T07:49:57.908939Z","shell.execute_reply":"2026-09-16T07:49:57.913929Z"}},"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(vgg1_test.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-16T07:53:13.903949Z","iopub.execute_input":"2026-09-16T07:53:13.904368Z","iopub.status.idle":"2026-09-16T07:53:13.925760Z","shell.execute_reply.started":"2026-09-16T07:53:13.904338Z","shell.execute_reply":"2026-09-16T07:53:13.924791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:53:16.692997Z","iopub.execute_input":"2026-09-16T07:53:16.693412Z","iopub.status.idle":"2026-09-16T07:53:16.702036Z","shell.execute_reply.started":"2026-09-16T07:53:16.693381Z","shell.execute_reply":"2026-09-16T07:53:16.700869Z"}},"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(vgg1_test)\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=min(100, all_images.shape[0]), 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_vgg1.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'}\n\nprint(\"Done.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T07:56:23.209096Z","iopub.execute_input":"2026-09-16T07:56:23.209955Z","iopub.status.idle":"2026-09-16T07:56:24.200001Z","shell.execute_reply.started":"2026-09-16T07:56:23.209856Z","shell.execute_reply":"2026-09-16T07:56:24.198652Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_list = []\nlabels_list = []\n\nwhile sum(len(x) for x in images_list) < 100:\n    batch_images, batch_labels = next(vgg1_test)\n    images_list.append(batch_images)\n    labels_list.append(batch_labels)\n\n# Combine all batches\nall_images = np.concatenate(images_list, axis=0)\nall_labels = np.concatenate(labels_list, axis=0)\n\n# Randomly select 100 images\nnp.random.seed(42)\n\nrandom_indices = np.random.choice(\n    all_images.shape[0],\n    size=100,\n    replace=False\n)\n\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\n\n\n\n\nprobabilities = model_vgg1.predict(\n    sample_images,\n    verbose=1\n).reshape(-1)\n\n# Convert probability to class\npredictions = (probabilities > 0.5).astype(int)\n\nclass_mapping = {\n    0: 'Cat',\n    1: 'Dog'\n}\n\n\n\n\nfig, axes = plt.subplots(\n    10, 10,\n    figsize=(20, 20)\n)\n\naxes = axes.flatten()\n\nfor i in range(100):\n\n    ax = axes[i]\n\n    # Get image\n    img = sample_images[i]\n\n    # Normalize image for displaying\n    if img.max() > 1.0 or img.min() < 0:\n        img = (img - img.min()) / (img.max() - img.min())\n\n    ax.imshow(img)\n    ax.axis('off')\n\n    # True label\n    gt_class = class_mapping[int(sample_labels[i])]\n\n    # Predicted label\n    pred_class = class_mapping[int(predictions[i])]\n\n    # Probability\n    prob = probabilities[i]\n\n    # Green = correct\n    # Red = incorrect\n    if gt_class == pred_class:\n        text_color = 'darkgreen'\n    else:\n        text_color = 'darkred'\n\n    # Title\n    title_str = (\n        f\"GT: {gt_class}\\n\"\n        f\"Pred: {pred_class}\\n\"\n        f\"Prob: {prob:.3f}\"\n    )\n\n    ax.set_title(\n        title_str,\n        color=text_color,\n        fontsize=8,\n        pad=2\n    )\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T08:07:42.128220Z","iopub.execute_input":"2026-09-16T08:07:42.129065Z","iopub.status.idle":"2026-09-16T08:07:53.508158Z","shell.execute_reply.started":"2026-09-16T08:07:42.129028Z","shell.execute_reply":"2026-09-16T08:07:53.506316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T02:33:06.758306Z","iopub.status.idle":"2026-09-16T02:33:06.758638Z","shell.execute_reply.started":"2026-09-16T02:33:06.758490Z","shell.execute_reply":"2026-09-16T02:33:06.758506Z"}},"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-16T02:33:06.760248Z","iopub.status.idle":"2026-09-16T02:33:06.760701Z","shell.execute_reply.started":"2026-09-16T02:33:06.760458Z","shell.execute_reply":"2026-09-16T02:33:06.760479Z"}},"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-16T02:33:06.762084Z","iopub.status.idle":"2026-09-16T02:33:06.762486Z","shell.execute_reply.started":"2026-09-16T02:33:06.762346Z","shell.execute_reply":"2026-09-16T02:33:06.762361Z"}},"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-16T02:33:06.763718Z","iopub.status.idle":"2026-09-16T02:33:06.764183Z","shell.execute_reply.started":"2026-09-16T02:33:06.763937Z","shell.execute_reply":"2026-09-16T02:33:06.763958Z"}},"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-16T02:33:06.766749Z","iopub.status.idle":"2026-09-16T02:33:06.767184Z","shell.execute_reply.started":"2026-09-16T02:33:06.766957Z","shell.execute_reply":"2026-09-16T02:33:06.766976Z"}},"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-16T02:33:06.768082Z","iopub.status.idle":"2026-09-16T02:33:06.768503Z","shell.execute_reply.started":"2026-09-16T02:33:06.768295Z","shell.execute_reply":"2026-09-16T02:33:06.768314Z"}},"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-16T02:33:06.769832Z","iopub.status.idle":"2026-09-16T02:33:06.770255Z","shell.execute_reply.started":"2026-09-16T02:33:06.770023Z","shell.execute_reply":"2026-09-16T02:33:06.770042Z"}},"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-16T02:33:06.771634Z","iopub.status.idle":"2026-09-16T02:33:06.772170Z","shell.execute_reply.started":"2026-09-16T02:33:06.771884Z","shell.execute_reply":"2026-09-16T02:33:06.771907Z"}},"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-16T02:33:06.773530Z","iopub.status.idle":"2026-09-16T02:33:06.774001Z","shell.execute_reply.started":"2026-09-16T02:33:06.773733Z","shell.execute_reply":"2026-09-16T02:33:06.773754Z"}},"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-16T02:33:06.776525Z","iopub.status.idle":"2026-09-16T02:33:06.776866Z","shell.execute_reply.started":"2026-09-16T02:33:06.776712Z","shell.execute_reply":"2026-09-16T02:33:06.776728Z"}},"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-16T02:33:06.778420Z","iopub.status.idle":"2026-09-16T02:33:06.778879Z","shell.execute_reply.started":"2026-09-16T02:33:06.778656Z","shell.execute_reply":"2026-09-16T02:33:06.778676Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T02:33:06.780050Z","iopub.status.idle":"2026-09-16T02:33:06.780480Z","shell.execute_reply.started":"2026-09-16T02:33:06.780265Z","shell.execute_reply":"2026-09-16T02:33:06.780286Z"}},"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-16T02:33:06.782039Z","iopub.status.idle":"2026-09-16T02:33:06.782511Z","shell.execute_reply.started":"2026-09-16T02:33:06.782303Z","shell.execute_reply":"2026-09-16T02:33:06.782322Z"}},"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-16T02:33:06.783874Z","iopub.status.idle":"2026-09-16T02:33:06.784311Z","shell.execute_reply.started":"2026-09-16T02:33:06.784084Z","shell.execute_reply":"2026-09-16T02:33:06.784105Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}