{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2026-09-16T15:33:35.505676Z","iopub.execute_input":"2026-09-16T15:33:35.506020Z","iopub.status.idle":"2026-09-16T15:33:35.855059Z","shell.execute_reply.started":"2026-09-16T15:33:35.505988Z","shell.execute_reply":"2026-09-16T15:33:35.853873Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:35.856336Z","iopub.execute_input":"2026-09-16T15:33:35.856722Z","iopub.status.idle":"2026-09-16T15:33:36.986063Z","shell.execute_reply.started":"2026-09-16T15:33:35.856698Z","shell.execute_reply":"2026-09-16T15:33:36.984615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:36.989336Z","iopub.execute_input":"2026-09-16T15:33:36.989708Z","iopub.status.idle":"2026-09-16T15:33:38.066265Z","shell.execute_reply.started":"2026-09-16T15:33:36.989682Z","shell.execute_reply":"2026-09-16T15:33:38.064845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:33:38.068219Z","iopub.execute_input":"2026-09-16T15:33:38.068601Z","iopub.status.idle":"2026-09-16T15:33:49.654425Z","shell.execute_reply.started":"2026-09-16T15:33:38.068561Z","shell.execute_reply":"2026-09-16T15:33:49.653341Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:49.655859Z","iopub.execute_input":"2026-09-16T15:33:49.656161Z","iopub.status.idle":"2026-09-16T15:33:50.707960Z","shell.execute_reply.started":"2026-09-16T15:33:49.656137Z","shell.execute_reply":"2026-09-16T15:33:50.706699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:50.709613Z","iopub.execute_input":"2026-09-16T15:33:50.710510Z","iopub.status.idle":"2026-09-16T15:33:51.734882Z","shell.execute_reply.started":"2026-09-16T15:33:50.710474Z","shell.execute_reply":"2026-09-16T15:33:51.733853Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:51.736324Z","iopub.execute_input":"2026-09-16T15:33:51.736620Z","iopub.status.idle":"2026-09-16T15:33:52.826175Z","shell.execute_reply.started":"2026-09-16T15:33:51.736597Z","shell.execute_reply":"2026-09-16T15:33:52.824865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:52.827721Z","iopub.execute_input":"2026-09-16T15:33:52.828108Z","iopub.status.idle":"2026-09-16T15:33:53.958838Z","shell.execute_reply.started":"2026-09-16T15:33:52.828061Z","shell.execute_reply":"2026-09-16T15:33:53.957513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:53.962271Z","iopub.execute_input":"2026-09-16T15:33:53.962633Z","iopub.status.idle":"2026-09-16T15:33:53.966991Z","shell.execute_reply.started":"2026-09-16T15:33:53.962607Z","shell.execute_reply":"2026-09-16T15:33:53.966032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:53.968233Z","iopub.execute_input":"2026-09-16T15:33:53.968712Z","iopub.status.idle":"2026-09-16T15:33:55.236635Z","shell.execute_reply.started":"2026-09-16T15:33:53.968688Z","shell.execute_reply":"2026-09-16T15:33:55.235370Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:55.238404Z","iopub.execute_input":"2026-09-16T15:33:55.238938Z","iopub.status.idle":"2026-09-16T15:33:56.347106Z","shell.execute_reply.started":"2026-09-16T15:33:55.238888Z","shell.execute_reply":"2026-09-16T15:33:56.346099Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\n# from matplotlib import pyplot as plt\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:33:56.348665Z","iopub.execute_input":"2026-09-16T15:33:56.349099Z","iopub.status.idle":"2026-09-16T15:33:57.412303Z","shell.execute_reply.started":"2026-09-16T15:33:56.349058Z","shell.execute_reply":"2026-09-16T15:33:57.411499Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:33:57.413352Z","iopub.execute_input":"2026-09-16T15:33:57.414312Z","iopub.status.idle":"2026-09-16T15:33:58.454606Z","shell.execute_reply.started":"2026-09-16T15:33:57.414277Z","shell.execute_reply":"2026-09-16T15:33:58.453765Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:33:58.456041Z","iopub.execute_input":"2026-09-16T15:33:58.456527Z","iopub.status.idle":"2026-09-16T15:33:59.487939Z","shell.execute_reply.started":"2026-09-16T15:33:58.456474Z","shell.execute_reply":"2026-09-16T15:33:59.486547Z"}},"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-16T15:33:59.489570Z","iopub.execute_input":"2026-09-16T15:33:59.490440Z","iopub.status.idle":"2026-09-16T15:34:11.803727Z","shell.execute_reply.started":"2026-09-16T15:33:59.490408Z","shell.execute_reply":"2026-09-16T15:34:11.802876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:11.805181Z","iopub.execute_input":"2026-09-16T15:34:11.805895Z","iopub.status.idle":"2026-09-16T15:34:11.812279Z","shell.execute_reply.started":"2026-09-16T15:34:11.805860Z","shell.execute_reply":"2026-09-16T15:34:11.811283Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:11.813310Z","iopub.execute_input":"2026-09-16T15:34:11.813639Z","iopub.status.idle":"2026-09-16T15:34:11.834323Z","shell.execute_reply.started":"2026-09-16T15:34:11.813616Z","shell.execute_reply":"2026-09-16T15:34:11.833331Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:11.835491Z","iopub.execute_input":"2026-09-16T15:34:11.835868Z","iopub.status.idle":"2026-09-16T15:34:11.847044Z","shell.execute_reply.started":"2026-09-16T15:34:11.835816Z","shell.execute_reply":"2026-09-16T15:34:11.845962Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:34:11.848235Z","iopub.execute_input":"2026-09-16T15:34:11.848776Z","iopub.status.idle":"2026-09-16T15:34:12.857737Z","shell.execute_reply.started":"2026-09-16T15:34:11.848750Z","shell.execute_reply":"2026-09-16T15:34:12.856714Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:34:12.859238Z","iopub.execute_input":"2026-09-16T15:34:12.859536Z","iopub.status.idle":"2026-09-16T15:34:13.888816Z","shell.execute_reply.started":"2026-09-16T15:34:12.859511Z","shell.execute_reply":"2026-09-16T15:34:13.887866Z"}},"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-16T15:34:13.890225Z","iopub.execute_input":"2026-09-16T15:34:13.890514Z","iopub.status.idle":"2026-09-16T15:34:14.926052Z","shell.execute_reply.started":"2026-09-16T15:34:13.890488Z","shell.execute_reply":"2026-09-16T15:34:14.925113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:14.927549Z","iopub.execute_input":"2026-09-16T15:34:14.928015Z","iopub.status.idle":"2026-09-16T15:34:17.016564Z","shell.execute_reply.started":"2026-09-16T15:34:14.927986Z","shell.execute_reply":"2026-09-16T15:34:17.015829Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:34:17.017736Z","iopub.execute_input":"2026-09-16T15:34:17.018067Z","iopub.status.idle":"2026-09-16T15:34:17.022583Z","shell.execute_reply.started":"2026-09-16T15:34:17.018046Z","shell.execute_reply":"2026-09-16T15:34:17.021457Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:17.023748Z","iopub.execute_input":"2026-09-16T15:34:17.024471Z","iopub.status.idle":"2026-09-16T15:34:19.220521Z","shell.execute_reply.started":"2026-09-16T15:34:17.024419Z","shell.execute_reply":"2026-09-16T15:34:19.219567Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:19.222060Z","iopub.execute_input":"2026-09-16T15:34:19.222365Z","iopub.status.idle":"2026-09-16T15:34:21.346950Z","shell.execute_reply.started":"2026-09-16T15:34:19.222340Z","shell.execute_reply":"2026-09-16T15:34:21.345946Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:21.348647Z","iopub.execute_input":"2026-09-16T15:34:21.349116Z","iopub.status.idle":"2026-09-16T15:34:31.883780Z","shell.execute_reply.started":"2026-09-16T15:34:21.349087Z","shell.execute_reply":"2026-09-16T15:34:31.882780Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:34:31.890430Z","iopub.execute_input":"2026-09-16T15:34:31.890879Z","iopub.status.idle":"2026-09-16T15:34:31.905024Z","shell.execute_reply.started":"2026-09-16T15:34:31.890844Z","shell.execute_reply":"2026-09-16T15:34:31.904193Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:34:31.906217Z","iopub.execute_input":"2026-09-16T15:34:31.906533Z","iopub.status.idle":"2026-09-16T15:34:31.913666Z","shell.execute_reply.started":"2026-09-16T15:34:31.906508Z","shell.execute_reply":"2026-09-16T15:34:31.912872Z"}},"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-16T15:34:31.914692Z","iopub.execute_input":"2026-09-16T15:34:31.914960Z","iopub.status.idle":"2026-09-16T15:34:31.923559Z","shell.execute_reply.started":"2026-09-16T15:34:31.914939Z","shell.execute_reply":"2026-09-16T15:34:31.922871Z"}},"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-16T15:34:31.924727Z","iopub.execute_input":"2026-09-16T15:34:31.925050Z","iopub.status.idle":"2026-09-16T15:34:31.934200Z","shell.execute_reply.started":"2026-09-16T15:34:31.925022Z","shell.execute_reply":"2026-09-16T15:34:31.933360Z"}},"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-16T15:34:31.935207Z","iopub.execute_input":"2026-09-16T15:34:31.935497Z","iopub.status.idle":"2026-09-16T15:34:33.934943Z","shell.execute_reply.started":"2026-09-16T15:34:31.935471Z","shell.execute_reply":"2026-09-16T15:34:33.933469Z"}},"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-16T15:34:33.936304Z","iopub.execute_input":"2026-09-16T15:34:33.936671Z","iopub.status.idle":"2026-09-16T15:34:33.943638Z","shell.execute_reply.started":"2026-09-16T15:34:33.936636Z","shell.execute_reply":"2026-09-16T15:34:33.942696Z"}},"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-16T15:34:33.944780Z","iopub.execute_input":"2026-09-16T15:34:33.945188Z","iopub.status.idle":"2026-09-16T15:34:34.149975Z","shell.execute_reply.started":"2026-09-16T15:34:33.945164Z","shell.execute_reply":"2026-09-16T15:34:34.148722Z"}},"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-16T15:34:34.151249Z","iopub.execute_input":"2026-09-16T15:34:34.151836Z","iopub.status.idle":"2026-09-16T15:34:34.234864Z","shell.execute_reply.started":"2026-09-16T15:34:34.151775Z","shell.execute_reply":"2026-09-16T15:34:34.233884Z"}},"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-16T15:34:34.236346Z","iopub.execute_input":"2026-09-16T15:34:34.236755Z","iopub.status.idle":"2026-09-16T15:34:34.339489Z","shell.execute_reply.started":"2026-09-16T15:34:34.236719Z","shell.execute_reply":"2026-09-16T15:34:34.338359Z"}},"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-16T15:34:34.340724Z","iopub.execute_input":"2026-09-16T15:34:34.341058Z","iopub.status.idle":"2026-09-16T15:34:34.347781Z","shell.execute_reply.started":"2026-09-16T15:34:34.341033Z","shell.execute_reply":"2026-09-16T15:34:34.346919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:34:34.349187Z","iopub.execute_input":"2026-09-16T15:34:34.349589Z","iopub.status.idle":"2026-09-16T15:34:35.392867Z","shell.execute_reply.started":"2026-09-16T15:34:34.349565Z","shell.execute_reply":"2026-09-16T15:34:35.391516Z"}},"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-16T15:34:35.394428Z","iopub.execute_input":"2026-09-16T15:34:35.395172Z","iopub.status.idle":"2026-09-16T15:34:35.399641Z","shell.execute_reply.started":"2026-09-16T15:34:35.395143Z","shell.execute_reply":"2026-09-16T15:34:35.398652Z"}},"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-16T15:34:35.400728Z","iopub.execute_input":"2026-09-16T15:34:35.401043Z","iopub.status.idle":"2026-09-16T15:35:01.359607Z","shell.execute_reply.started":"2026-09-16T15:34:35.401021Z","shell.execute_reply":"2026-09-16T15:35:01.358729Z"}},"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-16T15:35:01.360778Z","iopub.execute_input":"2026-09-16T15:35:01.361451Z","iopub.status.idle":"2026-09-16T15:35:01.368682Z","shell.execute_reply.started":"2026-09-16T15:35:01.361423Z","shell.execute_reply":"2026-09-16T15:35:01.367584Z"}},"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-16T15:35:01.369651Z","iopub.execute_input":"2026-09-16T15:35:01.369949Z","iopub.status.idle":"2026-09-16T15:35:01.384846Z","shell.execute_reply.started":"2026-09-16T15:35:01.369928Z","shell.execute_reply":"2026-09-16T15:35:01.383855Z"}},"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-16T15:35:01.386104Z","iopub.execute_input":"2026-09-16T15:35:01.386679Z","iopub.status.idle":"2026-09-16T15:35:01.396572Z","shell.execute_reply.started":"2026-09-16T15:35:01.386649Z","shell.execute_reply":"2026-09-16T15:35:01.395541Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:01.397810Z","iopub.execute_input":"2026-09-16T15:35:01.398158Z","iopub.status.idle":"2026-09-16T15:35:01.405725Z","shell.execute_reply.started":"2026-09-16T15:35:01.398128Z","shell.execute_reply":"2026-09-16T15:35:01.404863Z"}},"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-16T15:35:01.407074Z","iopub.execute_input":"2026-09-16T15:35:01.407441Z","iopub.status.idle":"2026-09-16T15:35:01.416414Z","shell.execute_reply.started":"2026-09-16T15:35:01.407415Z","shell.execute_reply":"2026-09-16T15:35:01.415475Z"}},"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-16T15:35:01.417595Z","iopub.execute_input":"2026-09-16T15:35:01.418065Z","iopub.status.idle":"2026-09-16T15:35:02.483305Z","shell.execute_reply.started":"2026-09-16T15:35:01.418010Z","shell.execute_reply":"2026-09-16T15:35:02.482371Z"}},"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-16T15:35:02.484939Z","iopub.execute_input":"2026-09-16T15:35:02.485323Z","iopub.status.idle":"2026-09-16T15:35:02.490894Z","shell.execute_reply.started":"2026-09-16T15:35:02.485296Z","shell.execute_reply":"2026-09-16T15:35:02.490003Z"}},"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-16T15:35:02.492175Z","iopub.execute_input":"2026-09-16T15:35:02.492567Z","iopub.status.idle":"2026-09-16T15:35:02.506277Z","shell.execute_reply.started":"2026-09-16T15:35:02.492546Z","shell.execute_reply":"2026-09-16T15:35:02.505494Z"}},"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-16T15:35:02.507473Z","iopub.execute_input":"2026-09-16T15:35:02.507703Z","iopub.status.idle":"2026-09-16T15:35:02.516168Z","shell.execute_reply.started":"2026-09-16T15:35:02.507683Z","shell.execute_reply":"2026-09-16T15:35:02.515357Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:02.517255Z","iopub.execute_input":"2026-09-16T15:35:02.517574Z","iopub.status.idle":"2026-09-16T15:35:02.525742Z","shell.execute_reply.started":"2026-09-16T15:35:02.517552Z","shell.execute_reply":"2026-09-16T15:35:02.524957Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:02.526861Z","iopub.execute_input":"2026-09-16T15:35:02.527276Z","iopub.status.idle":"2026-09-16T15:35:02.536940Z","shell.execute_reply.started":"2026-09-16T15:35:02.527251Z","shell.execute_reply":"2026-09-16T15:35:02.536036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:02.538401Z","iopub.execute_input":"2026-09-16T15:35:02.538707Z","iopub.status.idle":"2026-09-16T15:35:02.545461Z","shell.execute_reply.started":"2026-09-16T15:35:02.538678Z","shell.execute_reply":"2026-09-16T15:35:02.544493Z"}},"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-16T15:35:02.546460Z","iopub.execute_input":"2026-09-16T15:35:02.546760Z","iopub.status.idle":"2026-09-16T15:35:02.555762Z","shell.execute_reply.started":"2026-09-16T15:35:02.546737Z","shell.execute_reply":"2026-09-16T15:35:02.554753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:02.557380Z","iopub.execute_input":"2026-09-16T15:35:02.558021Z","iopub.status.idle":"2026-09-16T15:35:02.567885Z","shell.execute_reply.started":"2026-09-16T15:35:02.557997Z","shell.execute_reply":"2026-09-16T15:35:02.567011Z"}},"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-16T15:35:02.569025Z","iopub.execute_input":"2026-09-16T15:35:02.569325Z","iopub.status.idle":"2026-09-16T15:35:09.400710Z","shell.execute_reply.started":"2026-09-16T15:35:02.569303Z","shell.execute_reply":"2026-09-16T15:35:09.399940Z"}},"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-16T15:35:09.401966Z","iopub.execute_input":"2026-09-16T15:35:09.402733Z","iopub.status.idle":"2026-09-16T15:35:09.408534Z","shell.execute_reply.started":"2026-09-16T15:35:09.402705Z","shell.execute_reply":"2026-09-16T15:35:09.407597Z"}},"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-16T15:35:09.409633Z","iopub.execute_input":"2026-09-16T15:35:09.410274Z","iopub.status.idle":"2026-09-16T15:35:19.235782Z","shell.execute_reply.started":"2026-09-16T15:35:09.410247Z","shell.execute_reply":"2026-09-16T15:35:19.234332Z"}},"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-16T15:35:19.237451Z","iopub.execute_input":"2026-09-16T15:35:19.237918Z","iopub.status.idle":"2026-09-16T15:35:28.918053Z","shell.execute_reply.started":"2026-09-16T15:35:19.237866Z","shell.execute_reply":"2026-09-16T15:35:28.917025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images, indices):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(indices[i]))  # ตั้งค่า title ด้วย index จาก list/array indices\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:28.919364Z","iopub.execute_input":"2026-09-16T15:35:28.919745Z","iopub.status.idle":"2026-09-16T15:35:28.926044Z","shell.execute_reply.started":"2026-09-16T15:35:28.919719Z","shell.execute_reply":"2026-09-16T15:35:28.924964Z"},"jupyter":{"source_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images, test_labels = test_it.__next__()  # หรือ next(test_it)\nprint(f\"{test_images.shape=}, {test_labels.shape}\")\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple(test_images, test_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:28.927293Z","iopub.execute_input":"2026-09-16T15:35:28.927543Z","iopub.status.idle":"2026-09-16T15:35:38.676364Z","shell.execute_reply.started":"2026-09-16T15:35:28.927520Z","shell.execute_reply":"2026-09-16T15:35:38.673924Z"}},"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-16T15:35:38.677855Z","iopub.execute_input":"2026-09-16T15:35:38.678202Z","iopub.status.idle":"2026-09-16T15:35:38.682978Z","shell.execute_reply.started":"2026-09-16T15:35:38.678161Z","shell.execute_reply":"2026-09-16T15:35:38.682245Z"}},"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-16T15:35:38.684111Z","iopub.execute_input":"2026-09-16T15:35:38.684526Z","iopub.status.idle":"2026-09-16T15:35:38.700172Z","shell.execute_reply.started":"2026-09-16T15:35:38.684467Z","shell.execute_reply":"2026-09-16T15:35:38.699269Z"}},"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-16T15:35:38.701363Z","iopub.execute_input":"2026-09-16T15:35:38.701689Z","iopub.status.idle":"2026-09-16T15:35:38.714677Z","shell.execute_reply.started":"2026-09-16T15:35:38.701658Z","shell.execute_reply":"2026-09-16T15:35:38.713517Z"}},"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-16T15:35:38.716048Z","iopub.execute_input":"2026-09-16T15:35:38.716394Z","iopub.status.idle":"2026-09-16T15:35:39.833215Z","shell.execute_reply.started":"2026-09-16T15:35:38.716372Z","shell.execute_reply":"2026-09-16T15:35:39.832340Z"}},"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-16T15:35:39.834431Z","iopub.execute_input":"2026-09-16T15:35:39.834879Z","iopub.status.idle":"2026-09-16T15:35:46.461264Z","shell.execute_reply.started":"2026-09-16T15:35:39.834843Z","shell.execute_reply":"2026-09-16T15:35:46.460072Z"}},"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-16T15:35:46.468376Z","iopub.execute_input":"2026-09-16T15:35:46.468605Z","iopub.status.idle":"2026-09-16T15:35:46.837908Z","shell.execute_reply.started":"2026-09-16T15:35:46.468585Z","shell.execute_reply":"2026-09-16T15:35:46.836863Z"}},"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-16T15:35:46.839113Z","iopub.execute_input":"2026-09-16T15:35:46.839729Z","iopub.status.idle":"2026-09-16T15:35:46.845439Z","shell.execute_reply.started":"2026-09-16T15:35:46.839701Z","shell.execute_reply":"2026-09-16T15:35:46.844379Z"}},"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-16T15:35:46.846900Z","iopub.execute_input":"2026-09-16T15:35:46.847144Z","iopub.status.idle":"2026-09-16T15:35:46.857447Z","shell.execute_reply.started":"2026-09-16T15:35:46.847122Z","shell.execute_reply":"2026-09-16T15:35:46.856590Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:46.858358Z","iopub.execute_input":"2026-09-16T15:35:46.858689Z","iopub.status.idle":"2026-09-16T15:35:46.869483Z","shell.execute_reply.started":"2026-09-16T15:35:46.858668Z","shell.execute_reply":"2026-09-16T15:35:46.868628Z"}},"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-16T15:35:46.870524Z","iopub.execute_input":"2026-09-16T15:35:46.870774Z","iopub.status.idle":"2026-09-16T15:35:46.882358Z","shell.execute_reply.started":"2026-09-16T15:35:46.870754Z","shell.execute_reply":"2026-09-16T15:35:46.881459Z"}},"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-16T15:35:46.883391Z","iopub.execute_input":"2026-09-16T15:35:46.883700Z","iopub.status.idle":"2026-09-16T15:35:46.908475Z","shell.execute_reply.started":"2026-09-16T15:35:46.883679Z","shell.execute_reply":"2026-09-16T15:35:46.907360Z"}},"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-16T15:35:46.909549Z","iopub.execute_input":"2026-09-16T15:35:46.910399Z","iopub.status.idle":"2026-09-16T15:35:46.923428Z","shell.execute_reply.started":"2026-09-16T15:35:46.910368Z","shell.execute_reply":"2026-09-16T15:35:46.922706Z"}},"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-16T15:35:46.924518Z","iopub.execute_input":"2026-09-16T15:35:46.924905Z","iopub.status.idle":"2026-09-16T15:35:46.942075Z","shell.execute_reply.started":"2026-09-16T15:35:46.924873Z","shell.execute_reply":"2026-09-16T15:35:46.941168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:46.944188Z","iopub.execute_input":"2026-09-16T15:35:46.944645Z","iopub.status.idle":"2026-09-16T15:35:46.995550Z","shell.execute_reply.started":"2026-09-16T15:35:46.944620Z","shell.execute_reply":"2026-09-16T15:35:46.994617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:46.996891Z","iopub.execute_input":"2026-09-16T15:35:46.997181Z","iopub.status.idle":"2026-09-16T15:35:47.002824Z","shell.execute_reply.started":"2026-09-16T15:35:46.997157Z","shell.execute_reply":"2026-09-16T15:35:47.002007Z"}},"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-16T15:35:47.004179Z","iopub.execute_input":"2026-09-16T15:35:47.004705Z","iopub.status.idle":"2026-09-16T15:35:47.011731Z","shell.execute_reply.started":"2026-09-16T15:35:47.004680Z","shell.execute_reply":"2026-09-16T15:35:47.010721Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nimport tensorflow as tf\n\n# 1. Verify that TensorFlow can communicate with the GPU hardware\nphysical_devices = tf.config.list_physical_devices('GPU')\nprint(f\"Hardware status: {len(physical_devices)} GPU(s) detected.\")\n\nif len(physical_devices) > 0:\n    # Optional but highly recommended: Prevent TF from pre-allocating 100% of VRAM\n    try:\n        tf.config.experimental.set_memory_growth(physical_devices[0], True)\n    except Exception as e:\n        print(f\"Memory growth configuration failed: {e}\")\n\n    # 2. Explicitly bind the execution to the primary GPU\n    with tf.device('/GPU:0'):\n        \n        print(f\"Model ID: {id(model_vgg16)}\")\n        \n        # Note: reset_states() is strictly for stateful RNNs (LSTMs/GRUs). \n        # For a feed-forward CNN like VGG16, this method has no effect and can be removed.\n        model_vgg16.reset_states() \n        \n        model_vgg16_history = model_vgg16.fit(\n            train_it, \n            steps_per_epoch=len(train_it),\n            validation_data=val_it,\n            validation_steps=len(val_it),\n            epochs=1, \n            verbose=1,\n            callbacks=[PlotLossesKeras()]\n        )\nelse:\n    print(\"WARNING: No GPU detected. Execution will proceed on the CPU, which will be significantly slower.\")\n    # Fallback to standard execution\n    model_vgg16_history = model_vgg16.fit(\n        train_it, \n        steps_per_epoch=len(train_it),\n        validation_data=val_it,\n        validation_steps=len(val_it),\n        epochs=1, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:35:47.012926Z","iopub.execute_input":"2026-09-16T15:35:47.013566Z","iopub.status.idle":"2026-09-16T15:39:17.093348Z","shell.execute_reply.started":"2026-09-16T15:35:47.013543Z","shell.execute_reply":"2026-09-16T15:39:17.092194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:39:17.094794Z","iopub.execute_input":"2026-09-16T15:39:17.095408Z","iopub.status.idle":"2026-09-16T15:39:17.474747Z","shell.execute_reply.started":"2026-09-16T15:39:17.095371Z","shell.execute_reply":"2026-09-16T15:39:17.473832Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_vgg16.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:39:17.475788Z","iopub.execute_input":"2026-09-16T15:39:17.476363Z","iopub.status.idle":"2026-09-16T15:39:36.197033Z","shell.execute_reply.started":"2026-09-16T15:39:17.476339Z","shell.execute_reply":"2026-09-16T15:39:36.196005Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model for the test set\n_, test_acc = model_vgg16.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (test_acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:39:36.198339Z","iopub.execute_input":"2026-09-16T15:39:36.198714Z","iopub.status.idle":"2026-09-16T15:40:46.957696Z","shell.execute_reply.started":"2026-09-16T15:39:36.198680Z","shell.execute_reply":"2026-09-16T15:40:46.956586Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. Reset the generator state to ensure alignment from index 0\ntest_it.reset()\n\n# 2. Extract the ordered ground truth labels from the generator\ny_true = test_it.classes\nprint(y_true.shape)\n\n# 3. Execute the forward pass over the entire test dataset\n# Calculate exact steps to prevent infinite looping or partial evaluation\nsteps = np.ceil(test_it.samples / test_it.batch_size)\nprobabilities = model_vgg16.predict(test_it, steps=steps, verbose=1).squeeze()\nprint(probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:40:46.959090Z","iopub.execute_input":"2026-09-16T15:40:46.959470Z","iopub.status.idle":"2026-09-16T15:41:18.585847Z","shell.execute_reply.started":"2026-09-16T15:40:46.959444Z","shell.execute_reply":"2026-09-16T15:41:18.584722Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:41:18.594917Z","iopub.execute_input":"2026-09-16T15:41:18.595522Z","iopub.status.idle":"2026-09-16T15:41:18.601747Z","shell.execute_reply.started":"2026-09-16T15:41:18.595496Z","shell.execute_reply":"2026-09-16T15:41:18.600737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:41:18.602891Z","iopub.execute_input":"2026-09-16T15:41:18.603177Z","iopub.status.idle":"2026-09-16T15:41:18.615727Z","shell.execute_reply.started":"2026-09-16T15:41:18.603153Z","shell.execute_reply":"2026-09-16T15:41:18.614567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 4. Discretize continuous logistic probabilities into binary class predictions\ny_pred = (probabilities > 0.5).astype(int)\nprint(y_pred.shape)\n\n# 5. Extract dynamic class labels mapping (e.g., {'cats': 0, 'dogs': 1})\n# This ensures the report correctly maps index 0 and 1 to your string labels\ntarget_names = list(test_it.class_indices.keys())\n\n# 6. Compute and output the classification report\nreport = classification_report(y_true, y_pred, target_names=target_names)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:41:18.617085Z","iopub.execute_input":"2026-09-16T15:41:18.618033Z","iopub.status.idle":"2026-09-16T15:41:18.639739Z","shell.execute_reply.started":"2026-09-16T15:41:18.618000Z","shell.execute_reply":"2026-09-16T15:41:18.639064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:41:18.640690Z","iopub.execute_input":"2026-09-16T15:41:18.641228Z","iopub.status.idle":"2026-09-16T15:41:18.647200Z","shell.execute_reply.started":"2026-09-16T15:41:18.641206Z","shell.execute_reply":"2026-09-16T15:41:18.646008Z"}},"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-09-16T15:41:18.648465Z","iopub.execute_input":"2026-09-16T15:41:18.649006Z","iopub.status.idle":"2026-09-16T15:41:26.112872Z","shell.execute_reply.started":"2026-09-16T15:41:18.648974Z","shell.execute_reply":"2026-09-16T15:41:26.112066Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:41:26.114262Z","iopub.execute_input":"2026-09-16T15:41:26.115040Z","iopub.status.idle":"2026-09-16T15:41:34.538572Z","shell.execute_reply.started":"2026-09-16T15:41:26.115002Z","shell.execute_reply":"2026-09-16T15:41:34.537429Z"}},"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-16T15:41:34.539761Z","iopub.execute_input":"2026-09-16T15:41:34.540186Z","iopub.status.idle":"2026-09-16T15:41:35.044849Z","shell.execute_reply.started":"2026-09-16T15:41:34.540160Z","shell.execute_reply":"2026-09-16T15:41:35.043517Z"}},"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-16T15:44:47.971775Z","iopub.execute_input":"2026-09-16T15:44:47.972137Z","iopub.status.idle":"2026-09-16T15:44:47.979652Z","shell.execute_reply.started":"2026-09-16T15:44:47.972111Z","shell.execute_reply":"2026-09-16T15:44:47.978311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-09-16T15:44:54.653536Z","iopub.execute_input":"2026-09-16T15:44:54.653912Z","iopub.status.idle":"2026-09-16T15:44:58.084637Z","shell.execute_reply.started":"2026-09-16T15:44:54.653884Z","shell.execute_reply":"2026-09-16T15:44:58.083676Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-09-16T15:45:02.342226Z","iopub.execute_input":"2026-09-16T15:45:02.342568Z","iopub.status.idle":"2026-09-16T15:45:02.350164Z","shell.execute_reply.started":"2026-09-16T15:45:02.342543Z","shell.execute_reply":"2026-09-16T15:45:02.349054Z"}},"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-16T15:45:05.609200Z","iopub.execute_input":"2026-09-16T15:45:05.610007Z","iopub.status.idle":"2026-09-16T15:45:05.616397Z","shell.execute_reply.started":"2026-09-16T15:45:05.609975Z","shell.execute_reply":"2026-09-16T15:45:05.615148Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_dir = './train'\nif not os.path.exists(train_dir):\n    train_dir = '/kaggle/working/train'\n\nfilenames = os.listdir(train_dir)\ncategories = []\nfilepaths = []\n\nfor filename in filenames:\n    if filename.endswith('.jpg'):\n        category = filename.split('.')[0]\n        categories.append(category)\n        filepaths.append(os.path.join(train_dir, filename))\n\ndf = pd.DataFrame({\n    'filename': filepaths,\n    'category': categories\n})\n\n# แบ่ง Train 80% และ Validation 20%\ntrain_df, val_df = train_test_split(df, test_size=0.2, random_state=42, stratify=df['category'])\n\nprint(f\"จำนวนรูปชุด Train: {len(train_df)} รูป\")\nprint(f\"จำนวนรูปชุด Validation: {len(val_df)} รูป\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:47:32.134896Z","iopub.execute_input":"2026-09-16T15:47:32.136125Z","iopub.status.idle":"2026-09-16T15:47:32.244792Z","shell.execute_reply.started":"2026-09-16T15:47:32.136088Z","shell.execute_reply":"2026-09-16T15:47:32.244031Z"}},"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-16T15:48:01.133254Z","iopub.execute_input":"2026-09-16T15:48:01.133582Z","iopub.status.idle":"2026-09-16T15:48:01.141845Z","shell.execute_reply.started":"2026-09-16T15:48:01.133560Z","shell.execute_reply":"2026-09-16T15:48:01.140626Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_SIZE = (224, 224)\nBATCH_SIZE = 32\n\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=15,\n    horizontal_flip=True,\n    zoom_range=0.1\n)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_gen = train_datagen.flow_from_dataframe(\n    train_df,\n    x_col='filename',\n    y_col='category',\n    target_size=IMG_SIZE,\n    class_mode='categorical',\n    batch_size=BATCH_SIZE,\n    shuffle=True\n)\n\nval_gen = val_datagen.flow_from_dataframe(\n    val_df,\n    x_col='filename',\n    y_col='category',\n    target_size=IMG_SIZE,\n    class_mode='categorical',\n    batch_size=BATCH_SIZE,\n    shuffle=False\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:48:05.320245Z","iopub.execute_input":"2026-09-16T15:48:05.321001Z","iopub.status.idle":"2026-09-16T15:48:05.527132Z","shell.execute_reply.started":"2026-09-16T15:48:05.320967Z","shell.execute_reply":"2026-09-16T15:48:05.526281Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- Model 1: MobileNetV2 ---\nbase_m1 = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_m1.trainable = False\n\nx1 = base_m1.output\nx1 = GlobalAveragePooling2D()(x1)\nx1 = Dropout(0.2)(x1)\nout1 = Dense(2, activation='softmax')(x1)\n\nmodel1 = Model(inputs=base_m1.input, outputs=out1)\nmodel1.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train 3 epochs\nhistory1 = model1.fit(train_gen, epochs=3, validation_data=val_gen)\n\n# Eval Model 1\nval_gen.reset()\npred1 = model1.predict(val_gen)\ny_pred1 = np.argmax(pred1, axis=1)\n\nprint(\"=== Classification Report: MobileNetV2 ===\")\nprint(classification_report(val_gen.classes, y_pred1, target_names=['cat', 'dog'], digits=4))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T15:48:12.139778Z","iopub.execute_input":"2026-09-16T15:48:12.140626Z","iopub.status.idle":"2026-09-16T15:59:51.810068Z","shell.execute_reply.started":"2026-09-16T15:48:12.140592Z","shell.execute_reply":"2026-09-16T15:59:51.809093Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = next(test_it)\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:04:54.250690Z","iopub.execute_input":"2026-09-16T16:04:54.251543Z","iopub.status.idle":"2026-09-16T16:04:54.490284Z","shell.execute_reply.started":"2026-09-16T16:04:54.251499Z","shell.execute_reply":"2026-09-16T16:04:54.489387Z"}},"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-16T16:04:59.458564Z","iopub.execute_input":"2026-09-16T16:04:59.459474Z","iopub.status.idle":"2026-09-16T16:04:59.465011Z","shell.execute_reply.started":"2026-09-16T16:04:59.459440Z","shell.execute_reply":"2026-09-16T16:04:59.463933Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"markdown","source":"# Pre-trained1","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom sklearn.metrics import classification_report\n\nimport tensorflow as tf\nfrom tensorflow.keras.applications import InceptionV3, ResNet50V2, MobileNetV2\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:18:13.663992Z","iopub.execute_input":"2026-09-16T16:18:13.664890Z","iopub.status.idle":"2026-09-16T16:18:13.669938Z","shell.execute_reply.started":"2026-09-16T16:18:13.664790Z","shell.execute_reply":"2026-09-16T16:18:13.669057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Model 1: InceptionV3\nbase_inc = InceptionV3(weights='imagenet', include_top=False, input_shape=train_it.image_shape)\nbase_inc.trainable = False\n\nx1 = base_inc.output\nx1 = GlobalAveragePooling2D()(x1)\nx1 = Dropout(0.2)(x1)\nout1 = Dense(2, activation='softmax')(x1)\n\nmodel_inc = Model(inputs=base_inc.input, outputs=out1)\nmodel_inc.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train 3 epochs\nhistory_inc = model_inc.fit(train_it, epochs=3, validation_data=val_it)\n\n# Classification Report\nval_it.reset()\npred_inc = model_inc.predict(val_it)\ny_pred_inc = np.argmax(pred_inc, axis=1)\n\nprint(\"\\n=== Classification Report: InceptionV3 ===\")\nprint(classification_report(val_it.classes, y_pred_inc, target_names=['cat', 'dog'], digits=4))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:24:18.853082Z","iopub.execute_input":"2026-09-16T16:24:18.853576Z","iopub.status.idle":"2026-09-16T16:29:01.081603Z","shell.execute_reply.started":"2026-09-16T16:24:18.853545Z","shell.execute_reply":"2026-09-16T16:29:01.080615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_history(history, title):\n    plt.figure(figsize=(12, 4))\n    \n    # กราฟ Accuracy\n    plt.subplot(1, 2, 1)\n    plt.plot(history.history['accuracy'], label='Train Acc')\n    plt.plot(history.history['val_accuracy'], label='Val Acc')\n    plt.title(f'{title} - Accuracy')\n    plt.xlabel('Epoch')\n    plt.legend()\n    \n    # กราฟ Loss\n    plt.subplot(1, 2, 2)\n    plt.plot(history.history['loss'], label='Train Loss')\n    plt.plot(history.history['val_loss'], label='Val Loss')\n    plt.title(f'{title} - Loss')\n    plt.xlabel('Epoch')\n    plt.legend()\n    plt.show()\n\n# พล็อตกราฟของ InceptionV3\nplot_history(history_inc, \"InceptionV3\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:33:07.933470Z","iopub.execute_input":"2026-09-16T16:33:07.934445Z","iopub.status.idle":"2026-09-16T16:33:08.412034Z","shell.execute_reply.started":"2026-09-16T16:33:07.934412Z","shell.execute_reply":"2026-09-16T16:33:08.410787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Model 2: ResNet50V2\nbase_res = ResNet50V2(weights='imagenet', include_top=False, input_shape=train_it.image_shape)\nbase_res.trainable = False\n\nx2 = base_res.output\nx2 = GlobalAveragePooling2D()(x2)\nx2 = Dropout(0.2)(x2)\nout2 = Dense(2, activation='softmax')(x2)\n\nmodel_res = Model(inputs=base_res.input, outputs=out2)\nmodel_res.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train 3 epochs\nhistory_res = model_res.fit(train_it, epochs=3, validation_data=val_it)\n\n# Report & Graph\nval_it.reset()\npred_res = model_res.predict(val_it)\ny_pred_res = np.argmax(pred_res, axis=1)\n\nprint(\"\\n=== Classification Report: ResNet50V2 ===\")\nprint(classification_report(val_it.classes, y_pred_res, target_names=['cat', 'dog'], digits=4))\n\nplot_history(history_res, \"ResNet50V2\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:33:22.460684Z","iopub.execute_input":"2026-09-16T16:33:22.461040Z","iopub.status.idle":"2026-09-16T16:37:56.097235Z","shell.execute_reply.started":"2026-09-16T16:33:22.461013Z","shell.execute_reply":"2026-09-16T16:37:56.096243Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Pre-trained2","metadata":{}},{"cell_type":"code","source":"# Model 3: MobileNetV2\nbase_mob = MobileNetV2(weights='imagenet', include_top=False, input_shape=train_it.image_shape)\nbase_mob.trainable = False\n\nx3 = base_mob.output\nx3 = GlobalAveragePooling2D()(x3)\nx3 = Dropout(0.2)(x3)\nout3 = Dense(2, activation='softmax')(x3)\n\nmodel_mob = Model(inputs=base_mob.input, outputs=out3)\nmodel_mob.compile(optimizer=Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train 3 epochs\nhistory_mob = model_mob.fit(train_it, epochs=3, validation_data=val_it)\n\n# Report & Graph\nval_it.reset()\npred_mob = model_mob.predict(val_it)\ny_pred_mob = np.argmax(pred_mob, axis=1)\n\nprint(\"\\n=== Classification Report: MobileNetV2 ===\")\nprint(classification_report(val_it.classes, y_pred_mob, target_names=['cat', 'dog'], digits=4))\n\nplot_history(history_mob, \"MobileNetV2\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:38:35.116921Z","iopub.execute_input":"2026-09-16T16:38:35.117672Z","iopub.status.idle":"2026-09-16T16:42:33.517953Z","shell.execute_reply.started":"2026-09-16T16:38:35.117642Z","shell.execute_reply":"2026-09-16T16:42:33.516885Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Pre-trained3","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport re\n\ntest_it.reset()\n\ntest_preds = model_inc.predict(test_it, verbose=1)\n\nfilenames = test_it.filenames\nids = []\nfor f in filenames:\n    clean_name = f.split('/')[-1]\n    nums = re.findall(r'\\d+', clean_name)\n    if nums:\n        ids.append(int(nums[-1]))\n    else:\n        ids.append(clean_name.split('.')[0])\n\ndog_class_idx = train_it.class_indices['dog'] if 'dog' in train_it.class_indices else 1\ndog_probs = test_preds[:, dog_class_idx]\n\nsubmission = pd.DataFrame({\n    'id': ids,\n    'label': dog_probs\n}).sort_values(by='id').reset_index(drop=True)\n\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Done!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-16T16:55:40.518254Z","iopub.execute_input":"2026-09-16T16:55:40.518834Z","iopub.status.idle":"2026-09-16T16:56:10.137576Z","shell.execute_reply.started":"2026-09-16T16:55:40.518763Z","shell.execute_reply":"2026-09-16T16:56:10.136448Z"}},"outputs":[],"execution_count":null}]}