{"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-10-02T14:42:04.182557Z","iopub.execute_input":"2026-10-02T14:42:04.183104Z","iopub.status.idle":"2026-10-02T14:42:04.188104Z","shell.execute_reply.started":"2026-10-02T14:42:04.183054Z","shell.execute_reply":"2026-10-02T14:42:04.187244Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:04.189892Z","iopub.execute_input":"2026-10-02T14:42:04.190711Z","iopub.status.idle":"2026-10-02T14:42:05.313688Z","shell.execute_reply.started":"2026-10-02T14:42:04.190686Z","shell.execute_reply":"2026-10-02T14:42:05.312547Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:05.316057Z","iopub.execute_input":"2026-10-02T14:42:05.316719Z","iopub.status.idle":"2026-10-02T14:42:06.424955Z","shell.execute_reply.started":"2026-10-02T14:42:05.316685Z","shell.execute_reply":"2026-10-02T14:42:06.423966Z"}},"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-10-02T14:42:06.426592Z","iopub.execute_input":"2026-10-02T14:42:06.426949Z","iopub.status.idle":"2026-10-02T14:42:16.512989Z","shell.execute_reply.started":"2026-10-02T14:42:06.426913Z","shell.execute_reply":"2026-10-02T14:42:16.511919Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:16.515461Z","iopub.execute_input":"2026-10-02T14:42:16.515836Z","iopub.status.idle":"2026-10-02T14:42:17.60091Z","shell.execute_reply.started":"2026-10-02T14:42:16.5158Z","shell.execute_reply":"2026-10-02T14:42:17.599834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:17.602547Z","iopub.execute_input":"2026-10-02T14:42:17.602951Z","iopub.status.idle":"2026-10-02T14:42:18.717944Z","shell.execute_reply.started":"2026-10-02T14:42:17.602923Z","shell.execute_reply":"2026-10-02T14:42:18.716595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:18.719813Z","iopub.execute_input":"2026-10-02T14:42:18.720773Z","iopub.status.idle":"2026-10-02T14:42:19.850679Z","shell.execute_reply.started":"2026-10-02T14:42:18.72073Z","shell.execute_reply":"2026-10-02T14:42:19.849571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:19.852207Z","iopub.execute_input":"2026-10-02T14:42:19.852579Z","iopub.status.idle":"2026-10-02T14:42:21.002489Z","shell.execute_reply.started":"2026-10-02T14:42:19.852541Z","shell.execute_reply":"2026-10-02T14:42:21.001348Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:21.004014Z","iopub.execute_input":"2026-10-02T14:42:21.004317Z","iopub.status.idle":"2026-10-02T14:42:21.008682Z","shell.execute_reply.started":"2026-10-02T14:42:21.00429Z","shell.execute_reply":"2026-10-02T14:42:21.007878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:21.010025Z","iopub.execute_input":"2026-10-02T14:42:21.010355Z","iopub.status.idle":"2026-10-02T14:42:22.147532Z","shell.execute_reply.started":"2026-10-02T14:42:21.010328Z","shell.execute_reply":"2026-10-02T14:42:22.146157Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:22.151496Z","iopub.execute_input":"2026-10-02T14:42:22.151807Z","iopub.status.idle":"2026-10-02T14:42:23.281806Z","shell.execute_reply.started":"2026-10-02T14:42:22.151768Z","shell.execute_reply":"2026-10-02T14:42:23.280716Z"}},"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-10-02T14:42:23.283369Z","iopub.execute_input":"2026-10-02T14:42:23.283719Z","iopub.status.idle":"2026-10-02T14:42:24.627349Z","shell.execute_reply.started":"2026-10-02T14:42:23.283689Z","shell.execute_reply":"2026-10-02T14:42:24.626473Z"},"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-10-02T14:42:24.628711Z","iopub.execute_input":"2026-10-02T14:42:24.629057Z","iopub.status.idle":"2026-10-02T14:42:25.682496Z","shell.execute_reply.started":"2026-10-02T14:42:24.629023Z","shell.execute_reply":"2026-10-02T14:42:25.68153Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:25.683882Z","iopub.execute_input":"2026-10-02T14:42:25.684281Z","iopub.status.idle":"2026-10-02T14:42:26.775985Z","shell.execute_reply.started":"2026-10-02T14:42:25.684243Z","shell.execute_reply":"2026-10-02T14:42:26.774708Z"}},"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-10-02T14:42:26.778969Z","iopub.execute_input":"2026-10-02T14:42:26.77964Z","iopub.status.idle":"2026-10-02T14:42:26.785497Z","shell.execute_reply.started":"2026-10-02T14:42:26.779592Z","shell.execute_reply":"2026-10-02T14:42:26.784562Z"}},"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-10-02T14:42:26.787096Z","iopub.execute_input":"2026-10-02T14:42:26.787481Z","iopub.status.idle":"2026-10-02T14:42:26.798355Z","shell.execute_reply.started":"2026-10-02T14:42:26.787446Z","shell.execute_reply":"2026-10-02T14:42:26.797407Z"},"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-10-02T14:42:26.799555Z","iopub.execute_input":"2026-10-02T14:42:26.799831Z","iopub.status.idle":"2026-10-02T14:42:26.811665Z","shell.execute_reply.started":"2026-10-02T14:42:26.799808Z","shell.execute_reply":"2026-10-02T14:42:26.810788Z"},"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-10-02T14:42:26.812879Z","iopub.execute_input":"2026-10-02T14:42:26.813657Z","iopub.status.idle":"2026-10-02T14:42:26.820556Z","shell.execute_reply.started":"2026-10-02T14:42:26.813633Z","shell.execute_reply":"2026-10-02T14:42:26.819591Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:26.821767Z","iopub.execute_input":"2026-10-02T14:42:26.822292Z","iopub.status.idle":"2026-10-02T14:42:27.919716Z","shell.execute_reply.started":"2026-10-02T14:42:26.822268Z","shell.execute_reply":"2026-10-02T14:42:27.91872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:27.921126Z","iopub.execute_input":"2026-10-02T14:42:27.921569Z","iopub.status.idle":"2026-10-02T14:42:28.976303Z","shell.execute_reply.started":"2026-10-02T14:42:27.921495Z","shell.execute_reply":"2026-10-02T14:42:28.975362Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test #validation","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:28.977887Z","iopub.execute_input":"2026-10-02T14:42:28.978266Z","iopub.status.idle":"2026-10-02T14:42:30.075687Z","shell.execute_reply.started":"2026-10-02T14:42:28.978239Z","shell.execute_reply":"2026-10-02T14:42:30.074709Z"}},"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-10-02T14:42:30.077323Z","iopub.execute_input":"2026-10-02T14:42:30.077938Z","iopub.status.idle":"2026-10-02T14:42:33.098247Z","shell.execute_reply.started":"2026-10-02T14:42:30.077908Z","shell.execute_reply":"2026-10-02T14:42:33.096951Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:33.099642Z","iopub.execute_input":"2026-10-02T14:42:33.101108Z","iopub.status.idle":"2026-10-02T14:42:33.106699Z","shell.execute_reply.started":"2026-10-02T14:42:33.101078Z","shell.execute_reply":"2026-10-02T14:42:33.105635Z"}},"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-10-02T14:42:33.107856Z","iopub.execute_input":"2026-10-02T14:42:33.108076Z","iopub.status.idle":"2026-10-02T14:42:36.119276Z","shell.execute_reply.started":"2026-10-02T14:42:33.108056Z","shell.execute_reply":"2026-10-02T14:42:36.118261Z"},"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-10-02T14:42:36.12089Z","iopub.execute_input":"2026-10-02T14:42:36.121219Z","iopub.status.idle":"2026-10-02T14:42:38.350053Z","shell.execute_reply.started":"2026-10-02T14:42:36.12119Z","shell.execute_reply":"2026-10-02T14:42:38.349037Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-10-02T14:42:38.351683Z","iopub.execute_input":"2026-10-02T14:42:38.352291Z","iopub.status.idle":"2026-10-02T14:42:47.292608Z","shell.execute_reply.started":"2026-10-02T14:42:38.352261Z","shell.execute_reply":"2026-10-02T14:42:47.29135Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-10-02T14:42:47.294475Z","iopub.execute_input":"2026-10-02T14:42:47.294948Z","iopub.status.idle":"2026-10-02T14:42:47.300755Z","shell.execute_reply.started":"2026-10-02T14:42:47.294909Z","shell.execute_reply":"2026-10-02T14:42:47.299734Z"},"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-10-02T14:42:47.301848Z","iopub.execute_input":"2026-10-02T14:42:47.302602Z","iopub.status.idle":"2026-10-02T14:42:47.323552Z","shell.execute_reply.started":"2026-10-02T14:42:47.302555Z","shell.execute_reply":"2026-10-02T14:42:47.322264Z"}},"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-10-02T14:42:47.334721Z","iopub.execute_input":"2026-10-02T14:42:47.335052Z","iopub.status.idle":"2026-10-02T14:42:47.341379Z","shell.execute_reply.started":"2026-10-02T14:42:47.335024Z","shell.execute_reply":"2026-10-02T14:42:47.340299Z"}},"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-10-02T14:42:47.342665Z","iopub.execute_input":"2026-10-02T14:42:47.342965Z","iopub.status.idle":"2026-10-02T14:42:47.356267Z","shell.execute_reply.started":"2026-10-02T14:42:47.342941Z","shell.execute_reply":"2026-10-02T14:42:47.355443Z"}},"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-10-02T14:42:47.357437Z","iopub.execute_input":"2026-10-02T14:42:47.358569Z","iopub.status.idle":"2026-10-02T14:42:47.44422Z","shell.execute_reply.started":"2026-10-02T14:42:47.358528Z","shell.execute_reply":"2026-10-02T14:42:47.443343Z"}},"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-10-02T14:42:47.4457Z","iopub.execute_input":"2026-10-02T14:42:47.446082Z","iopub.status.idle":"2026-10-02T14:42:47.454622Z","shell.execute_reply.started":"2026-10-02T14:42:47.446044Z","shell.execute_reply":"2026-10-02T14:42:47.453588Z"}},"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-10-02T14:42:47.455936Z","iopub.execute_input":"2026-10-02T14:42:47.456756Z","iopub.status.idle":"2026-10-02T14:42:47.532757Z","shell.execute_reply.started":"2026-10-02T14:42:47.456721Z","shell.execute_reply":"2026-10-02T14:42:47.531803Z"}},"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-10-02T14:42:47.533991Z","iopub.execute_input":"2026-10-02T14:42:47.534355Z","iopub.status.idle":"2026-10-02T14:42:47.612334Z","shell.execute_reply.started":"2026-10-02T14:42:47.53432Z","shell.execute_reply":"2026-10-02T14:42:47.611346Z"}},"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-10-02T14:42:47.613636Z","iopub.execute_input":"2026-10-02T14:42:47.613994Z","iopub.status.idle":"2026-10-02T14:42:47.706533Z","shell.execute_reply.started":"2026-10-02T14:42:47.613959Z","shell.execute_reply":"2026-10-02T14:42:47.705448Z"}},"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-10-02T14:42:47.707745Z","iopub.execute_input":"2026-10-02T14:42:47.708024Z","iopub.status.idle":"2026-10-02T14:42:47.714662Z","shell.execute_reply.started":"2026-10-02T14:42:47.708Z","shell.execute_reply":"2026-10-02T14:42:47.713524Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:47.716273Z","iopub.execute_input":"2026-10-02T14:42:47.71662Z","iopub.status.idle":"2026-10-02T14:42:48.77973Z","shell.execute_reply.started":"2026-10-02T14:42:47.716587Z","shell.execute_reply":"2026-10-02T14:42:48.778734Z"}},"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-10-02T14:42:48.781116Z","iopub.execute_input":"2026-10-02T14:42:48.781818Z","iopub.status.idle":"2026-10-02T14:42:48.786697Z","shell.execute_reply.started":"2026-10-02T14:42:48.781789Z","shell.execute_reply":"2026-10-02T14:42:48.785746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.vgg16 import preprocess_input\n\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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-10-02T14:42:48.788026Z","iopub.execute_input":"2026-10-02T14:42:48.788289Z","iopub.status.idle":"2026-10-02T14:42:54.891235Z","shell.execute_reply.started":"2026-10-02T14:42:48.788266Z","shell.execute_reply":"2026-10-02T14:42:54.890048Z"}},"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-10-02T14:42:54.892711Z","iopub.execute_input":"2026-10-02T14:42:54.893108Z","iopub.status.idle":"2026-10-02T14:42:54.901105Z","shell.execute_reply.started":"2026-10-02T14:42:54.89308Z","shell.execute_reply":"2026-10-02T14:42:54.899958Z"}},"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-10-02T14:42:54.902624Z","iopub.execute_input":"2026-10-02T14:42:54.903084Z","iopub.status.idle":"2026-10-02T14:42:54.924145Z","shell.execute_reply.started":"2026-10-02T14:42:54.903055Z","shell.execute_reply":"2026-10-02T14:42:54.923103Z"}},"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-10-02T14:42:54.925545Z","iopub.execute_input":"2026-10-02T14:42:54.925953Z","iopub.status.idle":"2026-10-02T14:42:54.936624Z","shell.execute_reply.started":"2026-10-02T14:42:54.925921Z","shell.execute_reply":"2026-10-02T14:42:54.935556Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:54.937828Z","iopub.execute_input":"2026-10-02T14:42:54.938421Z","iopub.status.idle":"2026-10-02T14:42:54.952021Z","shell.execute_reply.started":"2026-10-02T14:42:54.938367Z","shell.execute_reply":"2026-10-02T14:42:54.951088Z"}},"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-10-02T14:42:54.953326Z","iopub.execute_input":"2026-10-02T14:42:54.953754Z","iopub.status.idle":"2026-10-02T14:42:54.960574Z","shell.execute_reply.started":"2026-10-02T14:42:54.953727Z","shell.execute_reply":"2026-10-02T14:42:54.95965Z"}},"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-10-02T14:42:54.963146Z","iopub.execute_input":"2026-10-02T14:42:54.96408Z","iopub.status.idle":"2026-10-02T14:42:56.104381Z","shell.execute_reply.started":"2026-10-02T14:42:54.964052Z","shell.execute_reply":"2026-10-02T14:42:56.103282Z"}},"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-10-02T14:42:56.106085Z","iopub.execute_input":"2026-10-02T14:42:56.106452Z","iopub.status.idle":"2026-10-02T14:42:56.113585Z","shell.execute_reply.started":"2026-10-02T14:42:56.106414Z","shell.execute_reply":"2026-10-02T14:42:56.112399Z"}},"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-10-02T14:42:56.115Z","iopub.execute_input":"2026-10-02T14:42:56.115829Z","iopub.status.idle":"2026-10-02T14:42:56.130067Z","shell.execute_reply.started":"2026-10-02T14:42:56.115802Z","shell.execute_reply":"2026-10-02T14:42:56.12886Z"}},"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-10-02T14:42:56.131854Z","iopub.execute_input":"2026-10-02T14:42:56.132185Z","iopub.status.idle":"2026-10-02T14:42:56.143762Z","shell.execute_reply.started":"2026-10-02T14:42:56.132158Z","shell.execute_reply":"2026-10-02T14:42:56.142616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:56.145217Z","iopub.execute_input":"2026-10-02T14:42:56.145985Z","iopub.status.idle":"2026-10-02T14:42:56.153841Z","shell.execute_reply.started":"2026-10-02T14:42:56.145947Z","shell.execute_reply":"2026-10-02T14:42:56.152866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:56.155207Z","iopub.execute_input":"2026-10-02T14:42:56.155618Z","iopub.status.idle":"2026-10-02T14:42:56.16768Z","shell.execute_reply.started":"2026-10-02T14:42:56.155591Z","shell.execute_reply":"2026-10-02T14:42:56.166836Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:56.168871Z","iopub.execute_input":"2026-10-02T14:42:56.169319Z","iopub.status.idle":"2026-10-02T14:42:56.180934Z","shell.execute_reply.started":"2026-10-02T14:42:56.169282Z","shell.execute_reply":"2026-10-02T14:42:56.180063Z"}},"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-10-02T14:42:56.182369Z","iopub.execute_input":"2026-10-02T14:42:56.183005Z","iopub.status.idle":"2026-10-02T14:42:56.197306Z","shell.execute_reply.started":"2026-10-02T14:42:56.182977Z","shell.execute_reply":"2026-10-02T14:42:56.196052Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T14:42:56.198919Z","iopub.execute_input":"2026-10-02T14:42:56.199225Z","iopub.status.idle":"2026-10-02T14:42:56.213954Z","shell.execute_reply.started":"2026-10-02T14:42:56.199161Z","shell.execute_reply":"2026-10-02T14:42:56.21297Z"}},"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-10-02T14:42:56.215602Z","iopub.execute_input":"2026-10-02T14:42:56.216046Z","iopub.status.idle":"2026-10-02T14:43:02.41076Z","shell.execute_reply.started":"2026-10-02T14:42:56.216018Z","shell.execute_reply":"2026-10-02T14:43:02.409819Z"}},"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-10-02T14:43:02.411977Z","iopub.execute_input":"2026-10-02T14:43:02.412341Z","iopub.status.idle":"2026-10-02T14:43:02.419755Z","shell.execute_reply.started":"2026-10-02T14:43:02.412315Z","shell.execute_reply":"2026-10-02T14:43:02.418779Z"}},"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-10-02T14:43:02.42129Z","iopub.execute_input":"2026-10-02T14:43:02.421669Z","iopub.status.idle":"2026-10-02T14:43:11.971212Z","shell.execute_reply.started":"2026-10-02T14:43:02.421634Z","shell.execute_reply":"2026-10-02T14:43:11.970231Z"}},"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-10-02T14:43:11.972582Z","iopub.execute_input":"2026-10-02T14:43:11.972932Z","iopub.status.idle":"2026-10-02T14:43:21.292981Z","shell.execute_reply.started":"2026-10-02T14:43:11.9729Z","shell.execute_reply":"2026-10-02T14:43:21.29207Z"}},"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-10-02T14:43:21.294135Z","iopub.execute_input":"2026-10-02T14:43:21.294574Z","iopub.status.idle":"2026-10-02T14:43:21.300629Z","shell.execute_reply.started":"2026-10-02T14:43:21.294532Z","shell.execute_reply":"2026-10-02T14:43:21.299694Z"},"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-10-02T14:43:21.301828Z","iopub.execute_input":"2026-10-02T14:43:21.302108Z","iopub.status.idle":"2026-10-02T14:43:31.058884Z","shell.execute_reply.started":"2026-10-02T14:43:21.302084Z","shell.execute_reply":"2026-10-02T14:43:31.057318Z"}},"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-10-02T14:43:31.060179Z","iopub.execute_input":"2026-10-02T14:43:31.060639Z","iopub.status.idle":"2026-10-02T14:43:31.065294Z","shell.execute_reply.started":"2026-10-02T14:43:31.06061Z","shell.execute_reply":"2026-10-02T14:43:31.064293Z"}},"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-10-02T14:43:31.066386Z","iopub.execute_input":"2026-10-02T14:43:31.066752Z","iopub.status.idle":"2026-10-02T14:43:31.082838Z","shell.execute_reply.started":"2026-10-02T14:43:31.066727Z","shell.execute_reply":"2026-10-02T14:43:31.081792Z"}},"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-10-02T15:56:18.171265Z","iopub.execute_input":"2026-10-02T15:56:18.172011Z","iopub.status.idle":"2026-10-02T15:56:18.177754Z","shell.execute_reply.started":"2026-10-02T15:56:18.171977Z","shell.execute_reply":"2026-10-02T15:56:18.176885Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **VGG16 (Fined-tuning)**","metadata":{}},{"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-10-02T16:46:21.198522Z","iopub.execute_input":"2026-10-02T16:46:21.199433Z","iopub.status.idle":"2026-10-02T16:46:21.549482Z","shell.execute_reply.started":"2026-10-02T16:46:21.199396Z","shell.execute_reply":"2026-10-02T16:46:21.548778Z"}},"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-10-02T16:46:21.550829Z","iopub.execute_input":"2026-10-02T16:46:21.551106Z","iopub.status.idle":"2026-10-02T16:46:23.820469Z","shell.execute_reply.started":"2026-10-02T16:46:21.551081Z","shell.execute_reply":"2026-10-02T16:46:23.819552Z"}},"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-10-02T16:46:23.822339Z","iopub.execute_input":"2026-10-02T16:46:23.823174Z","iopub.status.idle":"2026-10-02T16:46:24.159812Z","shell.execute_reply.started":"2026-10-02T16:46:23.823135Z","shell.execute_reply":"2026-10-02T16:46:24.159023Z"}},"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-10-02T16:46:24.161136Z","iopub.execute_input":"2026-10-02T16:46:24.161717Z","iopub.status.idle":"2026-10-02T16:46:24.166835Z","shell.execute_reply.started":"2026-10-02T16:46:24.161682Z","shell.execute_reply":"2026-10-02T16:46:24.166057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Freeze ชั้นที่ 0 ถึง 15 (Block 1-4 ของ VGG16)\nfor index, layer in enumerate(model_16_feature_extractor.layers):\n    if index <= 15:\n        layer.trainable = False\n    else:\n        layer.trainable = True\n\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-10-02T16:46:24.16883Z","iopub.execute_input":"2026-10-02T16:46:24.169142Z","iopub.status.idle":"2026-10-02T16:46:24.175891Z","shell.execute_reply.started":"2026-10-02T16:46:24.169109Z","shell.execute_reply":"2026-10-02T16:46:24.175193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:46:26.289888Z","iopub.execute_input":"2026-10-02T16:46:26.290196Z","iopub.status.idle":"2026-10-02T16:46:26.295883Z","shell.execute_reply.started":"2026-10-02T16:46:26.290171Z","shell.execute_reply":"2026-10-02T16:46:26.295026Z"}},"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-10-02T16:46:26.452655Z","iopub.execute_input":"2026-10-02T16:46:26.453149Z","iopub.status.idle":"2026-10-02T16:46:26.461657Z","shell.execute_reply.started":"2026-10-02T16:46:26.453124Z","shell.execute_reply":"2026-10-02T16:46:26.460877Z"}},"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-10-02T16:46:26.608071Z","iopub.execute_input":"2026-10-02T16:46:26.608781Z","iopub.status.idle":"2026-10-02T16:46:26.621924Z","shell.execute_reply.started":"2026-10-02T16:46:26.608753Z","shell.execute_reply":"2026-10-02T16:46:26.620913Z"}},"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-10-02T16:46:26.795959Z","iopub.execute_input":"2026-10-02T16:46:26.796909Z","iopub.status.idle":"2026-10-02T16:46:26.810066Z","shell.execute_reply.started":"2026-10-02T16:46:26.796882Z","shell.execute_reply":"2026-10-02T16:46:26.809394Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.layers import Flatten, Dense\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\n# 1. นิยาม Classifier Head ต่อจาก VGG16\nx = Flatten()(model_16_feature_extractor.output)\nx = Dense(128, activation='relu', kernel_initializer='he_uniform')(x)\noutput = Dense(1, activation='sigmoid')(x)\n\n# 2. รวมเป็น Model ใหม่\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output)\n\n# 3. Compile ด้วย Learning Rate ต่ำ (เช่น 0.0001 เพื่อป้องกันไม่ให้น้ำหนักเดิมพัง)\nopt = SGD(learning_rate=0.0001, momentum=0.9) # ใช้ learning_rate แทน lr\nmodel_vgg16.compile(\n    optimizer=opt,\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:46:27.210196Z","iopub.execute_input":"2026-10-02T16:46:27.210895Z","iopub.status.idle":"2026-10-02T16:46:27.244565Z","shell.execute_reply.started":"2026-10-02T16:46:27.210869Z","shell.execute_reply":"2026-10-02T16:46:27.243733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:46:27.604875Z","iopub.execute_input":"2026-10-02T16:46:27.605624Z","iopub.status.idle":"2026-10-02T16:46:27.65027Z","shell.execute_reply.started":"2026-10-02T16:46:27.605597Z","shell.execute_reply":"2026-10-02T16:46:27.648061Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:46:28.005073Z","iopub.execute_input":"2026-10-02T16:46:28.005921Z","iopub.status.idle":"2026-10-02T16:46:28.010895Z","shell.execute_reply.started":"2026-10-02T16:46:28.005891Z","shell.execute_reply":"2026-10-02T16:46:28.00998Z"}},"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-10-02T16:46:28.394549Z","iopub.execute_input":"2026-10-02T16:46:28.395302Z","iopub.status.idle":"2026-10-02T16:46:28.398488Z","shell.execute_reply.started":"2026-10-02T16:46:28.395273Z","shell.execute_reply":"2026-10-02T16:46:28.397539Z"}},"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=20, \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-10-02T16:46:28.942197Z","iopub.execute_input":"2026-10-02T16:46:28.942551Z","iopub.status.idle":"2026-10-02T17:17:15.434884Z","shell.execute_reply.started":"2026-10-02T16:46:28.942475Z","shell.execute_reply":"2026-10-02T17:17:15.43379Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:19:14.430052Z","iopub.execute_input":"2026-10-02T17:19:14.430596Z","iopub.status.idle":"2026-10-02T17:19:14.732937Z","shell.execute_reply.started":"2026-10-02T17:19:14.430561Z","shell.execute_reply":"2026-10-02T17:19:14.732094Z"}},"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-10-02T17:19:14.734433Z","iopub.execute_input":"2026-10-02T17:19:14.73477Z","iopub.status.idle":"2026-10-02T17:19:32.440057Z","shell.execute_reply.started":"2026-10-02T17:19:14.734744Z","shell.execute_reply":"2026-10-02T17:19:32.439206Z"}},"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-10-02T17:19:32.441597Z","iopub.execute_input":"2026-10-02T17:19:32.441965Z","iopub.status.idle":"2026-10-02T17:20:02.384614Z","shell.execute_reply.started":"2026-10-02T17:19:32.441938Z","shell.execute_reply":"2026-10-02T17:20:02.383709Z"}},"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-10-02T17:20:02.385826Z","iopub.execute_input":"2026-10-02T17:20:02.386201Z","iopub.status.idle":"2026-10-02T17:20:29.597918Z","shell.execute_reply.started":"2026-10-02T17:20:02.386166Z","shell.execute_reply":"2026-10-02T17:20:29.596982Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:20:29.599679Z","iopub.execute_input":"2026-10-02T17:20:29.599951Z","iopub.status.idle":"2026-10-02T17:20:29.605861Z","shell.execute_reply.started":"2026-10-02T17:20:29.599926Z","shell.execute_reply":"2026-10-02T17:20:29.60486Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:20:29.606863Z","iopub.execute_input":"2026-10-02T17:20:29.607172Z","iopub.status.idle":"2026-10-02T17:20:29.612076Z","shell.execute_reply.started":"2026-10-02T17:20:29.60715Z","shell.execute_reply":"2026-10-02T17:20:29.611251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. ทำการ Predict ข้อมูลทั้งหมดใน test_it\n# (อย่าลืมตั้งค่า test_it: shuffle=False เพื่อให้ ลำดับของ y_true ตรงกับ y_pred)\nprobabilities = model_vgg16.predict(test_it, steps=len(test_it))\n\n# 2. แปลง Probabilities ให้เป็น 1D array และแปลงเป็น Binary (0 หรือ 1)\ny_pred = (probabilities > 0.5).astype(int).reshape(-1)\n\n# 3. ดึง y_true จาก Generator\ny_true = test_it.classes\n\n# 4. ดึง Class Names\ntarget_names = list(test_it.class_indices.keys())\n\n# 5. แสดงผล Classification Report\nprint(\"y_true shape:\", y_true.shape)\nprint(\"y_pred shape:\", y_pred.shape)\n\nreport = classification_report(y_true, y_pred, target_names=target_names)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:20:29.613234Z","iopub.execute_input":"2026-10-02T17:20:29.613581Z","iopub.status.idle":"2026-10-02T17:20:58.507733Z","shell.execute_reply.started":"2026-10-02T17:20:29.613548Z","shell.execute_reply":"2026-10-02T17:20:58.506784Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:20:58.508829Z","iopub.execute_input":"2026-10-02T17:20:58.509258Z","iopub.status.idle":"2026-10-02T17:20:58.515563Z","shell.execute_reply.started":"2026-10-02T17:20:58.509228Z","shell.execute_reply":"2026-10-02T17:20:58.514564Z"}},"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'}\n\nprint(\"Done.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T17:20:58.516668Z","iopub.execute_input":"2026-10-02T17:20:58.518228Z","iopub.status.idle":"2026-10-02T17:20:59.688258Z","shell.execute_reply.started":"2026-10-02T17:20:58.518197Z","shell.execute_reply":"2026-10-02T17:20:59.687211Z"}},"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-10-02T17:20:59.690298Z","iopub.execute_input":"2026-10-02T17:20:59.690679Z","iopub.status.idle":"2026-10-02T17:21:08.8756Z","shell.execute_reply.started":"2026-10-02T17:20:59.690652Z","shell.execute_reply":"2026-10-02T17:21:08.874206Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **InceptionV3 (Fined-tuning)**","metadata":{}},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.inception_v3 import preprocess_input\n\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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-10-02T15:43:26.374591Z","iopub.execute_input":"2026-10-02T15:43:26.375156Z","iopub.status.idle":"2026-10-02T15:43:29.81324Z","shell.execute_reply.started":"2026-10-02T15:43:26.375123Z","shell.execute_reply":"2026-10-02T15:43:29.812497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================= Block 2 (Fine-tuning Version) =================\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.layers import Dense, GlobalAveragePooling2D, Flatten\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_inceptionv3_finetune():\n    # 1. Load Base Model\n    base_model = InceptionV3(include_top=False, input_shape=(224, 224, 3))\n    \n    # 2. Freeze ชั้นส่วนใหญ่ แล้ว Unfreeze เฉพาะ N ชั้นสุดท้าย (เช่น 50 ชั้นท้าย)\n    for layer in base_model.layers[:-50]:\n        layer.trainable = False\n    for layer in base_model.layers[-50:]:\n        layer.trainable = True\n\n    # 3. Add Classifier Head\n    # (แนะนำ GlobalAveragePooling2D แทน Flatten เพื่อลด Overfitting และจำนวน Parameter)\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dense(256, activation='relu', kernel_initializer='he_uniform')(x)\n    output = Dense(1, activation='sigmoid')(x)\n    \n    model = Model(inputs=base_model.inputs, outputs=output)\n    \n    # 4. Compile ด้วย Learning Rate ที่ต่ำมาก (เช่น 0.0001)\n    opt = SGD(learning_rate=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\nmodel_inceptionv3 = define_model_inceptionv3_finetune()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:43:29.816039Z","iopub.execute_input":"2026-10-02T15:43:29.816674Z","iopub.status.idle":"2026-10-02T15:43:32.015155Z","shell.execute_reply.started":"2026-10-02T15:43:29.816643Z","shell.execute_reply":"2026-10-02T15:43:32.014305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================= Block 2.5 (เพิ่มคั่นเพื่อ Fine-tune) =================\n\n# 1. Unfreeze ชั้นท้ายๆ ของโมเดล\nfor layer in model_inceptionv3.layers[-50:]:\n    layer.trainable = True\n\n# 2. Re-compile ด้วย Learning Rate ที่น้อยลง\nmodel_inceptionv3.compile(\n    optimizer=SGD(learning_rate=0.0001, momentum=0.9),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:43:32.016252Z","iopub.execute_input":"2026-10-02T15:43:32.016974Z","iopub.status.idle":"2026-10-02T15:43:32.032565Z","shell.execute_reply.started":"2026-10-02T15:43:32.016945Z","shell.execute_reply":"2026-10-02T15:43:32.031474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-10-02T15:43:32.034003Z","iopub.execute_input":"2026-10-02T15:43:32.034331Z","iopub.status.idle":"2026-10-02T15:43:34.232926Z","shell.execute_reply.started":"2026-10-02T15:43:32.034309Z","shell.execute_reply":"2026-10-02T15:43:34.232132Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-10-02T15:43:34.233899Z","iopub.execute_input":"2026-10-02T15:43:34.234269Z","iopub.status.idle":"2026-10-02T15:43:34.239328Z","shell.execute_reply.started":"2026-10-02T15:43:34.234242Z","shell.execute_reply":"2026-10-02T15:43:34.238547Z"}},"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-10-02T15:43:34.241053Z","iopub.execute_input":"2026-10-02T15:43:34.241256Z","iopub.status.idle":"2026-10-02T15:43:34.24669Z","shell.execute_reply.started":"2026-10-02T15:43:34.241237Z","shell.execute_reply":"2026-10-02T15:43:34.245807Z"}},"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=5, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:43:34.426899Z","iopub.execute_input":"2026-10-02T15:43:34.427403Z","iopub.status.idle":"2026-10-02T15:49:25.788449Z","shell.execute_reply.started":"2026-10-02T15:43:34.427376Z","shell.execute_reply":"2026-10-02T15:49:25.787711Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# del model_inceptionv3","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:43:14.463256Z","iopub.execute_input":"2026-10-02T15:43:14.464167Z","iopub.status.idle":"2026-10-02T15:43:14.467884Z","shell.execute_reply.started":"2026-10-02T15:43:14.464132Z","shell.execute_reply":"2026-10-02T15:43:14.466895Z"}},"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-10-02T16:43:32.684485Z","iopub.execute_input":"2026-10-02T16:43:32.685425Z","iopub.status.idle":"2026-10-02T16:43:32.6921Z","shell.execute_reply.started":"2026-10-02T16:43:32.685391Z","shell.execute_reply":"2026-10-02T16:43:32.691212Z"}},"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-10-02T15:18:09.354729Z","iopub.execute_input":"2026-10-02T15:18:09.355089Z","iopub.status.idle":"2026-10-02T15:18:09.371409Z","shell.execute_reply.started":"2026-10-02T15:18:09.35506Z","shell.execute_reply":"2026-10-02T15:18:09.370572Z"}},"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-10-02T15:18:09.372798Z","iopub.execute_input":"2026-10-02T15:18:09.373246Z","iopub.status.idle":"2026-10-02T15:18:09.379164Z","shell.execute_reply.started":"2026-10-02T15:18:09.373211Z","shell.execute_reply":"2026-10-02T15:18:09.378215Z"}},"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-10-02T15:18:09.381847Z","iopub.execute_input":"2026-10-02T15:18:09.382681Z","iopub.status.idle":"2026-10-02T15:18:09.391303Z","shell.execute_reply.started":"2026-10-02T15:18:09.382646Z","shell.execute_reply":"2026-10-02T15:18:09.390262Z"}},"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-10-02T15:18:09.39249Z","iopub.execute_input":"2026-10-02T15:18:09.392836Z","iopub.status.idle":"2026-10-02T15:18:39.343162Z","shell.execute_reply.started":"2026-10-02T15:18:09.392803Z","shell.execute_reply":"2026-10-02T15:18:39.342414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# images = test_it.__next__()\n# images.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:18:39.344365Z","iopub.execute_input":"2026-10-02T15:18:39.344974Z","iopub.status.idle":"2026-10-02T15:18:39.348821Z","shell.execute_reply.started":"2026-10-02T15:18:39.344932Z","shell.execute_reply":"2026-10-02T15:18:39.347826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(test_it)  # หรือ val_it\n\n# 2. เลือก 5 รูปแรกมาใช้งาน\nimages_to_predict = images[:5]\nprint(images_to_predict.shape)  # ควรได้ shape เช่น (5, 224, 224, 3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:44:11.652311Z","iopub.execute_input":"2026-10-02T16:44:11.653095Z","iopub.status.idle":"2026-10-02T16:44:11.873762Z","shell.execute_reply.started":"2026-10-02T16:44:11.653059Z","shell.execute_reply":"2026-10-02T16:44:11.872821Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. ดึง Batch ภาพออกมาจาก Generator\nimages, labels = next(val_it)  # หรือเปลี่ยนเป็น test_it\n\n# 2. เลือกเฉพาะ 5 ภาพแรก\nimages_to_predict = images[:5]\n\n# 3. สั่ง ทำนายผล\nprobs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T16:45:04.631378Z","iopub.execute_input":"2026-10-02T16:45:04.632211Z","iopub.status.idle":"2026-10-02T16:45:07.16007Z","shell.execute_reply.started":"2026-10-02T16:45:04.632173Z","shell.execute_reply":"2026-10-02T16:45:07.159267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **EfficientNetB7 (Fined-tuning)**","metadata":{}},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.efficientnet import preprocess_input\n\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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=64,\n    target_size=(224, 224),\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=64,\n    target_size=(224, 224),\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-10-02T15:19:28.25877Z","iopub.execute_input":"2026-10-02T15:19:28.259441Z","iopub.status.idle":"2026-10-02T15:19:36.074315Z","shell.execute_reply.started":"2026-10-02T15:19:28.259405Z","shell.execute_reply":"2026-10-02T15:19:36.073261Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.efficientnet import EfficientNetB0\nfrom keras.layers import Dense, Flatten\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_efficientnet():\n    # load model EfficientNetB0\n    model = EfficientNetB0(include_top=False, input_shape=(224, 224, 3))\n    \n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\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')(class4)\n    \n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    \n    # compile model (หมายเหตุ: Keras เวอร์ชั่นใหม่ใช้ learning_rate แทน lr)\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:19:36.076089Z","iopub.execute_input":"2026-10-02T15:19:36.076703Z","iopub.status.idle":"2026-10-02T15:19:36.083811Z","shell.execute_reply.started":"2026-10-02T15:19:36.076665Z","shell.execute_reply":"2026-10-02T15:19:36.082909Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.efficientnet import EfficientNetB0\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_efficientnet_finetune():\n    base_model = EfficientNetB0(include_top=False, input_shape=(224, 224, 3))\n    \n \n    for layer in base_model.layers[:-20]:\n        layer.trainable = False\n    for layer in base_model.layers[-20:]:\n        layer.trainable = True\n\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dense(256, activation='relu', kernel_initializer='he_uniform')(x)\n    output = Dense(1, activation='sigmoid')(x)\n    \n    model = Model(inputs=base_model.inputs, outputs=output)\n    \n    opt = SGD(learning_rate=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\nmodel_inceptionv3 = define_model_efficientnet_finetune()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:19:36.084896Z","iopub.execute_input":"2026-10-02T15:19:36.085152Z","iopub.status.idle":"2026-10-02T15:19:38.782479Z","shell.execute_reply.started":"2026-10-02T15:19:36.08513Z","shell.execute_reply":"2026-10-02T15:19:38.781733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKerasTF\nfrom keras.optimizers import SGD\n\n# 2. Unfreeze บางชั้นในตัวโมเดลเดิม (ถ้ายังไม่ได้ unfreeze)\nfor layer in model_inceptionv3.layers[-30:]:\n    layer.trainable = True\n\n# 3. Re-compile ใหม่ด้วย Learning Rate ที่เล็กลง\nmodel_inceptionv3.compile(\n    optimizer=SGD(learning_rate=0.0001, momentum=0.9),\n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\n# 4. เทรน Fine-tuning ต่อ\nhistory_finetune = 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=7, \n    verbose=1,\n    callbacks=[PlotLossesKerasTF()]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T15:20:55.646071Z","iopub.execute_input":"2026-10-02T15:20:55.64679Z","iopub.status.idle":"2026-10-02T15:29:04.465699Z","shell.execute_reply.started":"2026-10-02T15:20:55.646754Z","shell.execute_reply":"2026-10-02T15:29:04.464646Z"}},"outputs":[],"execution_count":null}]}