{"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:04:59.139917Z","iopub.execute_input":"2026-10-03T17:04:59.140326Z","iopub.status.idle":"2026-10-03T17:04:59.445674Z","shell.execute_reply.started":"2026-10-03T17:04:59.140301Z","shell.execute_reply":"2026-10-03T17:04:59.444696Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:04:59.44685Z","iopub.execute_input":"2026-10-03T17:04:59.447333Z","iopub.status.idle":"2026-10-03T17:05:00.553413Z","shell.execute_reply.started":"2026-10-03T17:04:59.447289Z","shell.execute_reply":"2026-10-03T17:05:00.552163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:00.55561Z","iopub.execute_input":"2026-10-03T17:05:00.555988Z","iopub.status.idle":"2026-10-03T17:05:01.569168Z","shell.execute_reply.started":"2026-10-03T17:05:00.555964Z","shell.execute_reply":"2026-10-03T17:05:01.568349Z"}},"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:05:14.926938Z","iopub.execute_input":"2026-10-03T17:05:14.927399Z","iopub.status.idle":"2026-10-03T17:05:26.285879Z","shell.execute_reply.started":"2026-10-03T17:05:14.927366Z","shell.execute_reply":"2026-10-03T17:05:26.285114Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:29.343646Z","iopub.execute_input":"2026-10-03T17:05:29.34408Z","iopub.status.idle":"2026-10-03T17:05:30.331739Z","shell.execute_reply.started":"2026-10-03T17:05:29.344049Z","shell.execute_reply":"2026-10-03T17:05:30.330476Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:33.4553Z","iopub.execute_input":"2026-10-03T17:05:33.455669Z","iopub.status.idle":"2026-10-03T17:05:34.443403Z","shell.execute_reply.started":"2026-10-03T17:05:33.455638Z","shell.execute_reply":"2026-10-03T17:05:34.442453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:34.445259Z","iopub.execute_input":"2026-10-03T17:05:34.445555Z","iopub.status.idle":"2026-10-03T17:05:35.462076Z","shell.execute_reply.started":"2026-10-03T17:05:34.445531Z","shell.execute_reply":"2026-10-03T17:05:35.46123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:35.463436Z","iopub.execute_input":"2026-10-03T17:05:35.463717Z","iopub.status.idle":"2026-10-03T17:05:36.524214Z","shell.execute_reply.started":"2026-10-03T17:05:35.463692Z","shell.execute_reply":"2026-10-03T17:05:36.523348Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:36.526066Z","iopub.execute_input":"2026-10-03T17:05:36.52646Z","iopub.status.idle":"2026-10-03T17:05:36.530607Z","shell.execute_reply.started":"2026-10-03T17:05:36.526434Z","shell.execute_reply":"2026-10-03T17:05:36.529743Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:36.531693Z","iopub.execute_input":"2026-10-03T17:05:36.532298Z","iopub.status.idle":"2026-10-03T17:05:37.588577Z","shell.execute_reply.started":"2026-10-03T17:05:36.532267Z","shell.execute_reply":"2026-10-03T17:05:37.587437Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:37.590004Z","iopub.execute_input":"2026-10-03T17:05:37.590352Z","iopub.status.idle":"2026-10-03T17:05:38.599393Z","shell.execute_reply.started":"2026-10-03T17:05:37.590323Z","shell.execute_reply":"2026-10-03T17:05:38.598505Z"}},"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:05:57.616474Z","iopub.execute_input":"2026-10-03T17:05:57.617174Z","iopub.status.idle":"2026-10-03T17:05:58.807133Z","shell.execute_reply.started":"2026-10-03T17:05:57.617141Z","shell.execute_reply":"2026-10-03T17:05:58.805977Z"},"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:05:58.808704Z","iopub.execute_input":"2026-10-03T17:05:58.809073Z","iopub.status.idle":"2026-10-03T17:05:59.826827Z","shell.execute_reply.started":"2026-10-03T17:05:58.809048Z","shell.execute_reply":"2026-10-03T17:05:59.825695Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:05:59.827966Z","iopub.execute_input":"2026-10-03T17:05:59.828342Z","iopub.status.idle":"2026-10-03T17:06:00.855441Z","shell.execute_reply.started":"2026-10-03T17:05:59.828298Z","shell.execute_reply":"2026-10-03T17:06:00.854225Z"}},"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:06:00.858633Z","iopub.execute_input":"2026-10-03T17:06:00.859042Z","iopub.status.idle":"2026-10-03T17:06:13.212423Z","shell.execute_reply.started":"2026-10-03T17:06:00.859016Z","shell.execute_reply":"2026-10-03T17:06:13.211523Z"}},"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:06:13.213472Z","iopub.execute_input":"2026-10-03T17:06:13.214297Z","iopub.status.idle":"2026-10-03T17:06:13.218748Z","shell.execute_reply.started":"2026-10-03T17:06:13.214267Z","shell.execute_reply":"2026-10-03T17:06:13.217361Z"},"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:06:13.220074Z","iopub.execute_input":"2026-10-03T17:06:13.220384Z","iopub.status.idle":"2026-10-03T17:06:13.249103Z","shell.execute_reply.started":"2026-10-03T17:06:13.220359Z","shell.execute_reply":"2026-10-03T17:06:13.248063Z"},"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:06:13.250414Z","iopub.execute_input":"2026-10-03T17:06:13.251053Z","iopub.status.idle":"2026-10-03T17:06:13.259125Z","shell.execute_reply.started":"2026-10-03T17:06:13.251016Z","shell.execute_reply":"2026-10-03T17:06:13.258249Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:06:13.260503Z","iopub.execute_input":"2026-10-03T17:06:13.260864Z","iopub.status.idle":"2026-10-03T17:06:14.267222Z","shell.execute_reply.started":"2026-10-03T17:06:13.260839Z","shell.execute_reply":"2026-10-03T17:06:14.26598Z"}},"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:06:14.268855Z","iopub.execute_input":"2026-10-03T17:06:14.269806Z","iopub.status.idle":"2026-10-03T17:06:15.253702Z","shell.execute_reply.started":"2026-10-03T17:06:14.269766Z","shell.execute_reply":"2026-10-03T17:06:15.252697Z"}},"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:06:15.257472Z","iopub.execute_input":"2026-10-03T17:06:15.257724Z","iopub.status.idle":"2026-10-03T17:06:16.261334Z","shell.execute_reply.started":"2026-10-03T17:06:15.257704Z","shell.execute_reply":"2026-10-03T17:06:16.26043Z"}},"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:06:16.262781Z","iopub.execute_input":"2026-10-03T17:06:16.263086Z","iopub.status.idle":"2026-10-03T17:06:18.198353Z","shell.execute_reply.started":"2026-10-03T17:06:16.263061Z","shell.execute_reply":"2026-10-03T17:06:18.197256Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:06:18.199868Z","iopub.execute_input":"2026-10-03T17:06:18.200362Z","iopub.status.idle":"2026-10-03T17:06:18.205212Z","shell.execute_reply.started":"2026-10-03T17:06:18.200335Z","shell.execute_reply":"2026-10-03T17:06:18.204221Z"}},"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:06:18.20641Z","iopub.execute_input":"2026-10-03T17:06:18.207266Z","iopub.status.idle":"2026-10-03T17:06:20.354323Z","shell.execute_reply.started":"2026-10-03T17:06:18.207233Z","shell.execute_reply":"2026-10-03T17:06:20.353167Z"},"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:06:20.355933Z","iopub.execute_input":"2026-10-03T17:06:20.356846Z","iopub.status.idle":"2026-10-03T17:06:22.358343Z","shell.execute_reply.started":"2026-10-03T17:06:20.356819Z","shell.execute_reply":"2026-10-03T17:06:22.357374Z"},"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:06:22.35993Z","iopub.execute_input":"2026-10-03T17:06:22.36079Z","iopub.status.idle":"2026-10-03T17:06:32.555041Z","shell.execute_reply.started":"2026-10-03T17:06:22.360752Z","shell.execute_reply":"2026-10-03T17:06:32.554002Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-10-03T17:06:32.556418Z","iopub.execute_input":"2026-10-03T17:06:32.556712Z","iopub.status.idle":"2026-10-03T17:06:32.572861Z","shell.execute_reply.started":"2026-10-03T17:06:32.556688Z","shell.execute_reply":"2026-10-03T17:06:32.572088Z"},"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:06:32.574008Z","iopub.execute_input":"2026-10-03T17:06:32.574801Z","iopub.status.idle":"2026-10-03T17:06:32.578489Z","shell.execute_reply.started":"2026-10-03T17:06:32.574777Z","shell.execute_reply":"2026-10-03T17:06:32.577706Z"}},"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, Dropout\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:12:25.424265Z","iopub.execute_input":"2026-10-03T17:12:25.425333Z","iopub.status.idle":"2026-10-03T17:12:25.430279Z","shell.execute_reply.started":"2026-10-03T17:12:25.425293Z","shell.execute_reply":"2026-10-03T17:12:25.429433Z"}},"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 = Adam(learning_rate=0.0001)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:12:25.606732Z","iopub.execute_input":"2026-10-03T17:12:25.60721Z","iopub.status.idle":"2026-10-03T17:12:25.613465Z","shell.execute_reply.started":"2026-10-03T17:12:25.607154Z","shell.execute_reply":"2026-10-03T17:12:25.612593Z"}},"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:12:25.78302Z","iopub.execute_input":"2026-10-03T17:12:25.783287Z","iopub.status.idle":"2026-10-03T17:12:27.899898Z","shell.execute_reply.started":"2026-10-03T17:12:25.783264Z","shell.execute_reply":"2026-10-03T17:12:27.898976Z"}},"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:12:27.901575Z","iopub.execute_input":"2026-10-03T17:12:27.901876Z","iopub.status.idle":"2026-10-03T17:12:27.908036Z","shell.execute_reply.started":"2026-10-03T17:12:27.901852Z","shell.execute_reply":"2026-10-03T17:12:27.907166Z"}},"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:12:27.909016Z","iopub.execute_input":"2026-10-03T17:12:27.909302Z","iopub.status.idle":"2026-10-03T17:12:27.986162Z","shell.execute_reply.started":"2026-10-03T17:12:27.90927Z","shell.execute_reply":"2026-10-03T17:12:27.985423Z"}},"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, Dropout\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:12:27.987904Z","iopub.execute_input":"2026-10-03T17:12:27.988578Z","iopub.status.idle":"2026-10-03T17:12:28.061943Z","shell.execute_reply.started":"2026-10-03T17:12:27.988546Z","shell.execute_reply":"2026-10-03T17:12:28.061053Z"}},"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, Dropout\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:12:32.024024Z","iopub.execute_input":"2026-10-03T17:12:32.024707Z","iopub.status.idle":"2026-10-03T17:12:32.112378Z","shell.execute_reply.started":"2026-10-03T17:12:32.024675Z","shell.execute_reply":"2026-10-03T17:12:32.111559Z"}},"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:12:32.183393Z","iopub.execute_input":"2026-10-03T17:12:32.183625Z","iopub.status.idle":"2026-10-03T17:12:32.190219Z","shell.execute_reply.started":"2026-10-03T17:12:32.183605Z","shell.execute_reply":"2026-10-03T17:12:32.189253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:12:32.351728Z","iopub.execute_input":"2026-10-03T17:12:32.352007Z","iopub.status.idle":"2026-10-03T17:12:33.370148Z","shell.execute_reply.started":"2026-10-03T17:12:32.351985Z","shell.execute_reply":"2026-10-03T17:12:33.368927Z"}},"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:12:33.372409Z","iopub.execute_input":"2026-10-03T17:12:33.372795Z","iopub.status.idle":"2026-10-03T17:12:33.377391Z","shell.execute_reply.started":"2026-10-03T17:12:33.37276Z","shell.execute_reply":"2026-10-03T17:12:33.376474Z"}},"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:12:33.378481Z","iopub.execute_input":"2026-10-03T17:12:33.378755Z","iopub.status.idle":"2026-10-03T17:13:06.051312Z","shell.execute_reply.started":"2026-10-03T17:12:33.378732Z","shell.execute_reply":"2026-10-03T17:13:06.05056Z"}},"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\nfrom tensorflow.keras.applications.vgg16 import preprocess_input\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    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    validation_split=VAL_SPLIT,\n)\n\nval_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,          # 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:13:06.053486Z","iopub.execute_input":"2026-10-03T17:13:06.053837Z","iopub.status.idle":"2026-10-03T17:13:06.941642Z","shell.execute_reply.started":"2026-10-03T17:13:06.053806Z","shell.execute_reply":"2026-10-03T17:13:06.940647Z"}},"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:13:06.942709Z","iopub.execute_input":"2026-10-03T17:13:06.943063Z","iopub.status.idle":"2026-10-03T17:13:06.950498Z","shell.execute_reply.started":"2026-10-03T17:13:06.94304Z","shell.execute_reply":"2026-10-03T17:13:06.949598Z"}},"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:22:33.068537Z","iopub.execute_input":"2026-10-03T17:22:33.069349Z","iopub.status.idle":"2026-10-03T17:22:33.076157Z","shell.execute_reply.started":"2026-10-03T17:22:33.069316Z","shell.execute_reply":"2026-10-03T17:22:33.075163Z"}},"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:22:33.23042Z","iopub.execute_input":"2026-10-03T17:22:33.231099Z","iopub.status.idle":"2026-10-03T17:22:33.235044Z","shell.execute_reply.started":"2026-10-03T17:22:33.231072Z","shell.execute_reply":"2026-10-03T17:22:33.234061Z"}},"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:22:33.495959Z","iopub.execute_input":"2026-10-03T17:22:33.496832Z","iopub.status.idle":"2026-10-03T17:22:33.500685Z","shell.execute_reply.started":"2026-10-03T17:22:33.496801Z","shell.execute_reply":"2026-10-03T17:22:33.499584Z"}},"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:22:33.650913Z","iopub.execute_input":"2026-10-03T17:22:33.651202Z","iopub.status.idle":"2026-10-03T17:22:33.655109Z","shell.execute_reply.started":"2026-10-03T17:22:33.651158Z","shell.execute_reply":"2026-10-03T17:22:33.65424Z"}},"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:22:34.499062Z","iopub.execute_input":"2026-10-03T17:22:34.499926Z","iopub.status.idle":"2026-10-03T17:22:35.532555Z","shell.execute_reply.started":"2026-10-03T17:22:34.49989Z","shell.execute_reply":"2026-10-03T17:22:35.531282Z"}},"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:22:35.534621Z","iopub.execute_input":"2026-10-03T17:22:35.534951Z","iopub.status.idle":"2026-10-03T17:22:35.541401Z","shell.execute_reply.started":"2026-10-03T17:22:35.534925Z","shell.execute_reply":"2026-10-03T17:22:35.540413Z"}},"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:22:35.544057Z","iopub.execute_input":"2026-10-03T17:22:35.544796Z","iopub.status.idle":"2026-10-03T17:22:35.553166Z","shell.execute_reply.started":"2026-10-03T17:22:35.544768Z","shell.execute_reply":"2026-10-03T17:22:35.552241Z"}},"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:22:35.554997Z","iopub.execute_input":"2026-10-03T17:22:35.55531Z","iopub.status.idle":"2026-10-03T17:22:35.566305Z","shell.execute_reply.started":"2026-10-03T17:22:35.555269Z","shell.execute_reply":"2026-10-03T17:22:35.565412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:22:35.780044Z","iopub.execute_input":"2026-10-03T17:22:35.78075Z","iopub.status.idle":"2026-10-03T17:22:35.784675Z","shell.execute_reply.started":"2026-10-03T17:22:35.780717Z","shell.execute_reply":"2026-10-03T17:22:35.783584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:22:36.140042Z","iopub.execute_input":"2026-10-03T17:22:36.140841Z","iopub.status.idle":"2026-10-03T17:22:36.145274Z","shell.execute_reply.started":"2026-10-03T17:22:36.140802Z","shell.execute_reply":"2026-10-03T17:22:36.144345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:22:36.315631Z","iopub.execute_input":"2026-10-03T17:22:36.316366Z","iopub.status.idle":"2026-10-03T17:22:36.320254Z","shell.execute_reply.started":"2026-10-03T17:22:36.316336Z","shell.execute_reply":"2026-10-03T17:22:36.319242Z"}},"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:22:36.924754Z","iopub.execute_input":"2026-10-03T17:22:36.925506Z","iopub.status.idle":"2026-10-03T17:22:36.930459Z","shell.execute_reply.started":"2026-10-03T17:22:36.925473Z","shell.execute_reply":"2026-10-03T17:22:36.929372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:22:37.348515Z","iopub.execute_input":"2026-10-03T17:22:37.348987Z","iopub.status.idle":"2026-10-03T17:22:37.354949Z","shell.execute_reply.started":"2026-10-03T17:22:37.348958Z","shell.execute_reply":"2026-10-03T17:22:37.353956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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:22:41.412839Z","iopub.execute_input":"2026-10-03T17:22:41.413403Z","iopub.status.idle":"2026-10-03T17:22:53.01163Z","shell.execute_reply.started":"2026-10-03T17:22:41.413369Z","shell.execute_reply":"2026-10-03T17:22:53.0104Z"}},"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:22:53.014513Z","iopub.execute_input":"2026-10-03T17:22:53.014835Z","iopub.status.idle":"2026-10-03T17:22:53.024412Z","shell.execute_reply.started":"2026-10-03T17:22:53.01481Z","shell.execute_reply":"2026-10-03T17:22:53.023244Z"}},"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:22:53.025655Z","iopub.execute_input":"2026-10-03T17:22:53.026455Z","iopub.status.idle":"2026-10-03T17:22:58.693363Z","shell.execute_reply.started":"2026-10-03T17:22:53.026417Z","shell.execute_reply":"2026-10-03T17:22:58.692242Z"}},"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:22:58.695037Z","iopub.execute_input":"2026-10-03T17:22:58.695407Z","iopub.status.idle":"2026-10-03T17:23:04.07916Z","shell.execute_reply.started":"2026-10-03T17:22:58.695381Z","shell.execute_reply":"2026-10-03T17:23:04.078113Z"}},"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:23:04.08051Z","iopub.execute_input":"2026-10-03T17:23:04.080814Z","iopub.status.idle":"2026-10-03T17:23:04.086499Z","shell.execute_reply.started":"2026-10-03T17:23:04.08079Z","shell.execute_reply":"2026-10-03T17:23:04.085651Z"},"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:23:04.087717Z","iopub.execute_input":"2026-10-03T17:23:04.088043Z","iopub.status.idle":"2026-10-03T17:23:09.442953Z","shell.execute_reply.started":"2026-10-03T17:23:04.088019Z","shell.execute_reply":"2026-10-03T17:23:09.442064Z"}},"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:24:44.394819Z","iopub.execute_input":"2026-10-03T17:24:44.395764Z","iopub.status.idle":"2026-10-03T17:24:44.399858Z","shell.execute_reply.started":"2026-10-03T17:24:44.395732Z","shell.execute_reply":"2026-10-03T17:24:44.398986Z"}},"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:24:44.722581Z","iopub.execute_input":"2026-10-03T17:24:44.722891Z","iopub.status.idle":"2026-10-03T17:24:44.727978Z","shell.execute_reply.started":"2026-10-03T17:24:44.722868Z","shell.execute_reply":"2026-10-03T17:24:44.727291Z"}},"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:24:44.881684Z","iopub.execute_input":"2026-10-03T17:24:44.882557Z","iopub.status.idle":"2026-10-03T17:24:44.887911Z","shell.execute_reply.started":"2026-10-03T17:24:44.88253Z","shell.execute_reply":"2026-10-03T17:24:44.886923Z"}},"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 = Adam(learning_rate=0.0001)\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:24:45.042757Z","iopub.execute_input":"2026-10-03T17:24:45.043971Z","iopub.status.idle":"2026-10-03T17:24:45.753162Z","shell.execute_reply.started":"2026-10-03T17:24:45.043926Z","shell.execute_reply":"2026-10-03T17:24:45.75244Z"}},"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:24:45.754494Z","iopub.execute_input":"2026-10-03T17:24:45.754843Z","iopub.status.idle":"2026-10-03T17:24:50.380214Z","shell.execute_reply.started":"2026-10-03T17:24:45.754819Z","shell.execute_reply":"2026-10-03T17:24:50.379383Z"}},"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:24:50.381535Z","iopub.execute_input":"2026-10-03T17:24:50.3819Z","iopub.status.idle":"2026-10-03T17:24:50.747448Z","shell.execute_reply.started":"2026-10-03T17:24:50.381867Z","shell.execute_reply":"2026-10-03T17:24:50.746614Z"}},"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:24:50.749479Z","iopub.execute_input":"2026-10-03T17:24:50.749764Z","iopub.status.idle":"2026-10-03T17:24:50.754906Z","shell.execute_reply.started":"2026-10-03T17:24:50.749735Z","shell.execute_reply":"2026-10-03T17:24:50.753994Z"}},"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:24:50.755996Z","iopub.execute_input":"2026-10-03T17:24:50.756301Z","iopub.status.idle":"2026-10-03T17:24:50.769265Z","shell.execute_reply.started":"2026-10-03T17:24:50.756269Z","shell.execute_reply":"2026-10-03T17:24:50.768269Z"}},"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:24:50.770401Z","iopub.execute_input":"2026-10-03T17:24:50.770613Z","iopub.status.idle":"2026-10-03T17:24:50.782888Z","shell.execute_reply.started":"2026-10-03T17:24:50.770594Z","shell.execute_reply":"2026-10-03T17:24:50.782235Z"}},"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:24:50.783926Z","iopub.execute_input":"2026-10-03T17:24:50.784232Z","iopub.status.idle":"2026-10-03T17:24:50.798383Z","shell.execute_reply.started":"2026-10-03T17:24:50.7842Z","shell.execute_reply":"2026-10-03T17:24:50.797431Z"}},"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:24:50.799592Z","iopub.execute_input":"2026-10-03T17:24:50.799863Z","iopub.status.idle":"2026-10-03T17:24:50.822952Z","shell.execute_reply.started":"2026-10-03T17:24:50.799841Z","shell.execute_reply":"2026-10-03T17:24:50.822238Z"}},"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:24:50.823842Z","iopub.execute_input":"2026-10-03T17:24:50.824062Z","iopub.status.idle":"2026-10-03T17:24:50.83815Z","shell.execute_reply.started":"2026-10-03T17:24:50.824045Z","shell.execute_reply":"2026-10-03T17:24:50.837408Z"}},"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:24:50.840692Z","iopub.execute_input":"2026-10-03T17:24:50.841046Z","iopub.status.idle":"2026-10-03T17:24:50.857145Z","shell.execute_reply.started":"2026-10-03T17:24:50.841023Z","shell.execute_reply":"2026-10-03T17:24:50.856321Z"}},"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:24:50.858538Z","iopub.execute_input":"2026-10-03T17:24:50.859322Z","iopub.status.idle":"2026-10-03T17:24:50.872846Z","shell.execute_reply.started":"2026-10-03T17:24:50.859297Z","shell.execute_reply":"2026-10-03T17:24:50.871954Z"}},"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 = Adam(learning_rate=0.0001)\n\nmodel_vgg16.compile(optimizer=opt,\n                    loss='binary_crossentropy',\n                    metrics=['accuracy']\n                   )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:24:50.874148Z","iopub.execute_input":"2026-10-03T17:24:50.874839Z","iopub.status.idle":"2026-10-03T17:24:50.891211Z","shell.execute_reply.started":"2026-10-03T17:24:50.874769Z","shell.execute_reply":"2026-10-03T17:24:50.890521Z"}},"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:24:50.892151Z","iopub.execute_input":"2026-10-03T17:24:50.892462Z","iopub.status.idle":"2026-10-03T17:24:50.897171Z","shell.execute_reply.started":"2026-10-03T17:24:50.89244Z","shell.execute_reply":"2026-10-03T17:24:50.896139Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:24:50.898328Z","iopub.execute_input":"2026-10-03T17:24:50.89923Z","iopub.status.idle":"2026-10-03T17:24:50.95059Z","shell.execute_reply.started":"2026-10-03T17:24:50.89917Z","shell.execute_reply":"2026-10-03T17:24:50.949807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:24:50.961806Z","iopub.execute_input":"2026-10-03T17:24:50.962326Z","iopub.status.idle":"2026-10-03T17:24:50.967449Z","shell.execute_reply.started":"2026-10-03T17:24:50.962298Z","shell.execute_reply":"2026-10-03T17:24:50.966519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# del ตัวแปร #ลบตัวแปรออกจากหน่วยความจำ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:24:51.139116Z","iopub.execute_input":"2026-10-03T17:24:51.139482Z","iopub.status.idle":"2026-10-03T17:24:51.143677Z","shell.execute_reply.started":"2026-10-03T17:24:51.139457Z","shell.execute_reply":"2026-10-03T17:24:51.142729Z"}},"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:24:51.308521Z","iopub.execute_input":"2026-10-03T17:24:51.308834Z","iopub.status.idle":"2026-10-03T17:24:51.312952Z","shell.execute_reply.started":"2026-10-03T17:24:51.30881Z","shell.execute_reply":"2026-10-03T17:24:51.312062Z"}},"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:24:51.498513Z","iopub.execute_input":"2026-10-03T17:24:51.499154Z","iopub.status.idle":"2026-10-03T17:31:14.588388Z","shell.execute_reply.started":"2026-10-03T17:24:51.499124Z","shell.execute_reply":"2026-10-03T17:31:14.587311Z"}},"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:31:14.590453Z","iopub.execute_input":"2026-10-03T17:31:14.590748Z","iopub.status.idle":"2026-10-03T17:31:14.94755Z","shell.execute_reply.started":"2026-10-03T17:31:14.59072Z","shell.execute_reply":"2026-10-03T17:31:14.946872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"_, 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:31:14.948582Z","iopub.execute_input":"2026-10-03T17:31:14.948856Z","iopub.status.idle":"2026-10-03T17:32:10.485225Z","shell.execute_reply.started":"2026-10-03T17:31:14.948834Z","shell.execute_reply":"2026-10-03T17:32:10.484262Z"}},"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.487556Z","iopub.execute_input":"2026-10-03T17:32:10.487895Z","iopub.status.idle":"2026-10-03T17:32:13.725104Z","shell.execute_reply.started":"2026-10-03T17:32:10.487872Z","shell.execute_reply":"2026-10-03T17:32:13.724418Z"}},"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.726266Z","iopub.execute_input":"2026-10-03T17:32:13.726608Z","iopub.status.idle":"2026-10-03T17:32:46.895544Z","shell.execute_reply.started":"2026-10-03T17:32:13.726585Z","shell.execute_reply":"2026-10-03T17:32:46.894749Z"}},"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:46.896805Z","iopub.execute_input":"2026-10-03T17:32:46.897153Z","iopub.status.idle":"2026-10-03T17:33:19.743749Z","shell.execute_reply.started":"2026-10-03T17:32:46.89712Z","shell.execute_reply":"2026-10-03T17:33:19.742844Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:19.744877Z","iopub.execute_input":"2026-10-03T17:33:19.745299Z","iopub.status.idle":"2026-10-03T17:33:19.75397Z","shell.execute_reply.started":"2026-10-03T17:33:19.745273Z","shell.execute_reply":"2026-10-03T17:33:19.753185Z"}},"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:19.755152Z","iopub.execute_input":"2026-10-03T17:33:19.75549Z","iopub.status.idle":"2026-10-03T17:33:19.775455Z","shell.execute_reply.started":"2026-10-03T17:33:19.75546Z","shell.execute_reply":"2026-10-03T17:33:19.77449Z"}},"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:19.776612Z","iopub.execute_input":"2026-10-03T17:33:19.776924Z","iopub.status.idle":"2026-10-03T17:33:19.805709Z","shell.execute_reply.started":"2026-10-03T17:33:19.776895Z","shell.execute_reply":"2026-10-03T17:33:19.804804Z"}},"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:19.807829Z","iopub.execute_input":"2026-10-03T17:33:19.808044Z","iopub.status.idle":"2026-10-03T17:33:19.814049Z","shell.execute_reply.started":"2026-10-03T17:33:19.808025Z","shell.execute_reply":"2026-10-03T17:33:19.813037Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# เริ่มจาก batch แรก\ntest_it.reset()\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(4):\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\n\nnum_samples = min(100, all_images.shape[0])\n\nrandom_indices = np.random.choice(\n    all_images.shape[0],\n    size=num_samples,\n    replace=False\n)\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:19.815162Z","iopub.execute_input":"2026-10-03T17:33:19.815457Z","iopub.status.idle":"2026-10-03T17:33:22.222942Z","shell.execute_reply.started":"2026-10-03T17:33:19.815437Z","shell.execute_reply":"2026-10-03T17:33:22.222154Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_it.reset()\n\nbatch1_images, batch1_labels = next(test_it)\nprint(\"Batch 1:\", batch1_images.shape)\n\nbatch2_images, batch2_labels = next(test_it)\nprint(\"Batch 2:\", batch2_images.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:22.224125Z","iopub.execute_input":"2026-10-03T17:33:22.224607Z","iopub.status.idle":"2026-10-03T17:33:22.423862Z","shell.execute_reply.started":"2026-10-03T17:33:22.22458Z","shell.execute_reply":"2026-10-03T17:33:22.423094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:22.424916Z","iopub.execute_input":"2026-10-03T17:33:22.425313Z","iopub.status.idle":"2026-10-03T17:33:30.6525Z","shell.execute_reply.started":"2026-10-03T17:33:22.425284Z","shell.execute_reply":"2026-10-03T17:33:30.65143Z"}},"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-10-03T17:33:30.653658Z","iopub.execute_input":"2026-10-03T17:33:30.654054Z","iopub.status.idle":"2026-10-03T17:33:31.151768Z","shell.execute_reply.started":"2026-10-03T17:33:30.654028Z","shell.execute_reply":"2026-10-03T17:33:31.15059Z"}},"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(1, activation='sigmoid')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = Adam(learning_rate=0.0001)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:53.019989Z","iopub.execute_input":"2026-10-03T17:33:53.021636Z","iopub.status.idle":"2026-10-03T17:33:53.030695Z","shell.execute_reply.started":"2026-10-03T17:33:53.021591Z","shell.execute_reply":"2026-10-03T17:33:53.029677Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-10-03T17:33:53.188705Z","iopub.execute_input":"2026-10-03T17:33:53.188972Z","iopub.status.idle":"2026-10-03T17:33:56.238619Z","shell.execute_reply.started":"2026-10-03T17:33:53.188949Z","shell.execute_reply":"2026-10-03T17:33:56.237829Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\n\nfor index, layer in enumerate(model_inceptionv3.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:56.240077Z","iopub.execute_input":"2026-10-03T17:33:56.240429Z","iopub.status.idle":"2026-10-03T17:33:58.439921Z","shell.execute_reply.started":"2026-10-03T17:33:56.2404Z","shell.execute_reply":"2026-10-03T17:33:58.438864Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#print(model_inceptionv3.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:33:58.441089Z","iopub.execute_input":"2026-10-03T17:33:58.441467Z","iopub.status.idle":"2026-10-03T17:33:58.445714Z","shell.execute_reply.started":"2026-10-03T17:33:58.441434Z","shell.execute_reply":"2026-10-03T17:33:58.44489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.vgg16 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',     # 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:33:58.447256Z","iopub.execute_input":"2026-10-03T17:33:58.447532Z","iopub.status.idle":"2026-10-03T17:34:08.742807Z","shell.execute_reply.started":"2026-10-03T17:33:58.447511Z","shell.execute_reply":"2026-10-03T17:34:08.742091Z"}},"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\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\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 = 299\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    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    validation_split=VAL_SPLIT,\n)\n\nval_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,          # 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:34:08.744293Z","iopub.execute_input":"2026-10-03T17:34:08.744712Z","iopub.status.idle":"2026-10-03T17:34:08.914514Z","shell.execute_reply.started":"2026-10-03T17:34:08.744678Z","shell.execute_reply":"2026-10-03T17:34:08.913532Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-10-03T17:34:08.915656Z","iopub.execute_input":"2026-10-03T17:34:08.915986Z","iopub.status.idle":"2026-10-03T17:34:08.922407Z","shell.execute_reply.started":"2026-10-03T17:34:08.915955Z","shell.execute_reply":"2026-10-03T17:34:08.921569Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nfor w in model_inceptionv3.trainable_weights:\n    print(w.name, K.count_params(w))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:34:08.923473Z","iopub.execute_input":"2026-10-03T17:34:08.923728Z","iopub.status.idle":"2026-10-03T17:34:08.939857Z","shell.execute_reply.started":"2026-10-03T17:34:08.923708Z","shell.execute_reply":"2026-10-03T17:34:08.93902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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_inceptionv3.reset_states()\n        \n        model_inceptionv3_history = model_inceptionv3.fit(\n            train_it, \n            steps_per_epoch=len(train_it),\n            validation_data=val_it,\n            validation_steps=len(val_it),\n            epochs=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_inceptionv3_history = model_inceptionv3.fit(\n        train_it, \n        steps_per_epoch=len(train_it),\n        validation_data=val_it,\n        validation_steps=len(val_it),\n        epochs=2, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:34:08.942028Z","iopub.execute_input":"2026-10-03T17:34:08.942704Z","iopub.status.idle":"2026-10-03T17:39:31.350012Z","shell.execute_reply.started":"2026-10-03T17:34:08.942671Z","shell.execute_reply":"2026-10-03T17:39:31.348915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"summarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:39:31.351453Z","iopub.execute_input":"2026-10-03T17:39:31.352319Z","iopub.status.idle":"2026-10-03T17:39:31.724639Z","shell.execute_reply.started":"2026-10-03T17:39:31.352283Z","shell.execute_reply":"2026-10-03T17:39:31.723573Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"_, test_acc = model_inceptionv3.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:47:13.313342Z","iopub.execute_input":"2026-10-03T17:47:13.314238Z","iopub.status.idle":"2026-10-03T17:47:13.675051Z","shell.execute_reply.started":"2026-10-03T17:47:13.314153Z","shell.execute_reply":"2026-10-03T17:47:13.672815Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:16.525151Z","iopub.execute_input":"2026-10-03T17:50:16.525558Z","iopub.status.idle":"2026-10-03T17:50:16.532844Z","shell.execute_reply.started":"2026-10-03T17:50:16.525527Z","shell.execute_reply":"2026-10-03T17:50:16.531885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:16.694442Z","iopub.execute_input":"2026-10-03T17:50:16.694667Z","iopub.status.idle":"2026-10-03T17:50:16.698766Z","shell.execute_reply.started":"2026-10-03T17:50:16.694648Z","shell.execute_reply":"2026-10-03T17:50:16.697801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:16.855442Z","iopub.execute_input":"2026-10-03T17:50:16.855919Z","iopub.status.idle":"2026-10-03T17:50:16.859213Z","shell.execute_reply.started":"2026-10-03T17:50:16.855895Z","shell.execute_reply":"2026-10-03T17:50:16.858335Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # mark loaded layers as not trainable\n# for index, layer in enumerate(model.layers[:15]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = False\n    \n# for index, layer in enumerate(model.layers[15:]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:20.691416Z","iopub.execute_input":"2026-10-03T17:50:20.691773Z","iopub.status.idle":"2026-10-03T17:50:20.696174Z","shell.execute_reply.started":"2026-10-03T17:50:20.69174Z","shell.execute_reply":"2026-10-03T17:50:20.695234Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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=(299, 299)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:20.875047Z","iopub.execute_input":"2026-10-03T17:50:20.87534Z","iopub.status.idle":"2026-10-03T17:50:26.846626Z","shell.execute_reply.started":"2026-10-03T17:50:20.875309Z","shell.execute_reply":"2026-10-03T17:50:26.845633Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\n# best_model = 'vgg16_model.hdf5'\n# my_model.save(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:50:26.848526Z","iopub.execute_input":"2026-10-03T17:50:26.848888Z","iopub.status.idle":"2026-10-03T17:51:03.580217Z","shell.execute_reply.started":"2026-10-03T17:50:26.848855Z","shell.execute_reply":"2026-10-03T17:51:03.579345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# images = test_it.__next__()\n# images.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:51:03.581546Z","iopub.execute_input":"2026-10-03T17:51:03.581888Z","iopub.status.idle":"2026-10-03T17:51:03.586682Z","shell.execute_reply.started":"2026-10-03T17:51:03.581856Z","shell.execute_reply":"2026-10-03T17:51:03.585896Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5 first img: 1, 0, 1, 1, 0\n# images_to_predict = images[:5]\n# images_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:51:03.588817Z","iopub.execute_input":"2026-10-03T17:51:03.589168Z","iopub.status.idle":"2026-10-03T17:51:03.597146Z","shell.execute_reply.started":"2026-10-03T17:51:03.589143Z","shell.execute_reply":"2026-10-03T17:51:03.596257Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = history_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:51:03.598403Z","iopub.execute_input":"2026-10-03T17:51:03.598839Z","iopub.status.idle":"2026-10-03T17:51:03.6371Z","shell.execute_reply.started":"2026-10-03T17:51:03.598805Z","shell.execute_reply":"2026-10-03T17:51:03.636059Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# เริ่มจาก batch แรก\ntest_it.reset()\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(4):\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\n\nnum_samples = min(100, all_images.shape[0])\n\nrandom_indices = np.random.choice(\n    all_images.shape[0],\n    size=num_samples,\n    replace=False\n)\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_inceptionv3.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:55:55.733908Z","iopub.execute_input":"2026-10-03T17:55:55.734895Z","iopub.status.idle":"2026-10-03T17:55:59.437548Z","shell.execute_reply.started":"2026-10-03T17:55:55.734857Z","shell.execute_reply":"2026-10-03T17:55:59.436585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:55:59.43917Z","iopub.execute_input":"2026-10-03T17:55:59.439561Z","iopub.status.idle":"2026-10-03T17:56:08.166056Z","shell.execute_reply.started":"2026-10-03T17:55:59.439526Z","shell.execute_reply":"2026-10-03T17:56:08.16436Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:56:14.101618Z","iopub.execute_input":"2026-10-03T17:56:14.102498Z","iopub.status.idle":"2026-10-03T17:56:14.127791Z","shell.execute_reply.started":"2026-10-03T17:56:14.102465Z","shell.execute_reply":"2026-10-03T17:56:14.126836Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## NASNetLarge¶","metadata":{}},{"cell_type":"code","source":"from keras.applications import NASNetLarge\n\ndef define_model_nasnetlarge():\n    # load model\n    model = NASNetLarge(\n        include_top=False,\n        input_shape=(331, 331, 3)\n    )\n\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(512, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(64, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n\n    output = Dense(1, activation='sigmoid')(class4)\n\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # compile model\n    opt = Adam(learning_rate=0.0001)\n\n    model.compile(\n        optimizer=opt,\n        loss='binary_crossentropy',\n        metrics=['accuracy']\n    )\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:56:21.158242Z","iopub.execute_input":"2026-10-03T17:56:21.158551Z","iopub.status.idle":"2026-10-03T17:56:21.16549Z","shell.execute_reply.started":"2026-10-03T17:56:21.158528Z","shell.execute_reply":"2026-10-03T17:56:21.164529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_nasnetlarge = define_model_nasnetlarge()\nprint(id(model_nasnetlarge))\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:56:21.343719Z","iopub.execute_input":"2026-10-03T17:56:21.34433Z","iopub.status.idle":"2026-10-03T17:56:32.782054Z","shell.execute_reply.started":"2026-10-03T17:56:21.344305Z","shell.execute_reply":"2026-10-03T17:56:32.781194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_nasnetlarge = define_model_nasnetlarge()\n\nfor index, layer in enumerate(model_nasnetlarge.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:56:32.783697Z","iopub.execute_input":"2026-10-03T17:56:32.784045Z","iopub.status.idle":"2026-10-03T17:56:41.291665Z","shell.execute_reply.started":"2026-10-03T17:56:32.784012Z","shell.execute_reply":"2026-10-03T17:56:41.290759Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = 331","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T17:56:41.292786Z","iopub.execute_input":"2026-10-03T17:56:41.293129Z","iopub.status.idle":"2026-10-03T17:56:41.297439Z","shell.execute_reply.started":"2026-10-03T17:56:41.293097Z","shell.execute_reply":"2026-10-03T17:56:41.296577Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.vgg16 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',     # 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:56:41.299699Z","iopub.execute_input":"2026-10-03T17:56:41.299919Z","iopub.status.idle":"2026-10-03T17:56:51.414635Z","shell.execute_reply.started":"2026-10-03T17:56:41.2999Z","shell.execute_reply":"2026-10-03T17:56:51.41395Z"}},"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\nfrom tensorflow.keras.applications.inception_v3 import preprocess_input\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 = 331\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    preprocessing_function=preprocess_input,\n    horizontal_flip=True,\n    validation_split=VAL_SPLIT,\n)\n\nval_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,          # 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:56:51.415807Z","iopub.execute_input":"2026-10-03T17:56:51.416307Z","iopub.status.idle":"2026-10-03T17:56:51.574908Z","shell.execute_reply.started":"2026-10-03T17:56:51.416281Z","shell.execute_reply":"2026-10-03T17:56:51.574248Z"}},"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_nasnetlarge.reset_states()\n        \n        model_nasnetlarge_history = model_nasnetlarge.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_nasnetlarge_history = model_nasnetlarge.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:56:51.575883Z","iopub.execute_input":"2026-10-03T17:56:51.576456Z","iopub.status.idle":"2026-10-03T18:31:52.370011Z","shell.execute_reply.started":"2026-10-03T17:56:51.576432Z","shell.execute_reply":"2026-10-03T18:31:52.36931Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"summarize_diagnostics(model_nasnetlarge_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T18:31:52.371247Z","iopub.execute_input":"2026-10-03T18:31:52.371607Z","iopub.status.idle":"2026-10-03T18:31:52.733946Z","shell.execute_reply.started":"2026-10-03T18:31:52.371582Z","shell.execute_reply":"2026-10-03T18:31:52.733316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    preprocessing_function=preprocess_input,\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=(331, 331)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T18:31:52.73497Z","iopub.execute_input":"2026-10-03T18:31:52.735293Z","iopub.status.idle":"2026-10-03T18:32:03.713487Z","shell.execute_reply.started":"2026-10-03T18:31:52.735264Z","shell.execute_reply":"2026-10-03T18:32:03.712747Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# เริ่มจาก batch แรก\ntest_it.reset()\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(4):\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\n\nnum_samples = min(100, all_images.shape[0])\n\nrandom_indices = np.random.choice(\n    all_images.shape[0],\n    size=num_samples,\n    replace=False\n)\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_nasnetlarge.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-03T18:32:03.715704Z","iopub.execute_input":"2026-10-03T18:32:03.716045Z","iopub.status.idle":"2026-10-03T18:32:13.537325Z","shell.execute_reply.started":"2026-10-03T18:32:03.71602Z","shell.execute_reply":"2026-10-03T18:32:13.536527Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-03T18:32:13.539412Z","iopub.execute_input":"2026-10-03T18:32:13.539751Z","iopub.status.idle":"2026-10-03T18:32:22.181884Z","shell.execute_reply.started":"2026-10-03T18:32:13.539726Z","shell.execute_reply":"2026-10-03T18:32:22.178549Z"}},"outputs":[],"execution_count":null}]}