{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.232604Z","iopub.execute_input":"2026-10-02T04:34:24.233097Z","iopub.status.idle":"2026-10-02T04:34:24.242608Z","shell.execute_reply.started":"2026-10-02T04:34:24.233041Z","shell.execute_reply":"2026-10-02T04:34:24.241725Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.244358Z","iopub.execute_input":"2026-10-02T04:34:24.24521Z","iopub.status.idle":"2026-10-02T04:34:24.397097Z","shell.execute_reply.started":"2026-10-02T04:34:24.245145Z","shell.execute_reply":"2026-10-02T04:34:24.395949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.398687Z","iopub.execute_input":"2026-10-02T04:34:24.399625Z","iopub.status.idle":"2026-10-02T04:34:24.52993Z","shell.execute_reply.started":"2026-10-02T04:34:24.399595Z","shell.execute_reply":"2026-10-02T04:34:24.528709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.5318Z","iopub.execute_input":"2026-10-02T04:34:24.532235Z","iopub.status.idle":"2026-10-02T04:34:24.547522Z","shell.execute_reply.started":"2026-10-02T04:34:24.532189Z","shell.execute_reply":"2026-10-02T04:34:24.5426Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.548277Z","iopub.status.idle":"2026-10-02T04:34:24.548743Z","shell.execute_reply.started":"2026-10-02T04:34:24.548529Z","shell.execute_reply":"2026-10-02T04:34:24.548558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.549641Z","iopub.status.idle":"2026-10-02T04:34:24.551187Z","shell.execute_reply.started":"2026-10-02T04:34:24.550926Z","shell.execute_reply":"2026-10-02T04:34:24.550952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.552264Z","iopub.status.idle":"2026-10-02T04:34:24.552942Z","shell.execute_reply.started":"2026-10-02T04:34:24.552666Z","shell.execute_reply":"2026-10-02T04:34:24.552693Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.554025Z","iopub.status.idle":"2026-10-02T04:34:24.554955Z","shell.execute_reply.started":"2026-10-02T04:34:24.554644Z","shell.execute_reply":"2026-10-02T04:34:24.55471Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.556453Z","iopub.status.idle":"2026-10-02T04:34:24.556817Z","shell.execute_reply.started":"2026-10-02T04:34:24.556643Z","shell.execute_reply":"2026-10-02T04:34:24.556664Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.557686Z","iopub.status.idle":"2026-10-02T04:34:24.558058Z","shell.execute_reply.started":"2026-10-02T04:34:24.557849Z","shell.execute_reply":"2026-10-02T04:34:24.557872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\n# from matplotlib import pyplot as plt\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.559137Z","iopub.status.idle":"2026-10-02T04:34:24.559555Z","shell.execute_reply.started":"2026-10-02T04:34:24.559329Z","shell.execute_reply":"2026-10-02T04:34:24.559353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.562287Z","iopub.status.idle":"2026-10-02T04:34:24.562911Z","shell.execute_reply.started":"2026-10-02T04:34:24.562707Z","shell.execute_reply":"2026-10-02T04:34:24.56273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.563541Z","iopub.status.idle":"2026-10-02T04:34:24.563881Z","shell.execute_reply.started":"2026-10-02T04:34:24.563697Z","shell.execute_reply":"2026-10-02T04:34:24.563717Z"}},"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-02T04:34:24.564508Z","iopub.status.idle":"2026-10-02T04:34:24.565664Z","shell.execute_reply.started":"2026-10-02T04:34:24.565477Z","shell.execute_reply":"2026-10-02T04:34:24.565503Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.566782Z","iopub.status.idle":"2026-10-02T04:34:24.567124Z","shell.execute_reply.started":"2026-10-02T04:34:24.566957Z","shell.execute_reply":"2026-10-02T04:34:24.566979Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.568579Z","iopub.status.idle":"2026-10-02T04:34:24.568993Z","shell.execute_reply.started":"2026-10-02T04:34:24.568772Z","shell.execute_reply":"2026-10-02T04:34:24.568796Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.570646Z","iopub.status.idle":"2026-10-02T04:34:24.571161Z","shell.execute_reply.started":"2026-10-02T04:34:24.570971Z","shell.execute_reply":"2026-10-02T04:34:24.570996Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.572107Z","iopub.status.idle":"2026-10-02T04:34:24.572654Z","shell.execute_reply.started":"2026-10-02T04:34:24.572476Z","shell.execute_reply":"2026-10-02T04:34:24.5725Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.573785Z","iopub.status.idle":"2026-10-02T04:34:24.574498Z","shell.execute_reply.started":"2026-10-02T04:34:24.57429Z","shell.execute_reply":"2026-10-02T04:34:24.574314Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.575178Z","iopub.status.idle":"2026-10-02T04:34:24.575531Z","shell.execute_reply.started":"2026-10-02T04:34:24.57534Z","shell.execute_reply":"2026-10-02T04:34:24.575359Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.576632Z","iopub.status.idle":"2026-10-02T04:34:24.578698Z","shell.execute_reply.started":"2026-10-02T04:34:24.578524Z","shell.execute_reply":"2026-10-02T04:34:24.578556Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.58065Z","iopub.status.idle":"2026-10-02T04:34:24.581022Z","shell.execute_reply.started":"2026-10-02T04:34:24.580899Z","shell.execute_reply":"2026-10-02T04:34:24.580914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.581891Z","iopub.status.idle":"2026-10-02T04:34:24.582535Z","shell.execute_reply.started":"2026-10-02T04:34:24.582318Z","shell.execute_reply":"2026-10-02T04:34:24.58237Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.583334Z","iopub.status.idle":"2026-10-02T04:34:24.583747Z","shell.execute_reply.started":"2026-10-02T04:34:24.583497Z","shell.execute_reply":"2026-10-02T04:34:24.583531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.585466Z","iopub.status.idle":"2026-10-02T04:34:24.586068Z","shell.execute_reply.started":"2026-10-02T04:34:24.58586Z","shell.execute_reply":"2026-10-02T04:34:24.585885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.587924Z","iopub.status.idle":"2026-10-02T04:34:24.589111Z","shell.execute_reply.started":"2026-10-02T04:34:24.588362Z","shell.execute_reply":"2026-10-02T04:34:24.58839Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.590845Z","iopub.status.idle":"2026-10-02T04:34:24.591258Z","shell.execute_reply.started":"2026-10-02T04:34:24.591065Z","shell.execute_reply":"2026-10-02T04:34:24.591088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu',\n                     kernel_initializer='he_uniform',\n                     padding='same',\n                     input_shape=(200, 200, 3))\n             )\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.592655Z","iopub.status.idle":"2026-10-02T04:34:24.593026Z","shell.execute_reply.started":"2026-10-02T04:34:24.592839Z","shell.execute_reply":"2026-10-02T04:34:24.592862Z"}},"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-02T04:34:24.593648Z","iopub.status.idle":"2026-10-02T04:34:24.593863Z","shell.execute_reply.started":"2026-10-02T04:34:24.593757Z","shell.execute_reply":"2026-10-02T04:34:24.59377Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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-02T04:34:24.594804Z","iopub.status.idle":"2026-10-02T04:34:24.59511Z","shell.execute_reply.started":"2026-10-02T04:34:24.594956Z","shell.execute_reply":"2026-10-02T04:34:24.59497Z"}},"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-02T04:34:24.597018Z","iopub.status.idle":"2026-10-02T04:34:24.597381Z","shell.execute_reply.started":"2026-10-02T04:34:24.597204Z","shell.execute_reply":"2026-10-02T04:34:24.597253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.59967Z","iopub.status.idle":"2026-10-02T04:34:24.600156Z","shell.execute_reply.started":"2026-10-02T04:34:24.599978Z","shell.execute_reply":"2026-10-02T04:34:24.600004Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx1 = Conv2D(64, (3, 3), activation='relu')(x1)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.601202Z","iopub.status.idle":"2026-10-02T04:34:24.60161Z","shell.execute_reply.started":"2026-10-02T04:34:24.601391Z","shell.execute_reply":"2026-10-02T04:34:24.601414Z"}},"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-02T04:34:24.60227Z","iopub.status.idle":"2026-10-02T04:34:24.602665Z","shell.execute_reply.started":"2026-10-02T04:34:24.602427Z","shell.execute_reply":"2026-10-02T04:34:24.602501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.603983Z","iopub.status.idle":"2026-10-02T04:34:24.604622Z","shell.execute_reply.started":"2026-10-02T04:34:24.604377Z","shell.execute_reply":"2026-10-02T04:34:24.604402Z"}},"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-02T04:34:24.606388Z","iopub.status.idle":"2026-10-02T04:34:24.606961Z","shell.execute_reply.started":"2026-10-02T04:34:24.606791Z","shell.execute_reply":"2026-10-02T04:34:24.606816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from 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-02T04:34:24.60786Z","iopub.status.idle":"2026-10-02T04:34:24.608227Z","shell.execute_reply.started":"2026-10-02T04:34:24.608035Z","shell.execute_reply":"2026-10-02T04:34:24.608057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import json\nimport math\nimport random\nimport shutil\nimport time\n\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.609018Z","iopub.status.idle":"2026-10-02T04:34:24.609262Z","shell.execute_reply.started":"2026-10-02T04:34:24.609136Z","shell.execute_reply":"2026-10-02T04:34:24.60915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"DATA_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}\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.617758Z","iopub.status.idle":"2026-10-02T04:34:24.618337Z","shell.execute_reply.started":"2026-10-02T04:34:24.618138Z","shell.execute_reply":"2026-10-02T04:34:24.618156Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"CLASS_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}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.619163Z","iopub.status.idle":"2026-10-02T04:34:24.619518Z","shell.execute_reply.started":"2026-10-02T04:34:24.619334Z","shell.execute_reply":"2026-10-02T04:34:24.61935Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMG_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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.621108Z","iopub.status.idle":"2026-10-02T04:34:24.621491Z","shell.execute_reply.started":"2026-10-02T04:34:24.621268Z","shell.execute_reply":"2026-10-02T04:34:24.621302Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.622878Z","iopub.status.idle":"2026-10-02T04:34:24.62331Z","shell.execute_reply.started":"2026-10-02T04:34:24.623103Z","shell.execute_reply":"2026-10-02T04:34:24.623132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TRAIN_DIR = SAMPLE_ROOT if DATA_MODE == 'sample' else FULL_TRAIN_PATH\nprint(f'TRAIN_DIR = {TRAIN_DIR}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.624704Z","iopub.status.idle":"2026-10-02T04:34:24.625055Z","shell.execute_reply.started":"2026-10-02T04:34:24.62493Z","shell.execute_reply":"2026-10-02T04:34:24.624951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1.0 / 255.0,\n    horizontal_flip=True,\n    validation_split=VAL_SPLIT,\n)\n\nval_datagen = ImageDataGenerator(\n    rescale=1.0 / 255.0,          # no augmentation\n    validation_split=VAL_SPLIT,\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.626072Z","iopub.status.idle":"2026-10-02T04:34:24.626423Z","shell.execute_reply.started":"2026-10-02T04:34:24.626231Z","shell.execute_reply":"2026-10-02T04:34:24.626253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.628222Z","iopub.status.idle":"2026-10-02T04:34:24.628771Z","shell.execute_reply.started":"2026-10-02T04:34:24.628429Z","shell.execute_reply":"2026-10-02T04:34:24.628482Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.629717Z","iopub.status.idle":"2026-10-02T04:34:24.630051Z","shell.execute_reply.started":"2026-10-02T04:34:24.629875Z","shell.execute_reply":"2026-10-02T04:34:24.629898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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)}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.631124Z","iopub.status.idle":"2026-10-02T04:34:24.631392Z","shell.execute_reply.started":"2026-10-02T04:34:24.631268Z","shell.execute_reply":"2026-10-02T04:34:24.631286Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"full_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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.632482Z","iopub.status.idle":"2026-10-02T04:34:24.632787Z","shell.execute_reply.started":"2026-10-02T04:34:24.632606Z","shell.execute_reply":"2026-10-02T04:34:24.63262Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(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)}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.633736Z","iopub.status.idle":"2026-10-02T04:34:24.634069Z","shell.execute_reply.started":"2026-10-02T04:34:24.633911Z","shell.execute_reply":"2026-10-02T04:34:24.633933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"assert 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'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.635518Z","iopub.status.idle":"2026-10-02T04:34:24.635733Z","shell.execute_reply.started":"2026-10-02T04:34:24.635631Z","shell.execute_reply":"2026-10-02T04:34:24.635644Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for 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')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.636708Z","iopub.status.idle":"2026-10-02T04:34:24.637019Z","shell.execute_reply.started":"2026-10-02T04:34:24.636905Z","shell.execute_reply":"2026-10-02T04:34:24.63692Z"}},"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-02T04:34:24.638921Z","iopub.status.idle":"2026-10-02T04:34:24.63917Z","shell.execute_reply.started":"2026-10-02T04:34:24.639049Z","shell.execute_reply":"2026-10-02T04:34:24.639066Z"}},"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-02T04:34:24.63996Z","iopub.status.idle":"2026-10-02T04:34:24.640568Z","shell.execute_reply.started":"2026-10-02T04:34:24.640387Z","shell.execute_reply":"2026-10-02T04:34:24.640402Z"}},"outputs":[],"execution_count":null},{"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-02T04:34:24.641989Z","iopub.status.idle":"2026-10-02T04:34:24.642391Z","shell.execute_reply.started":"2026-10-02T04:34:24.642184Z","shell.execute_reply":"2026-10-02T04:34:24.642208Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.643379Z","iopub.status.idle":"2026-10-02T04:34:24.643742Z","shell.execute_reply.started":"2026-10-02T04:34:24.643574Z","shell.execute_reply":"2026-10-02T04:34:24.643597Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.645309Z","iopub.status.idle":"2026-10-02T04:34:24.645659Z","shell.execute_reply.started":"2026-10-02T04:34:24.645486Z","shell.execute_reply":"2026-10-02T04:34:24.645508Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True\n)\n\ntest_it = test_datagen.flow_from_directory(\n    test_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.646837Z","iopub.status.idle":"2026-10-02T04:34:24.64716Z","shell.execute_reply.started":"2026-10-02T04:34:24.647005Z","shell.execute_reply":"2026-10-02T04:34:24.647023Z"}},"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()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.6487Z","iopub.status.idle":"2026-10-02T04:34:24.649134Z","shell.execute_reply.started":"2026-10-02T04:34:24.648982Z","shell.execute_reply":"2026-10-02T04:34:24.649008Z"}},"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-02T04:34:24.65098Z","iopub.status.idle":"2026-10-02T04:34:24.651296Z","shell.execute_reply.started":"2026-10-02T04:34:24.651126Z","shell.execute_reply":"2026-10-02T04:34:24.651145Z"}},"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-02T04:34:24.652516Z","iopub.status.idle":"2026-10-02T04:34:24.652863Z","shell.execute_reply.started":"2026-10-02T04:34:24.652671Z","shell.execute_reply":"2026-10-02T04:34:24.65269Z"}},"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-02T04:34:24.654281Z","iopub.status.idle":"2026-10-02T04:34:24.654603Z","shell.execute_reply.started":"2026-10-02T04:34:24.654466Z","shell.execute_reply":"2026-10-02T04:34:24.654487Z"}},"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\nindices = list(range(len(test_images)))\n\nplot_exmaple(test_images, test_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.655776Z","iopub.status.idle":"2026-10-02T04:34:24.65609Z","shell.execute_reply.started":"2026-10-02T04:34:24.655936Z","shell.execute_reply":"2026-10-02T04:34:24.655955Z"}},"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-02T04:34:24.659773Z","iopub.status.idle":"2026-10-02T04:34:24.660167Z","shell.execute_reply.started":"2026-10-02T04:34:24.660046Z","shell.execute_reply":"2026-10-02T04:34:24.660061Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Hyperparameter => changable\nIMAGE_SIZE = 224\nBATCH_SIE = 64\nEPOCHS = 20\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\nvgg16 = define_model_vgg16()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.661047Z","iopub.status.idle":"2026-10-02T04:34:24.661283Z","shell.execute_reply.started":"2026-10-02T04:34:24.661157Z","shell.execute_reply":"2026-10-02T04:34:24.66117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_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-02T04:34:24.662775Z","iopub.status.idle":"2026-10-02T04:34:24.663072Z","shell.execute_reply.started":"2026-10-02T04:34:24.662942Z","shell.execute_reply":"2026-10-02T04:34:24.662967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_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-02T04:34:24.663658Z","iopub.status.idle":"2026-10-02T04:34:24.663913Z","shell.execute_reply.started":"2026-10-02T04:34:24.663805Z","shell.execute_reply":"2026-10-02T04:34:24.663819Z"}},"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-02T04:34:24.666027Z","iopub.status.idle":"2026-10-02T04:34:24.666468Z","shell.execute_reply.started":"2026-10-02T04:34:24.666259Z","shell.execute_reply":"2026-10-02T04:34:24.666298Z"}},"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-02T04:34:24.667391Z","iopub.status.idle":"2026-10-02T04:34:24.667739Z","shell.execute_reply.started":"2026-10-02T04:34:24.667618Z","shell.execute_reply":"2026-10-02T04:34:24.667633Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.668997Z","iopub.status.idle":"2026-10-02T04:34:24.669252Z","shell.execute_reply.started":"2026-10-02T04:34:24.66913Z","shell.execute_reply":"2026-10-02T04:34:24.669145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"flat1 = Flatten()(model_16_feature_extractor.layers[-1].output)\nprint(flat1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.670404Z","iopub.status.idle":"2026-10-02T04:34:24.670751Z","shell.execute_reply.started":"2026-10-02T04:34:24.670628Z","shell.execute_reply":"2026-10-02T04:34:24.670645Z"}},"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-02T04:34:24.67174Z","iopub.status.idle":"2026-10-02T04:34:24.672069Z","shell.execute_reply.started":"2026-10-02T04:34:24.671943Z","shell.execute_reply":"2026-10-02T04:34:24.671965Z"}},"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-02T04:34:24.673509Z","iopub.status.idle":"2026-10-02T04:34:24.673859Z","shell.execute_reply.started":"2026-10-02T04:34:24.673681Z","shell.execute_reply":"2026-10-02T04:34:24.673705Z"}},"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-02T04:34:24.675314Z","iopub.status.idle":"2026-10-02T04:34:24.675621Z","shell.execute_reply.started":"2026-10-02T04:34:24.675493Z","shell.execute_reply":"2026-10-02T04:34:24.675512Z"}},"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-02T04:34:24.676992Z","iopub.status.idle":"2026-10-02T04:34:24.677243Z","shell.execute_reply.started":"2026-10-02T04:34:24.677131Z","shell.execute_reply":"2026-10-02T04:34:24.677146Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model to be trained\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output2)\n# compile model\nopt = SGD(lr=0.001, momentum=0.9)\n\nmodel_vgg16.compile(optimizer=opt,\n                    loss='binary_crossentropy',\n                    metrics=['accuracy']\n                   )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.678486Z","iopub.status.idle":"2026-10-02T04:34:24.678835Z","shell.execute_reply.started":"2026-10-02T04:34:24.678701Z","shell.execute_reply":"2026-10-02T04:34:24.678719Z"}},"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-02T04:34:24.681316Z","iopub.status.idle":"2026-10-02T04:34:24.681778Z","shell.execute_reply.started":"2026-10-02T04:34:24.681651Z","shell.execute_reply":"2026-10-02T04:34:24.681667Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.682962Z","iopub.status.idle":"2026-10-02T04:34:24.683227Z","shell.execute_reply.started":"2026-10-02T04:34:24.68311Z","shell.execute_reply":"2026-10-02T04:34:24.683131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.684365Z","iopub.status.idle":"2026-10-02T04:34:24.684736Z","shell.execute_reply.started":"2026-10-02T04:34:24.684613Z","shell.execute_reply":"2026-10-02T04:34:24.684635Z"}},"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.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.686348Z","iopub.status.idle":"2026-10-02T04:34:24.686702Z","shell.execute_reply.started":"2026-10-02T04:34:24.686515Z","shell.execute_reply":"2026-10-02T04:34:24.68653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if 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-02T04:34:24.687799Z","iopub.status.idle":"2026-10-02T04:34:24.688171Z","shell.execute_reply.started":"2026-10-02T04:34:24.688018Z","shell.execute_reply":"2026-10-02T04:34:24.68804Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"summarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.689093Z","iopub.status.idle":"2026-10-02T04:34:24.689414Z","shell.execute_reply.started":"2026-10-02T04:34:24.689217Z","shell.execute_reply":"2026-10-02T04:34:24.689231Z"}},"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-02T04:34:24.690585Z","iopub.status.idle":"2026-10-02T04:34:24.690938Z","shell.execute_reply.started":"2026-10-02T04:34:24.69075Z","shell.execute_reply":"2026-10-02T04:34:24.690771Z"}},"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-02T04:34:24.692039Z","iopub.status.idle":"2026-10-02T04:34:24.692385Z","shell.execute_reply.started":"2026-10-02T04:34:24.692208Z","shell.execute_reply":"2026-10-02T04:34:24.692229Z"}},"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-02T04:34:24.693845Z","iopub.status.idle":"2026-10-02T04:34:24.69414Z","shell.execute_reply.started":"2026-10-02T04:34:24.694Z","shell.execute_reply":"2026-10-02T04:34:24.694014Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.696927Z","iopub.status.idle":"2026-10-02T04:34:24.697335Z","shell.execute_reply.started":"2026-10-02T04:34:24.697141Z","shell.execute_reply":"2026-10-02T04:34:24.697158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.698528Z","iopub.status.idle":"2026-10-02T04:34:24.699198Z","shell.execute_reply.started":"2026-10-02T04:34:24.699047Z","shell.execute_reply":"2026-10-02T04:34:24.699067Z"}},"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-02T04:34:24.70076Z","iopub.status.idle":"2026-10-02T04:34:24.701173Z","shell.execute_reply.started":"2026-10-02T04:34:24.700972Z","shell.execute_reply":"2026-10-02T04:34:24.700993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.706807Z","iopub.execute_input":"2026-10-02T04:34:24.707122Z","iopub.status.idle":"2026-10-02T04:34:24.71426Z","shell.execute_reply.started":"2026-10-02T04:34:24.707083Z","shell.execute_reply":"2026-10-02T04:34:24.712723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.715076Z","iopub.status.idle":"2026-10-02T04:34:24.715311Z","shell.execute_reply.started":"2026-10-02T04:34:24.715196Z","shell.execute_reply":"2026-10-02T04:34:24.71521Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        # layer.trainable = True #try to test\n    \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n    # output = Dense(1, activation='sigmoid')(flat1)\n    output = Dense(2, activation='softmax')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.716741Z","iopub.status.idle":"2026-10-02T04:34:24.717092Z","shell.execute_reply.started":"2026-10-02T04:34:24.716957Z","shell.execute_reply":"2026-10-02T04:34:24.716978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.718853Z","iopub.status.idle":"2026-10-02T04:34:24.719591Z","shell.execute_reply.started":"2026-10-02T04:34:24.719343Z","shell.execute_reply":"2026-10-02T04:34:24.719362Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.720774Z","iopub.status.idle":"2026-10-02T04:34:24.721173Z","shell.execute_reply.started":"2026-10-02T04:34:24.720999Z","shell.execute_reply":"2026-10-02T04:34:24.721015Z"}},"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.722607Z","iopub.status.idle":"2026-10-02T04:34:24.723005Z","shell.execute_reply.started":"2026-10-02T04:34:24.722807Z","shell.execute_reply":"2026-10-02T04:34:24.722834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_inceptionv3.reset_states()\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.724373Z","iopub.status.idle":"2026-10-02T04:34:24.725364Z","shell.execute_reply.started":"2026-10-02T04:34:24.725163Z","shell.execute_reply":"2026-10-02T04:34:24.725192Z"}},"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}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.726221Z","iopub.status.idle":"2026-10-02T04:34:24.726585Z","shell.execute_reply.started":"2026-10-02T04:34:24.726378Z","shell.execute_reply":"2026-10-02T04:34:24.726393Z"}},"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.72759Z","iopub.status.idle":"2026-10-02T04:34:24.727869Z","shell.execute_reply.started":"2026-10-02T04:34:24.727701Z","shell.execute_reply":"2026-10-02T04:34:24.727713Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.729157Z","iopub.status.idle":"2026-10-02T04:34:24.729583Z","shell.execute_reply.started":"2026-10-02T04:34:24.729331Z","shell.execute_reply":"2026-10-02T04:34:24.729359Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.73096Z","iopub.status.idle":"2026-10-02T04:34:24.731306Z","shell.execute_reply.started":"2026-10-02T04:34:24.731138Z","shell.execute_reply":"2026-10-02T04:34:24.731158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-10-02T04:34:24.732348Z","iopub.status.idle":"2026-10-02T04:34:24.732723Z","shell.execute_reply.started":"2026-10-02T04:34:24.732601Z","shell.execute_reply":"2026-10-02T04:34:24.732623Z"}},"outputs":[],"execution_count":null}]}