{"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":[{"sourceType":"competition","sourceId":3362},{"sourceType":"datasetVersion","sourceId":4957779}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-03T17:25:00.795046Z","iopub.execute_input":"2026-10-03T17:25:00.795459Z","iopub.status.idle":"2026-10-03T17:25:00.800831Z","shell.execute_reply.started":"2026-10-03T17:25:00.795433Z","shell.execute_reply":"2026-10-03T17:25:00.799804Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:00.8027Z","iopub.execute_input":"2026-10-03T17:25:00.803638Z","iopub.status.idle":"2026-10-03T17:25:01.834501Z","shell.execute_reply.started":"2026-10-03T17:25:00.803603Z","shell.execute_reply":"2026-10-03T17:25:01.833352Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:01.83614Z","iopub.execute_input":"2026-10-03T17:25:01.836527Z","iopub.status.idle":"2026-10-03T17:25:02.822472Z","shell.execute_reply.started":"2026-10-03T17:25:01.836492Z","shell.execute_reply":"2026-10-03T17:25:02.821562Z"}},"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-03T17:25:02.824727Z","iopub.execute_input":"2026-10-03T17:25:02.825024Z","iopub.status.idle":"2026-10-03T17:25:13.035872Z","shell.execute_reply.started":"2026-10-03T17:25:02.825Z","shell.execute_reply":"2026-10-03T17:25:13.034501Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:13.038964Z","iopub.execute_input":"2026-10-03T17:25:13.03931Z","iopub.status.idle":"2026-10-03T17:25:14.156513Z","shell.execute_reply.started":"2026-10-03T17:25:13.039282Z","shell.execute_reply":"2026-10-03T17:25:14.155432Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:14.158305Z","iopub.execute_input":"2026-10-03T17:25:14.158682Z","iopub.status.idle":"2026-10-03T17:25:15.135436Z","shell.execute_reply.started":"2026-10-03T17:25:14.158648Z","shell.execute_reply":"2026-10-03T17:25:15.134523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:15.136734Z","iopub.execute_input":"2026-10-03T17:25:15.137046Z","iopub.status.idle":"2026-10-03T17:25:16.150819Z","shell.execute_reply.started":"2026-10-03T17:25:15.13702Z","shell.execute_reply":"2026-10-03T17:25:16.149922Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:16.152287Z","iopub.execute_input":"2026-10-03T17:25:16.15255Z","iopub.status.idle":"2026-10-03T17:25:17.20965Z","shell.execute_reply.started":"2026-10-03T17:25:16.152528Z","shell.execute_reply":"2026-10-03T17:25:17.208783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:17.211191Z","iopub.execute_input":"2026-10-03T17:25:17.211558Z","iopub.status.idle":"2026-10-03T17:25:17.216207Z","shell.execute_reply.started":"2026-10-03T17:25:17.211523Z","shell.execute_reply":"2026-10-03T17:25:17.215321Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:17.220203Z","iopub.execute_input":"2026-10-03T17:25:17.220555Z","iopub.status.idle":"2026-10-03T17:25:18.274063Z","shell.execute_reply.started":"2026-10-03T17:25:17.220532Z","shell.execute_reply":"2026-10-03T17:25:18.273165Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:18.275366Z","iopub.execute_input":"2026-10-03T17:25:18.275651Z","iopub.status.idle":"2026-10-03T17:25:19.285281Z","shell.execute_reply.started":"2026-10-03T17:25:18.275627Z","shell.execute_reply":"2026-10-03T17:25:19.284166Z"}},"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-03T17:25:19.286855Z","iopub.execute_input":"2026-10-03T17:25:19.287239Z","iopub.status.idle":"2026-10-03T17:25:20.217223Z","shell.execute_reply.started":"2026-10-03T17:25:19.287204Z","shell.execute_reply":"2026-10-03T17:25:20.216239Z"},"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-03T17:25:20.218542Z","iopub.execute_input":"2026-10-03T17:25:20.21902Z","iopub.status.idle":"2026-10-03T17:25:21.153Z","shell.execute_reply.started":"2026-10-03T17:25:20.218988Z","shell.execute_reply":"2026-10-03T17:25:21.152122Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:21.154525Z","iopub.execute_input":"2026-10-03T17:25:21.154897Z","iopub.status.idle":"2026-10-03T17:25:22.134468Z","shell.execute_reply.started":"2026-10-03T17:25:21.154863Z","shell.execute_reply":"2026-10-03T17:25:22.133073Z"}},"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-03T17:25:22.135951Z","iopub.execute_input":"2026-10-03T17:25:22.136563Z","iopub.status.idle":"2026-10-03T17:25:22.141813Z","shell.execute_reply.started":"2026-10-03T17:25:22.136536Z","shell.execute_reply":"2026-10-03T17:25:22.141029Z"}},"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-03T17:25:22.142964Z","iopub.execute_input":"2026-10-03T17:25:22.143352Z","iopub.status.idle":"2026-10-03T17:25:22.15658Z","shell.execute_reply.started":"2026-10-03T17:25:22.143318Z","shell.execute_reply":"2026-10-03T17:25:22.155808Z"},"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-03T17:25:22.15862Z","iopub.execute_input":"2026-10-03T17:25:22.159269Z","iopub.status.idle":"2026-10-03T17:25:22.167655Z","shell.execute_reply.started":"2026-10-03T17:25:22.159232Z","shell.execute_reply":"2026-10-03T17:25:22.16685Z"},"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-03T17:25:22.168793Z","iopub.execute_input":"2026-10-03T17:25:22.169667Z","iopub.status.idle":"2026-10-03T17:25:22.180195Z","shell.execute_reply.started":"2026-10-03T17:25:22.169635Z","shell.execute_reply":"2026-10-03T17:25:22.179371Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:22.18134Z","iopub.execute_input":"2026-10-03T17:25:22.18165Z","iopub.status.idle":"2026-10-03T17:25:23.168994Z","shell.execute_reply.started":"2026-10-03T17:25:22.181629Z","shell.execute_reply":"2026-10-03T17:25:23.167698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:23.170568Z","iopub.execute_input":"2026-10-03T17:25:23.170888Z","iopub.status.idle":"2026-10-03T17:25:24.146738Z","shell.execute_reply.started":"2026-10-03T17:25:23.170861Z","shell.execute_reply":"2026-10-03T17:25:24.145842Z"}},"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-03T17:25:24.148304Z","iopub.execute_input":"2026-10-03T17:25:24.148658Z","iopub.status.idle":"2026-10-03T17:25:25.126051Z","shell.execute_reply.started":"2026-10-03T17:25:24.148626Z","shell.execute_reply":"2026-10-03T17:25:25.125138Z"}},"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-03T17:25:25.127591Z","iopub.execute_input":"2026-10-03T17:25:25.127965Z","iopub.status.idle":"2026-10-03T17:25:27.021001Z","shell.execute_reply.started":"2026-10-03T17:25:25.127933Z","shell.execute_reply":"2026-10-03T17:25:27.020178Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:27.022259Z","iopub.execute_input":"2026-10-03T17:25:27.022589Z","iopub.status.idle":"2026-10-03T17:25:27.027395Z","shell.execute_reply.started":"2026-10-03T17:25:27.022559Z","shell.execute_reply":"2026-10-03T17:25:27.026534Z"}},"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-03T17:25:27.028467Z","iopub.execute_input":"2026-10-03T17:25:27.028739Z","iopub.status.idle":"2026-10-03T17:25:29.126834Z","shell.execute_reply.started":"2026-10-03T17:25:27.028717Z","shell.execute_reply":"2026-10-03T17:25:29.125904Z"},"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-03T17:25:29.128189Z","iopub.execute_input":"2026-10-03T17:25:29.128602Z","iopub.status.idle":"2026-10-03T17:25:31.153937Z","shell.execute_reply.started":"2026-10-03T17:25:29.128576Z","shell.execute_reply":"2026-10-03T17:25:31.152941Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-10-03T17:25:31.155521Z","iopub.execute_input":"2026-10-03T17:25:31.155875Z","iopub.status.idle":"2026-10-03T17:25:43.443182Z","shell.execute_reply.started":"2026-10-03T17:25:31.155841Z","shell.execute_reply":"2026-10-03T17:25:43.442052Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-10-03T17:25:43.444576Z","iopub.execute_input":"2026-10-03T17:25:43.4449Z","iopub.status.idle":"2026-10-03T17:25:43.460453Z","shell.execute_reply.started":"2026-10-03T17:25:43.444874Z","shell.execute_reply":"2026-10-03T17:25:43.459545Z"},"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-03T17:25:43.469501Z","iopub.execute_input":"2026-10-03T17:25:43.470255Z","iopub.status.idle":"2026-10-03T17:25:43.473551Z","shell.execute_reply.started":"2026-10-03T17:25:43.470231Z","shell.execute_reply":"2026-10-03T17:25:43.472611Z"}},"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-03T17:25:43.474608Z","iopub.execute_input":"2026-10-03T17:25:43.474938Z","iopub.status.idle":"2026-10-03T17:25:43.487787Z","shell.execute_reply.started":"2026-10-03T17:25:43.474917Z","shell.execute_reply":"2026-10-03T17:25:43.487143Z"}},"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-03T17:25:43.489085Z","iopub.execute_input":"2026-10-03T17:25:43.489524Z","iopub.status.idle":"2026-10-03T17:25:43.49633Z","shell.execute_reply.started":"2026-10-03T17:25:43.489502Z","shell.execute_reply":"2026-10-03T17:25:43.495473Z"}},"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-03T17:25:43.497523Z","iopub.execute_input":"2026-10-03T17:25:43.498429Z","iopub.status.idle":"2026-10-03T17:25:45.499946Z","shell.execute_reply.started":"2026-10-03T17:25:43.498405Z","shell.execute_reply":"2026-10-03T17:25:45.499028Z"}},"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-03T17:25:45.501453Z","iopub.execute_input":"2026-10-03T17:25:45.501886Z","iopub.status.idle":"2026-10-03T17:25:45.508592Z","shell.execute_reply.started":"2026-10-03T17:25:45.501845Z","shell.execute_reply":"2026-10-03T17:25:45.507496Z"}},"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-03T17:25:45.509719Z","iopub.execute_input":"2026-10-03T17:25:45.51024Z","iopub.status.idle":"2026-10-03T17:25:45.586443Z","shell.execute_reply.started":"2026-10-03T17:25:45.510215Z","shell.execute_reply":"2026-10-03T17:25:45.585525Z"}},"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-03T17:25:45.587611Z","iopub.execute_input":"2026-10-03T17:25:45.58824Z","iopub.status.idle":"2026-10-03T17:25:45.667268Z","shell.execute_reply.started":"2026-10-03T17:25:45.588215Z","shell.execute_reply":"2026-10-03T17:25:45.666402Z"}},"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-03T17:25:45.668929Z","iopub.execute_input":"2026-10-03T17:25:45.669319Z","iopub.status.idle":"2026-10-03T17:25:45.759808Z","shell.execute_reply.started":"2026-10-03T17:25:45.669283Z","shell.execute_reply":"2026-10-03T17:25:45.758996Z"}},"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-03T17:25:45.761056Z","iopub.execute_input":"2026-10-03T17:25:45.76162Z","iopub.status.idle":"2026-10-03T17:25:45.768086Z","shell.execute_reply.started":"2026-10-03T17:25:45.761585Z","shell.execute_reply":"2026-10-03T17:25:45.767177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:25:45.769255Z","iopub.execute_input":"2026-10-03T17:25:45.769509Z","iopub.status.idle":"2026-10-03T17:25:46.780969Z","shell.execute_reply.started":"2026-10-03T17:25:45.769488Z","shell.execute_reply":"2026-10-03T17:25:46.779701Z"}},"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-03T17:25:46.782978Z","iopub.execute_input":"2026-10-03T17:25:46.78331Z","iopub.status.idle":"2026-10-03T17:25:46.787373Z","shell.execute_reply.started":"2026-10-03T17:25:46.783282Z","shell.execute_reply":"2026-10-03T17:25:46.786454Z"}},"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-10-03T17:25:46.788608Z","iopub.execute_input":"2026-10-03T17:25:46.789204Z","iopub.status.idle":"2026-10-03T17:26:23.044918Z","shell.execute_reply.started":"2026-10-03T17:25:46.789164Z","shell.execute_reply":"2026-10-03T17:26:23.044234Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =============================================================================\n# Dogs vs Cats — data pipeline with a switchable stratified 10% sample\n#\n# Paste each BLOCK into its own notebook cell, in order.\n# To switch corpora, edit exactly one line: DATA_MODE in BLOCK 0.\n# =============================================================================\n\n\n# =============================================================================\n# BLOCK 0 — CONFIG\n# =============================================================================\nimport os\nimport json\nimport math\nimport random\nimport shutil\nimport time\n\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nDATA_MODE       = 'sample'   # 'full' | 'sample'   <- the only line you edit\nSAMPLE_FRACTION = 0.15       # ignored when DATA_MODE == 'full'\nVAL_SPLIT       = 0.2\nSEED            = 42\n\nBATCH_SIZE = 32              # keep your existing values\nIMAGE_SIZE = 224\n\nFULL_TRAIN_PATH = ('/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset'\n                   '/dataset_dogs_vs_cats/train')\nSAMPLE_ROOT     = '/kaggle/working/sample_train'\nMANIFEST_NAME   = '.sample_manifest.json'\n\nassert DATA_MODE in ('full', 'sample'), f\"DATA_MODE must be 'full' or 'sample', got {DATA_MODE!r}\"\n\n# sorted() matches the alphabetical ordering flow_from_directory uses internally,\n# so passing this as `classes=` locks the mapping to {'cats': 0, 'dogs': 1}.\nCLASS_NAMES = sorted(d for d in os.listdir(FULL_TRAIN_PATH)\n                     if os.path.isdir(os.path.join(FULL_TRAIN_PATH, d)))\n\nprint(f'DATA_MODE      : {DATA_MODE}')\nprint(f'classes        : {CLASS_NAMES}')\nprint(f'seed           : {SEED}')\n\n\n# =============================================================================\n# BLOCK 1 — BUILD THE STRATIFIED SUBSET TREE   (runs only when DATA_MODE == 'sample')\n#\n# Per-class sampling IS the stratification: taking round(N_c * fraction) files from\n# each class directory preserves the original class proportions by construction.\n# The tree is made of symlinks, so it costs no disk and takes seconds. It must live\n# under /kaggle/working because /kaggle/input is read-only.\n# =============================================================================\nIMG_EXT = ('.jpg', '.jpeg', '.png', '.bmp', '.ppm', '.tif', '.tiff', '.gif')\n\n\ndef list_class_files(root, cls):\n    \"\"\"Sorted image filenames for one class, so the listing order is not FS-dependent.\"\"\"\n    d = os.path.join(root, cls)\n    return sorted(f for f in os.listdir(d) if f.lower().endswith(IMG_EXT))\n\n\ndef build_stratified_sample(src_root, dst_root, classes, fraction, seed):\n    manifest_path = os.path.join(dst_root, MANIFEST_NAME)\n    wanted = {'source': src_root, 'fraction': fraction, 'seed': seed, 'classes': list(classes)}\n\n    if os.path.isdir(dst_root):\n        # Safety guard: only ever delete a tree this function created.\n        if not os.path.exists(manifest_path):\n            raise RuntimeError(\n                f'{dst_root} exists but has no {MANIFEST_NAME}; refusing to delete it. '\n                'Point SAMPLE_ROOT somewhere else or remove that directory yourself.')\n        with open(manifest_path) as fh:\n            old = json.load(fh)\n        if all(old.get(k) == v for k, v in wanted.items()):\n            print(f'reusing existing sample at {dst_root}')\n            for cls, c in old['counts'].items():\n                print(f\"  {cls:<10} {c['sampled']:>6} / {c['available']:>6}\")\n            return dst_root\n        print(f'config changed -> rebuilding {dst_root}')\n        shutil.rmtree(dst_root)\n\n    rng = random.Random(seed)          # one stream, so the whole draw is reproducible\n    counts, symlinked = {}, True\n\n    for cls in classes:\n        files = list_class_files(src_root, cls)\n        n = max(1, round(len(files) * fraction))\n        picked = rng.sample(files, n)\n\n        outdir = os.path.join(dst_root, cls)\n        os.makedirs(outdir, exist_ok=True)\n        for fname in picked:\n            # abspath matters: a relative symlink target is resolved relative to the\n            # LINK's directory, not the cwd, which would silently produce dead links.\n            src = os.path.abspath(os.path.join(src_root, cls, fname))\n            dst = os.path.join(outdir, fname)\n            try:\n                os.symlink(src, dst)\n            except (OSError, NotImplementedError, AttributeError):\n                shutil.copy2(src, dst)  # filesystem without symlink support\n                symlinked = False\n\n        counts[cls] = {'sampled': n, 'available': len(files)}\n        print(f'  {cls:<10} {n:>6} / {len(files):>6}  ({n / len(files):.1%})')\n\n    manifest = dict(wanted,\n                    counts=counts,\n                    symlinked=symlinked,\n                    created=time.strftime('%Y-%m-%d %H:%M:%S'))\n    with open(manifest_path, 'w') as fh:\n        json.dump(manifest, fh, indent=2)\n\n    print(f'built {dst_root}  (symlinked={symlinked})')\n    return dst_root\n\n\nif DATA_MODE == 'sample':\n    build_stratified_sample(FULL_TRAIN_PATH, SAMPLE_ROOT,\n                            CLASS_NAMES, SAMPLE_FRACTION, SEED)\nelse:\n    print('DATA_MODE=full -> skipping sample build')\n\n\n# =============================================================================\n# BLOCK 2 — SELECT THE ACTIVE CORPUS\n# Everything downstream reads TRAIN_DIR and is identical between the two modes.\n# =============================================================================\nTRAIN_DIR = SAMPLE_ROOT if DATA_MODE == 'sample' else FULL_TRAIN_PATH\nprint(f'TRAIN_DIR = {TRAIN_DIR}')\n\n\n# =============================================================================\n# BLOCK 3 — TWO GENERATORS\n#\n# Augmentation on train only. The original code shared one generator, so validation\n# images were randomly flipped every epoch: val metrics wobbled for no modelling\n# reason and the confusion matrix was computed on augmented inputs.\n#\n# Both generators MUST carry the same validation_split. flow_from_directory\n# partitions by slicing the sorted filename list *within each class directory*, so\n# the 80/20 split is itself stratified, is deterministic, and is unaffected by\n# `seed` — two separate instances therefore yield identical, non-overlapping\n# partitions. BLOCK 5 asserts this rather than trusting it.\n# =============================================================================\ntrain_datagen = ImageDataGenerator(\n    rescale=1.0 / 255.0,\n    horizontal_flip=True,\n    validation_split=VAL_SPLIT,\n)\n\nval_datagen = ImageDataGenerator(\n    rescale=1.0 / 255.0,          # no augmentation\n    validation_split=VAL_SPLIT,\n)\n\n\n# =============================================================================\n# BLOCK 4 — THE TWO ITERATORS\n# =============================================================================\ntrain_it = train_datagen.flow_from_directory(\n    TRAIN_DIR,\n    classes=CLASS_NAMES,          # lock the label mapping explicitly\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='training',\n    shuffle=True,\n    seed=SEED,\n)\n\nval_it = val_datagen.flow_from_directory(\n    TRAIN_DIR,\n    classes=CLASS_NAMES,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='validation',\n    shuffle=False,                # keep index alignment for the confusion matrix\n)\n\n\n# =============================================================================\n# BLOCK 5 — VERIFICATION (print + assert)\n# =============================================================================\ndef class_counts(it):\n    n = np.bincount(it.classes, minlength=len(CLASS_NAMES))\n    return {cls: int(c) for cls, c in zip(CLASS_NAMES, n)}\n\n\nfull_total   = sum(len(list_class_files(FULL_TRAIN_PATH, c)) for c in CLASS_NAMES)\nactive_total = sum(len(list_class_files(TRAIN_DIR, c)) for c in CLASS_NAMES)\n\nprint(f'class_indices  : {train_it.class_indices}')\nprint(f'full train set : {full_total}')\nprint(f'active corpus  : {active_total}  ({active_total / full_total:.1%} of full)')\nprint(f'train          : {train_it.samples:>6}  {class_counts(train_it)}')\nprint(f'val            : {val_it.samples:>6}  {class_counts(val_it)}')\n\nassert train_it.class_indices == {c: i for i, c in enumerate(CLASS_NAMES)}\nassert val_it.class_indices == train_it.class_indices\nassert not (set(train_it.filenames) & set(val_it.filenames)), 'train/val leakage'\nassert train_it.samples + val_it.samples == active_total, 'iterators lost files'\n\n# class balance must survive the sampling\nfor cls, c in class_counts(train_it).items():\n    share = c / train_it.samples\n    assert abs(share - 1 / len(CLASS_NAMES)) < 0.05, f'{cls} is imbalanced in train: {share:.1%}'\n\nprint('all checks passed')\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:23.046436Z","iopub.execute_input":"2026-10-03T17:26:23.046767Z","iopub.status.idle":"2026-10-03T17:26:24.166322Z","shell.execute_reply.started":"2026-10-03T17:26:23.046736Z","shell.execute_reply":"2026-10-03T17:26:24.165375Z"}},"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-03T17:26:24.167748Z","iopub.execute_input":"2026-10-03T17:26:24.16844Z","iopub.status.idle":"2026-10-03T17:26:24.174798Z","shell.execute_reply.started":"2026-10-03T17:26:24.168405Z","shell.execute_reply":"2026-10-03T17:26:24.173938Z"}},"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-03T17:26:24.175968Z","iopub.execute_input":"2026-10-03T17:26:24.176285Z","iopub.status.idle":"2026-10-03T17:26:24.189184Z","shell.execute_reply.started":"2026-10-03T17:26:24.176257Z","shell.execute_reply":"2026-10-03T17:26:24.188309Z"}},"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-03T17:26:24.190408Z","iopub.execute_input":"2026-10-03T17:26:24.190706Z","iopub.status.idle":"2026-10-03T17:26:24.200163Z","shell.execute_reply.started":"2026-10-03T17:26:24.190678Z","shell.execute_reply":"2026-10-03T17:26:24.199166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:24.201275Z","iopub.execute_input":"2026-10-03T17:26:24.201793Z","iopub.status.idle":"2026-10-03T17:26:24.214683Z","shell.execute_reply.started":"2026-10-03T17:26:24.201771Z","shell.execute_reply":"2026-10-03T17:26:24.214007Z"}},"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-03T17:26:24.215864Z","iopub.execute_input":"2026-10-03T17:26:24.216563Z","iopub.status.idle":"2026-10-03T17:26:24.227772Z","shell.execute_reply.started":"2026-10-03T17:26:24.21653Z","shell.execute_reply":"2026-10-03T17:26:24.226851Z"}},"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-03T17:26:24.228907Z","iopub.execute_input":"2026-10-03T17:26:24.229443Z","iopub.status.idle":"2026-10-03T17:26:25.234726Z","shell.execute_reply.started":"2026-10-03T17:26:24.22942Z","shell.execute_reply":"2026-10-03T17:26:25.233574Z"}},"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-03T17:26:25.236253Z","iopub.execute_input":"2026-10-03T17:26:25.236559Z","iopub.status.idle":"2026-10-03T17:26:25.242232Z","shell.execute_reply.started":"2026-10-03T17:26:25.236535Z","shell.execute_reply":"2026-10-03T17:26:25.241411Z"}},"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-03T17:26:25.243313Z","iopub.execute_input":"2026-10-03T17:26:25.243747Z","iopub.status.idle":"2026-10-03T17:26:25.255153Z","shell.execute_reply.started":"2026-10-03T17:26:25.243723Z","shell.execute_reply":"2026-10-03T17:26:25.254144Z"}},"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-03T17:26:25.256085Z","iopub.execute_input":"2026-10-03T17:26:25.25694Z","iopub.status.idle":"2026-10-03T17:26:25.269634Z","shell.execute_reply.started":"2026-10-03T17:26:25.256909Z","shell.execute_reply":"2026-10-03T17:26:25.268929Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:25.270773Z","iopub.execute_input":"2026-10-03T17:26:25.271136Z","iopub.status.idle":"2026-10-03T17:26:25.28203Z","shell.execute_reply.started":"2026-10-03T17:26:25.27109Z","shell.execute_reply":"2026-10-03T17:26:25.281342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:25.283214Z","iopub.execute_input":"2026-10-03T17:26:25.283478Z","iopub.status.idle":"2026-10-03T17:26:25.294782Z","shell.execute_reply.started":"2026-10-03T17:26:25.283458Z","shell.execute_reply":"2026-10-03T17:26:25.294072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:25.295831Z","iopub.execute_input":"2026-10-03T17:26:25.296689Z","iopub.status.idle":"2026-10-03T17:26:25.302196Z","shell.execute_reply.started":"2026-10-03T17:26:25.296654Z","shell.execute_reply":"2026-10-03T17:26:25.301459Z"}},"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-03T17:26:25.303281Z","iopub.execute_input":"2026-10-03T17:26:25.303601Z","iopub.status.idle":"2026-10-03T17:26:25.314596Z","shell.execute_reply.started":"2026-10-03T17:26:25.30358Z","shell.execute_reply":"2026-10-03T17:26:25.313877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:25.31552Z","iopub.execute_input":"2026-10-03T17:26:25.316104Z","iopub.status.idle":"2026-10-03T17:26:25.329266Z","shell.execute_reply.started":"2026-10-03T17:26:25.316057Z","shell.execute_reply":"2026-10-03T17:26:25.328308Z"}},"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-03T17:26:25.330394Z","iopub.execute_input":"2026-10-03T17:26:25.33072Z","iopub.status.idle":"2026-10-03T17:26:31.605776Z","shell.execute_reply.started":"2026-10-03T17:26:25.330691Z","shell.execute_reply":"2026-10-03T17:26:31.605081Z"}},"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-03T17:26:31.606934Z","iopub.execute_input":"2026-10-03T17:26:31.60729Z","iopub.status.idle":"2026-10-03T17:26:31.614541Z","shell.execute_reply.started":"2026-10-03T17:26:31.607256Z","shell.execute_reply":"2026-10-03T17:26:31.61387Z"}},"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-03T17:26:31.615697Z","iopub.execute_input":"2026-10-03T17:26:31.616058Z","iopub.status.idle":"2026-10-03T17:26:36.987545Z","shell.execute_reply.started":"2026-10-03T17:26:31.615997Z","shell.execute_reply":"2026-10-03T17:26:36.986456Z"}},"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-03T17:26:36.988647Z","iopub.execute_input":"2026-10-03T17:26:36.989006Z","iopub.status.idle":"2026-10-03T17:26:42.588595Z","shell.execute_reply.started":"2026-10-03T17:26:36.988982Z","shell.execute_reply":"2026-10-03T17:26:42.587772Z"}},"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-03T17:26:42.589676Z","iopub.execute_input":"2026-10-03T17:26:42.590008Z","iopub.status.idle":"2026-10-03T17:26:42.595554Z","shell.execute_reply.started":"2026-10-03T17:26:42.589983Z","shell.execute_reply":"2026-10-03T17:26:42.59473Z"},"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-03T17:26:42.596817Z","iopub.execute_input":"2026-10-03T17:26:42.597154Z","iopub.status.idle":"2026-10-03T17:26:47.803595Z","shell.execute_reply.started":"2026-10-03T17:26:42.597122Z","shell.execute_reply":"2026-10-03T17:26:47.802779Z"}},"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-03T17:26:47.805007Z","iopub.execute_input":"2026-10-03T17:26:47.805455Z","iopub.status.idle":"2026-10-03T17:26:47.809674Z","shell.execute_reply.started":"2026-10-03T17:26:47.805429Z","shell.execute_reply":"2026-10-03T17:26:47.808686Z"}},"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-03T17:26:47.810821Z","iopub.execute_input":"2026-10-03T17:26:47.811352Z","iopub.status.idle":"2026-10-03T17:26:47.824062Z","shell.execute_reply.started":"2026-10-03T17:26:47.811313Z","shell.execute_reply":"2026-10-03T17:26:47.82334Z"}},"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-03T17:26:47.824924Z","iopub.execute_input":"2026-10-03T17:26:47.82517Z","iopub.status.idle":"2026-10-03T17:26:47.839611Z","shell.execute_reply.started":"2026-10-03T17:26:47.825135Z","shell.execute_reply":"2026-10-03T17:26:47.838667Z"}},"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-10-03T17:26:47.840648Z","iopub.execute_input":"2026-10-03T17:26:47.84132Z","iopub.status.idle":"2026-10-03T17:26:48.634364Z","shell.execute_reply.started":"2026-10-03T17:26:47.841279Z","shell.execute_reply":"2026-10-03T17:26:48.633649Z"}},"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-03T17:26:48.635441Z","iopub.execute_input":"2026-10-03T17:26:48.63568Z","iopub.status.idle":"2026-10-03T17:26:52.985581Z","shell.execute_reply.started":"2026-10-03T17:26:48.635659Z","shell.execute_reply":"2026-10-03T17:26:52.984636Z"}},"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-03T17:26:52.986661Z","iopub.execute_input":"2026-10-03T17:26:52.987283Z","iopub.status.idle":"2026-10-03T17:26:53.715261Z","shell.execute_reply.started":"2026-10-03T17:26:52.987258Z","shell.execute_reply":"2026-10-03T17:26:53.713463Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n\t\tprint(index, \n              layer.name,\n              layer.trainable,\n              layer.output.shape\n        )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.718815Z","iopub.execute_input":"2026-10-03T17:26:53.719453Z","iopub.status.idle":"2026-10-03T17:26:53.724605Z","shell.execute_reply.started":"2026-10-03T17:26:53.719426Z","shell.execute_reply":"2026-10-03T17:26:53.723583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n    if index <= 14:\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-10-03T17:26:53.725715Z","iopub.execute_input":"2026-10-03T17:26:53.726217Z","iopub.status.idle":"2026-10-03T17:26:53.738301Z","shell.execute_reply.started":"2026-10-03T17:26:53.726179Z","shell.execute_reply":"2026-10-03T17:26:53.737523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.739226Z","iopub.execute_input":"2026-10-03T17:26:53.739485Z","iopub.status.idle":"2026-10-03T17:26:53.752345Z","shell.execute_reply.started":"2026-10-03T17:26:53.739464Z","shell.execute_reply":"2026-10-03T17:26:53.751354Z"}},"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-03T17:26:53.753427Z","iopub.execute_input":"2026-10-03T17:26:53.753735Z","iopub.status.idle":"2026-10-03T17:26:53.770434Z","shell.execute_reply.started":"2026-10-03T17:26:53.753706Z","shell.execute_reply":"2026-10-03T17:26:53.769558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"layer1 = Dense(256, activation='relu', kernel_initializer='he_uniform')(flat1)\nprint(layer1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.771441Z","iopub.execute_input":"2026-10-03T17:26:53.771718Z","iopub.status.idle":"2026-10-03T17:26:53.796962Z","shell.execute_reply.started":"2026-10-03T17:26:53.771696Z","shell.execute_reply":"2026-10-03T17:26:53.795978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"layer2 = Dense(128, activation='relu', kernel_initializer='he_uniform')(layer1)\nprint(layer2.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.797926Z","iopub.execute_input":"2026-10-03T17:26:53.798207Z","iopub.status.idle":"2026-10-03T17:26:53.814209Z","shell.execute_reply.started":"2026-10-03T17:26:53.798174Z","shell.execute_reply":"2026-10-03T17:26:53.812978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output1 = Dense(2, activation='softmax')(layer2)\nprint(f\"{output1.shape=}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.815656Z","iopub.execute_input":"2026-10-03T17:26:53.815986Z","iopub.status.idle":"2026-10-03T17:26:53.833791Z","shell.execute_reply.started":"2026-10-03T17:26:53.815953Z","shell.execute_reply":"2026-10-03T17:26:53.832828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output2 = Dense(1, activation='sigmoid')(layer2)\nprint(output2.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:53.835013Z","iopub.execute_input":"2026-10-03T17:26:53.835341Z","iopub.status.idle":"2026-10-03T17:26:54.175607Z","shell.execute_reply.started":"2026-10-03T17:26:53.835319Z","shell.execute_reply":"2026-10-03T17:26:54.174659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model to be trained\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output2)\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-10-03T17:26:54.176911Z","iopub.execute_input":"2026-10-03T17:26:54.177285Z","iopub.status.idle":"2026-10-03T17:26:54.19226Z","shell.execute_reply.started":"2026-10-03T17:26:54.177244Z","shell.execute_reply":"2026-10-03T17:26:54.191293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_vgg16.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:54.193446Z","iopub.execute_input":"2026-10-03T17:26:54.193718Z","iopub.status.idle":"2026-10-03T17:26:54.198579Z","shell.execute_reply.started":"2026-10-03T17:26:54.193696Z","shell.execute_reply":"2026-10-03T17:26:54.19771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:54.199718Z","iopub.execute_input":"2026-10-03T17:26:54.200027Z","iopub.status.idle":"2026-10-03T17:26:54.24722Z","shell.execute_reply.started":"2026-10-03T17:26:54.200005Z","shell.execute_reply":"2026-10-03T17:26:54.245575Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:54.249181Z","iopub.execute_input":"2026-10-03T17:26:54.249387Z","iopub.status.idle":"2026-10-03T17:26:54.254846Z","shell.execute_reply.started":"2026-10-03T17:26:54.249368Z","shell.execute_reply":"2026-10-03T17:26:54.253933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# del ตัวแปร #ลบตัวแปรออกจากหน่วยความจำ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:54.256024Z","iopub.execute_input":"2026-10-03T17:26:54.25638Z","iopub.status.idle":"2026-10-03T17:26:54.265408Z","shell.execute_reply.started":"2026-10-03T17:26:54.256348Z","shell.execute_reply":"2026-10-03T17:26:54.264606Z"}},"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-03T17:26:54.266429Z","iopub.execute_input":"2026-10-03T17:26:54.26673Z","iopub.status.idle":"2026-10-03T17:26:54.280079Z","shell.execute_reply.started":"2026-10-03T17:26:54.266702Z","shell.execute_reply":"2026-10-03T17:26:54.279445Z"}},"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=2, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:26:54.281049Z","iopub.execute_input":"2026-10-03T17:26:54.281825Z","iopub.status.idle":"2026-10-03T17:32:10.319424Z","shell.execute_reply.started":"2026-10-03T17:26:54.281802Z","shell.execute_reply":"2026-10-03T17:32:10.318574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:32:10.327007Z","iopub.execute_input":"2026-10-03T17:32:10.327753Z","iopub.status.idle":"2026-10-03T17:32:10.642474Z","shell.execute_reply.started":"2026-10-03T17:32:10.327728Z","shell.execute_reply":"2026-10-03T17:32:10.641732Z"}},"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-03T17:32:10.643497Z","iopub.execute_input":"2026-10-03T17:32:10.643791Z","iopub.status.idle":"2026-10-03T17:32:13.269069Z","shell.execute_reply.started":"2026-10-03T17:32:10.64376Z","shell.execute_reply":"2026-10-03T17:32:13.268266Z"}},"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-03T17:32:13.270281Z","iopub.execute_input":"2026-10-03T17:32:13.270645Z","iopub.status.idle":"2026-10-03T17:32:57.810743Z","shell.execute_reply.started":"2026-10-03T17:32:13.27062Z","shell.execute_reply":"2026-10-03T17:32:57.809983Z"}},"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-03T17:32:57.811938Z","iopub.execute_input":"2026-10-03T17:32:57.81229Z","iopub.status.idle":"2026-10-03T17:33:25.587479Z","shell.execute_reply.started":"2026-10-03T17:32:57.812256Z","shell.execute_reply":"2026-10-03T17:33:25.586587Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:25.588618Z","iopub.execute_input":"2026-10-03T17:33:25.588986Z","iopub.status.idle":"2026-10-03T17:33:25.597914Z","shell.execute_reply.started":"2026-10-03T17:33:25.588953Z","shell.execute_reply":"2026-10-03T17:33:25.597043Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:25.599213Z","iopub.execute_input":"2026-10-03T17:33:25.600172Z","iopub.status.idle":"2026-10-03T17:33:25.612273Z","shell.execute_reply.started":"2026-10-03T17:33:25.600138Z","shell.execute_reply":"2026-10-03T17:33:25.611519Z"}},"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-10-03T17:33:25.613331Z","iopub.execute_input":"2026-10-03T17:33:25.613636Z","iopub.status.idle":"2026-10-03T17:33:25.640893Z","shell.execute_reply.started":"2026-10-03T17:33:25.613606Z","shell.execute_reply":"2026-10-03T17:33:25.640182Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:25.641739Z","iopub.execute_input":"2026-10-03T17:33:25.641993Z","iopub.status.idle":"2026-10-03T17:33:25.64775Z","shell.execute_reply.started":"2026-10-03T17:33:25.641971Z","shell.execute_reply":"2026-10-03T17:33:25.646923Z"}},"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 unique indices \nnp.random.seed(42)  # For reproducibility\n\n# คำนวณจำนวนรูปที่จะสุ่ม (เลือกค่าน้อยสุดระหว่าง 100 กับ จำนวนรูปจริงที่มี)\nnum_samples = min(100, len(all_images))\n\nrandom_indices = np.random.choice(len(all_images), size=num_samples, replace=False)\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\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-03T17:33:25.648865Z","iopub.execute_input":"2026-10-03T17:33:25.6497Z","iopub.status.idle":"2026-10-03T17:33:26.416278Z","shell.execute_reply.started":"2026-10-03T17:33:25.649667Z","shell.execute_reply":"2026-10-03T17:33:26.415376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# 1. ดึงข้อมูลจาก iterator ให้ได้ภาพอย่างน้อย 100 ภาพ (2 batches = 128 ภาพ)\nimages_list = []\nlabels_list = []\n\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\nall_images = np.concatenate(images_list, axis=0)\nall_labels = np.concatenate(labels_list, axis=0)\n\n# 2. สุ่มแบบคงที่ (Seed=42) เลือกมา 100 ภาพพอดี\nnp.random.seed(42)\nnum_samples = min(100, len(all_images))\nrandom_indices = np.random.choice(len(all_images), size=num_samples, replace=False)\n\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\n\n# 3. ทำนายผล 100 ภาพโดยใช้ model_vgg16\nprobabilities = model_vgg16.predict(sample_images, verbose=0).squeeze()\n\n# 4. วาดรูปแสดงผลทั้ง 100 ภาพ (10 แถว x 10 คอลัมน์)\ncols = 10\nrows = int(np.ceil(num_samples / cols))\n\nfig, axes = plt.subplots(rows, cols, figsize=(20, rows * 2.5))\naxes = axes.flatten()\n\nclass_names = {0: 'Cat', 1: 'Dog'}\n\nfor i in range(len(axes)):\n    if i < num_samples:\n        img = sample_images[i]\n        \n        # Rescale ค่า Pixel ให้อยู่ในช่วง [0, 1] สำหรับ plt.imshow()\n        if img.max() > 1.0 or img.min() < 0:\n            img = (img - img.min()) / (img.max() - img.min())\n            \n        axes[i].imshow(img)\n        \n        gt_label = class_names.get(int(sample_labels[i]), str(int(sample_labels[i])))\n        prob = probabilities[i]\n        pred_label = 'Dog' if prob >= 0.5 else 'Cat'\n        \n        axes[i].set_title(f\"GT: {gt_label}\\nPred: {pred_label}\\nProb: {prob:.2f}\", fontsize=9, pad=4)\n        axes[i].axis('off')\n    else:\n        axes[i].axis('off')\n\n# ปรับระยะห่างระหว่างรูป ไม่ให้ข้อความทับกัน\nplt.subplots_adjust(wspace=0.3, hspace=0.6)\n\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:26.417491Z","iopub.execute_input":"2026-10-03T17:33:26.418074Z","iopub.status.idle":"2026-10-03T17:33:30.974972Z","shell.execute_reply.started":"2026-10-03T17:33:26.418044Z","shell.execute_reply":"2026-10-03T17:33:30.973535Z"}},"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 tensorflow.keras.applications.resnet_v2 import preprocess_input\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',\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',\n    shuffle=False  # Disable shuffle to maintain index alignment for metrics\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:30.976316Z","iopub.execute_input":"2026-10-03T17:33:30.976606Z","iopub.status.idle":"2026-10-03T17:33:45.009366Z","shell.execute_reply.started":"2026-10-03T17:33:30.976581Z","shell.execute_reply":"2026-10-03T17:33:45.008606Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================ Block 2 (Fine-tuning Version) ================\nfrom keras.applications.resnet_v2 import ResNet50V2\nfrom keras.layers import Dense, GlobalAveragePooling2D, Flatten\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_resnet50v2_finetune():\n    # 1. Load Base Model\n    base_model = ResNet50V2(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    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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:45.01045Z","iopub.execute_input":"2026-10-03T17:33:45.011303Z","iopub.status.idle":"2026-10-03T17:33:45.017501Z","shell.execute_reply.started":"2026-10-03T17:33:45.011275Z","shell.execute_reply":"2026-10-03T17:33:45.016717Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_resnet50v2 = define_model_resnet50v2_finetune()\nprint(id(model_resnet50v2))\n# model_resnet50v2.summary()","metadata":{"execution":{"iopub.status.busy":"2026-10-03T17:33:45.01875Z","iopub.execute_input":"2026-10-03T17:33:45.019594Z","iopub.status.idle":"2026-10-03T17:33:47.153085Z","shell.execute_reply.started":"2026-10-03T17:33:45.019565Z","shell.execute_reply":"2026-10-03T17:33:47.152186Z"},"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_resnet50v2.trainable_weights]))\nprint(trainable_params)","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:47.154488Z","iopub.execute_input":"2026-10-03T17:33:47.154805Z","iopub.status.idle":"2026-10-03T17:33:47.161247Z","shell.execute_reply.started":"2026-10-03T17:33:47.15478Z","shell.execute_reply":"2026-10-03T17:33:47.160299Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_resnet50v2.reset_states()\nhistory_resnet50v2 = model_resnet50v2.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-03T17:33:47.162631Z","iopub.execute_input":"2026-10-03T17:33:47.162973Z","iopub.status.idle":"2026-10-03T17:41:56.425007Z","shell.execute_reply.started":"2026-10-03T17:33:47.16294Z","shell.execute_reply":"2026-10-03T17:41:56.424181Z"}},"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_resnet50v2.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:41:56.426261Z","iopub.execute_input":"2026-10-03T17:41:56.426528Z","iopub.status.idle":"2026-10-03T17:41:58.156068Z","shell.execute_reply.started":"2026-10-03T17:41:56.426505Z","shell.execute_reply":"2026-10-03T17:41:58.155091Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# ResNet50V2 (Fined-tuning)","metadata":{}},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.resnet_v2 import preprocess_input\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-03T17:41:58.157225Z","iopub.execute_input":"2026-10-03T17:41:58.157588Z","iopub.status.idle":"2026-10-03T17:42:02.731969Z","shell.execute_reply.started":"2026-10-03T17:41:58.157564Z","shell.execute_reply":"2026-10-03T17:42:02.731298Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================ Block 2 (Fine-tuning Version) ================\nfrom keras.applications.resnet_v2 import ResNet50V2\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_resnet50v2():\n    # 1. Load Base Model\n    base_model = ResNet50V2(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    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 ที่ต่ำมาก\n    opt = SGD(learning_rate=0.0001, 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-03T17:42:02.73301Z","iopub.execute_input":"2026-10-03T17:42:02.733301Z","iopub.status.idle":"2026-10-03T17:42:02.739949Z","shell.execute_reply.started":"2026-10-03T17:42:02.733277Z","shell.execute_reply":"2026-10-03T17:42:02.738842Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_resnet50v2 = define_model_resnet50v2()\nprint(id(model_resnet50v2))\n# model_resnet50v2.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:42:02.740959Z","iopub.execute_input":"2026-10-03T17:42:02.741267Z","iopub.status.idle":"2026-10-03T17:42:04.280025Z","shell.execute_reply.started":"2026-10-03T17:42:02.741235Z","shell.execute_reply":"2026-10-03T17:42:04.279019Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_resnet50v2.reset_states()\nhistory_resnet50v2 = model_resnet50v2.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-03T17:42:04.281173Z","iopub.execute_input":"2026-10-03T17:42:04.282067Z","iopub.status.idle":"2026-10-03T17:50:22.684372Z","shell.execute_reply.started":"2026-10-03T17:42:04.282039Z","shell.execute_reply":"2026-10-03T17:50:22.683506Z"}},"outputs":[],"execution_count":null}]}