{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2026-09-13T02:55:05.139305Z","iopub.execute_input":"2026-09-13T02:55:05.139605Z","iopub.status.idle":"2026-09-13T02:55:05.465196Z","shell.execute_reply.started":"2026-09-13T02:55:05.139571Z","shell.execute_reply":"2026-09-13T02:55:05.464170Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:55:17.092686Z","iopub.execute_input":"2026-09-13T02:55:17.093335Z","iopub.status.idle":"2026-09-13T02:55:18.069604Z","shell.execute_reply.started":"2026-09-13T02:55:17.093301Z","shell.execute_reply":"2026-09-13T02:55:18.068722Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:55:22.541061Z","iopub.execute_input":"2026-09-13T02:55:22.541381Z","iopub.status.idle":"2026-09-13T02:55:23.500450Z","shell.execute_reply.started":"2026-09-13T02:55:22.541352Z","shell.execute_reply":"2026-09-13T02:55:23.499398Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:55:41.117008Z","iopub.execute_input":"2026-09-13T02:55:41.117389Z","iopub.status.idle":"2026-09-13T02:55:51.307878Z","shell.execute_reply.started":"2026-09-13T02:55:41.117360Z","shell.execute_reply":"2026-09-13T02:55:51.306745Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:55:51.309286Z","iopub.execute_input":"2026-09-13T02:55:51.309558Z","iopub.status.idle":"2026-09-13T02:55:52.279853Z","shell.execute_reply.started":"2026-09-13T02:55:51.309535Z","shell.execute_reply":"2026-09-13T02:55:52.278942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:55:55.293415Z","iopub.execute_input":"2026-09-13T02:55:55.294267Z","iopub.status.idle":"2026-09-13T02:55:56.252905Z","shell.execute_reply.started":"2026-09-13T02:55:55.294231Z","shell.execute_reply":"2026-09-13T02:55:56.251907Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:56:02.000186Z","iopub.execute_input":"2026-09-13T02:56:02.000534Z","iopub.status.idle":"2026-09-13T02:56:03.056563Z","shell.execute_reply.started":"2026-09-13T02:56:02.000507Z","shell.execute_reply":"2026-09-13T02:56:03.055180Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:56:04.995178Z","iopub.execute_input":"2026-09-13T02:56:04.996057Z","iopub.status.idle":"2026-09-13T02:56:06.069977Z","shell.execute_reply.started":"2026-09-13T02:56:04.996007Z","shell.execute_reply":"2026-09-13T02:56:06.069084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:56:23.684050Z","iopub.execute_input":"2026-09-12T13:56:23.684344Z","iopub.status.idle":"2026-09-12T13:56:23.690085Z","shell.execute_reply.started":"2026-09-12T13:56:23.684319Z","shell.execute_reply":"2026-09-12T13:56:23.689409Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:56:14.869517Z","iopub.execute_input":"2026-09-13T02:56:14.869869Z","iopub.status.idle":"2026-09-13T02:56:15.912094Z","shell.execute_reply.started":"2026-09-13T02:56:14.869839Z","shell.execute_reply":"2026-09-13T02:56:15.910806Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:56:15.914205Z","iopub.execute_input":"2026-09-13T02:56:15.914570Z","iopub.status.idle":"2026-09-13T02:56:16.910276Z","shell.execute_reply.started":"2026-09-13T02:56:15.914535Z","shell.execute_reply":"2026-09-13T02:56:16.908813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\n# from matplotlib import pyplot as plt\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:56:32.230521Z","iopub.execute_input":"2026-09-13T02:56:32.231115Z","iopub.status.idle":"2026-09-13T02:56:33.292679Z","shell.execute_reply.started":"2026-09-13T02:56:32.231061Z","shell.execute_reply":"2026-09-13T02:56:33.291689Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:56:40.154820Z","iopub.execute_input":"2026-09-13T02:56:40.155662Z","iopub.status.idle":"2026-09-13T02:56:41.227007Z","shell.execute_reply.started":"2026-09-13T02:56:40.155625Z","shell.execute_reply":"2026-09-13T02:56:41.226076Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:56:47.919085Z","iopub.execute_input":"2026-09-13T02:56:47.919396Z","iopub.status.idle":"2026-09-13T02:56:48.958509Z","shell.execute_reply.started":"2026-09-13T02:56:47.919372Z","shell.execute_reply":"2026-09-13T02:56:48.957437Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow\nprint(tensorflow.__version__)\n\nimport keras\nprint(keras.__version__)\n\nimport tensorflow.keras\nprint(tensorflow.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:57:45.833435Z","iopub.execute_input":"2026-09-13T02:57:45.834497Z","iopub.status.idle":"2026-09-13T02:57:45.839662Z","shell.execute_reply.started":"2026-09-13T02:57:45.834463Z","shell.execute_reply":"2026-09-13T02:57:45.838540Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:57:57.181679Z","iopub.execute_input":"2026-09-13T02:57:57.182410Z","iopub.status.idle":"2026-09-13T02:57:57.187859Z","shell.execute_reply.started":"2026-09-13T02:57:57.182380Z","shell.execute_reply":"2026-09-13T02:57:57.186615Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:58:18.799988Z","iopub.execute_input":"2026-09-13T02:58:18.800515Z","iopub.status.idle":"2026-09-13T02:58:18.805209Z","shell.execute_reply.started":"2026-09-13T02:58:18.800484Z","shell.execute_reply":"2026-09-13T02:58:18.804222Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:58:23.412596Z","iopub.execute_input":"2026-09-13T02:58:23.412888Z","iopub.status.idle":"2026-09-13T02:58:23.419670Z","shell.execute_reply.started":"2026-09-13T02:58:23.412865Z","shell.execute_reply":"2026-09-13T02:58:23.418809Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:58:25.926740Z","iopub.execute_input":"2026-09-13T02:58:25.927841Z","iopub.status.idle":"2026-09-13T02:58:26.908084Z","shell.execute_reply.started":"2026-09-13T02:58:25.927795Z","shell.execute_reply":"2026-09-13T02:58:26.907091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:58:26.910078Z","iopub.execute_input":"2026-09-13T02:58:26.910386Z","iopub.status.idle":"2026-09-13T02:58:27.886969Z","shell.execute_reply.started":"2026-09-13T02:58:26.910360Z","shell.execute_reply":"2026-09-13T02:58:27.885981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test #validation","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:58:27.888368Z","iopub.execute_input":"2026-09-13T02:58:27.888683Z","iopub.status.idle":"2026-09-13T02:58:28.865359Z","shell.execute_reply.started":"2026-09-13T02:58:27.888655Z","shell.execute_reply":"2026-09-13T02:58:28.864440Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:58:32.973648Z","iopub.execute_input":"2026-09-13T02:58:32.973975Z","iopub.status.idle":"2026-09-13T02:58:35.022378Z","shell.execute_reply.started":"2026-09-13T02:58:32.973949Z","shell.execute_reply":"2026-09-13T02:58:35.021547Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:58:38.180906Z","iopub.execute_input":"2026-09-13T02:58:38.181620Z","iopub.status.idle":"2026-09-13T02:58:38.186389Z","shell.execute_reply.started":"2026-09-13T02:58:38.181588Z","shell.execute_reply":"2026-09-13T02:58:38.185389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:58:42.053758Z","iopub.execute_input":"2026-09-13T02:58:42.054634Z","iopub.status.idle":"2026-09-13T02:58:44.173418Z","shell.execute_reply.started":"2026-09-13T02:58:42.054601Z","shell.execute_reply":"2026-09-13T02:58:44.172396Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:58:44.175387Z","iopub.execute_input":"2026-09-13T02:58:44.175691Z","iopub.status.idle":"2026-09-13T02:58:46.168405Z","shell.execute_reply.started":"2026-09-13T02:58:44.175664Z","shell.execute_reply":"2026-09-13T02:58:46.167457Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:59:01.628880Z","iopub.execute_input":"2026-09-13T02:59:01.629789Z","iopub.status.idle":"2026-09-13T02:59:11.580486Z","shell.execute_reply.started":"2026-09-13T02:59:01.629751Z","shell.execute_reply":"2026-09-13T02:59:11.579125Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-13T02:59:14.925093Z","iopub.execute_input":"2026-09-13T02:59:14.926032Z","iopub.status.idle":"2026-09-13T02:59:14.940781Z","shell.execute_reply.started":"2026-09-13T02:59:14.925985Z","shell.execute_reply":"2026-09-13T02:59:14.939858Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:08.529300Z","iopub.execute_input":"2026-09-12T13:57:08.529605Z","iopub.status.idle":"2026-09-12T13:57:08.533803Z","shell.execute_reply.started":"2026-09-12T13:57:08.529582Z","shell.execute_reply":"2026-09-12T13:57:08.532719Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:59:29.287559Z","iopub.execute_input":"2026-09-13T02:59:29.288205Z","iopub.status.idle":"2026-09-13T02:59:29.293070Z","shell.execute_reply.started":"2026-09-13T02:59:29.288173Z","shell.execute_reply":"2026-09-13T02:59:29.292145Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu',\n                     kernel_initializer='he_uniform',\n                     padding='same',\n                     input_shape=(200, 200, 3))\n             )\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T02:59:40.378552Z","iopub.execute_input":"2026-09-13T02:59:40.379440Z","iopub.status.idle":"2026-09-13T02:59:40.385676Z","shell.execute_reply.started":"2026-09-13T02:59:40.379407Z","shell.execute_reply":"2026-09-13T02:59:40.384659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:01:20.415149Z","iopub.execute_input":"2026-09-13T03:01:20.415480Z","iopub.status.idle":"2026-09-13T03:01:20.478799Z","shell.execute_reply.started":"2026-09-13T03:01:20.415456Z","shell.execute_reply":"2026-09-13T03:01:20.478075Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    pyplot.show()\n    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png') \n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:04:44.527560Z","iopub.execute_input":"2026-09-13T03:04:44.528684Z","iopub.status.idle":"2026-09-13T03:04:44.535192Z","shell.execute_reply.started":"2026-09-13T03:04:44.528643Z","shell.execute_reply":"2026-09-13T03:04:44.534339Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,\n                 (3, 3),\n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(2, activation='softmax'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:05:27.931994Z","iopub.execute_input":"2026-09-13T03:05:27.932993Z","iopub.status.idle":"2026-09-13T03:05:27.996422Z","shell.execute_reply.started":"2026-09-13T03:05:27.932957Z","shell.execute_reply":"2026-09-13T03:05:27.995604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:09:17.031366Z","iopub.execute_input":"2026-09-13T03:09:17.032131Z","iopub.status.idle":"2026-09-13T03:09:17.109682Z","shell.execute_reply.started":"2026-09-13T03:09:17.032088Z","shell.execute_reply":"2026-09-13T03:09:17.107498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API - new cell\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx1 = Conv2D(64, (3, 3), activation='relu')(x1)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:11:49.946890Z","iopub.execute_input":"2026-09-13T03:11:49.947970Z","iopub.status.idle":"2026-09-13T03:11:50.036228Z","shell.execute_reply.started":"2026-09-13T03:11:49.947933Z","shell.execute_reply":"2026-09-13T03:11:50.035428Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\ntype(datagen)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:14:22.698684Z","iopub.execute_input":"2026-09-13T03:14:22.699627Z","iopub.status.idle":"2026-09-13T03:14:22.705494Z","shell.execute_reply.started":"2026-09-13T03:14:22.699594Z","shell.execute_reply":"2026-09-13T03:14:22.704528Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:14:24.705562Z","iopub.execute_input":"2026-09-13T03:14:24.706502Z","iopub.status.idle":"2026-09-13T03:14:25.687874Z","shell.execute_reply.started":"2026-09-13T03:14:24.706468Z","shell.execute_reply":"2026-09-13T03:14:25.686894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = 224 #for vgg16\nBATCH_SIZE = 64\nEPOCHS = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:14:48.553052Z","iopub.execute_input":"2026-09-13T03:14:48.554043Z","iopub.status.idle":"2026-09-13T03:14:48.558341Z","shell.execute_reply.started":"2026-09-13T03:14:48.553980Z","shell.execute_reply":"2026-09-13T03:14:48.557418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True,\n    validation_split=0.2  # Defined here at initialization\n)\n\ntrain_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\n# 2. Extract the training subset (80% of data)\ntrain_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='training',     # Explicitly request the training partition\n    shuffle=True           # Stochastic sampling is standard for training\n)\n\n# 3. Extract the validation subset (20% of data)\nval_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='validation',   # Explicitly request the validation partition\n    shuffle=False          # Disable shuffle to maintain index alignment for metrics\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:17:05.360873Z","iopub.execute_input":"2026-09-13T03:17:05.361668Z","iopub.status.idle":"2026-09-13T03:17:19.312536Z","shell.execute_reply.started":"2026-09-13T03:17:05.361634Z","shell.execute_reply":"2026-09-13T03:17:19.311502Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_it), len(train_it.classes), train_it.classes[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:17:43.550147Z","iopub.execute_input":"2026-09-13T03:17:43.550829Z","iopub.status.idle":"2026-09-13T03:17:43.557855Z","shell.execute_reply.started":"2026-09-13T03:17:43.550795Z","shell.execute_reply":"2026-09-13T03:17:43.556835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(val_it), len(val_it.classes), val_it.classes[-10:]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:17:43.714699Z","iopub.execute_input":"2026-09-13T03:17:43.715517Z","iopub.status.idle":"2026-09-13T03:17:43.722475Z","shell.execute_reply.started":"2026-09-13T03:17:43.715484Z","shell.execute_reply":"2026-09-13T03:17:43.721419Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\n# model_1.reset_states()\n# history_1 = model_1.fit(\n#     train_it,\n#     steps_per_epoch=len(train_it),\n#     validation_data=val_it,\n#     validation_steps=len(val_it),\n#     epochs=EPOCHS,\n#     verbose=2,\n#     callbacks = [PlotLossesKeras()]\n#     )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.394350Z","iopub.status.idle":"2026-09-12T13:57:12.394628Z","shell.execute_reply.started":"2026-09-12T13:57:12.394490Z","shell.execute_reply":"2026-09-12T13:57:12.394505Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.396236Z","iopub.status.idle":"2026-09-12T13:57:12.396611Z","shell.execute_reply.started":"2026-09-12T13:57:12.396387Z","shell.execute_reply":"2026-09-12T13:57:12.396436Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n# _, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\n# print('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.398130Z","iopub.status.idle":"2026-09-12T13:57:12.398412Z","shell.execute_reply.started":"2026-09-12T13:57:12.398277Z","shell.execute_reply":"2026-09-12T13:57:12.398291Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Create test datagenerator from 308-456 Dogs vs Cats ","metadata":{}},{"cell_type":"code","source":"ls /kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:18:37.743338Z","iopub.execute_input":"2026-09-13T03:18:37.744227Z","iopub.status.idle":"2026-09-13T03:18:38.772806Z","shell.execute_reply.started":"2026-09-13T03:18:37.744193Z","shell.execute_reply":"2026-09-13T03:18:38.771810Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\ntest_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test'\n\nprint(test_path)\n# # List all .jpg files in the directory (adjust the pattern if needed)\n# image_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# # Check if images were found\n# if not image_files:\n#     print(\"No images found. Please verify the directory and file extensions.\")\n    \n# # Create a DataFrame with the file paths\n# test_df = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:18:53.038860Z","iopub.execute_input":"2026-09-13T03:18:53.039458Z","iopub.status.idle":"2026-09-13T03:18:53.046287Z","shell.execute_reply.started":"2026-09-13T03:18:53.039418Z","shell.execute_reply":"2026-09-13T03:18:53.045161Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.402795Z","iopub.status.idle":"2026-09-12T13:57:12.403106Z","shell.execute_reply.started":"2026-09-12T13:57:12.402977Z","shell.execute_reply":"2026-09-12T13:57:12.402990Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# image_files[:5], type(image_files), len(image_files)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.405239Z","iopub.status.idle":"2026-09-12T13:57:12.405523Z","shell.execute_reply.started":"2026-09-12T13:57:12.405388Z","shell.execute_reply":"2026-09-12T13:57:12.405402Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.406334Z","iopub.status.idle":"2026-09-12T13:57:12.406639Z","shell.execute_reply.started":"2026-09-12T13:57:12.406502Z","shell.execute_reply":"2026-09-12T13:57:12.406516Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.408600Z","iopub.status.idle":"2026-09-12T13:57:12.408982Z","shell.execute_reply.started":"2026-09-12T13:57:12.408783Z","shell.execute_reply":"2026-09-12T13:57:12.408799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.410365Z","iopub.status.idle":"2026-09-12T13:57:12.410772Z","shell.execute_reply.started":"2026-09-12T13:57:12.410565Z","shell.execute_reply":"2026-09-12T13:57:12.410585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Create test data generator\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# # Initialize your ImageDataGenerator (modify parameters as needed)\n# datagen_test = ImageDataGenerator(rescale=1./255,\n#                                  vertical_flip=True)\n\n# # Create the data generator using the DataFrame\n# test_it = datagen_test.flow_from_dataframe(\n#     dataframe=test_df,\n#     x_col='filename',\n#     y_col=None,            # No labels for testing, so set to None\n#     target_size=IMAGE_SIZE,\n#     batch_size=BATCH_SIZE,\n#     class_mode=None,       # Since there are no labels\n#     # shuffle=True,         # Usually testing data should not be shuffled\n#     shuffle=False,\n# )\n\n# type(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.412045Z","iopub.status.idle":"2026-09-12T13:57:12.412473Z","shell.execute_reply.started":"2026-09-12T13:57:12.412241Z","shell.execute_reply":"2026-09-12T13:57:12.412270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:20:26.206176Z","iopub.execute_input":"2026-09-13T03:20:26.207243Z","iopub.status.idle":"2026-09-13T03:20:26.213388Z","shell.execute_reply.started":"2026-09-13T03:20:26.207187Z","shell.execute_reply":"2026-09-13T03:20:26.212387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True\n)\n\ntest_it = test_datagen.flow_from_directory(\n    test_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:20:28.925158Z","iopub.execute_input":"2026-09-13T03:20:28.925873Z","iopub.status.idle":"2026-09-13T03:20:40.100294Z","shell.execute_reply.started":"2026-09-13T03:20:28.925842Z","shell.execute_reply":"2026-09-13T03:20:40.099584Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_exmaple(images, labels):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))  # Fixed: set_title instead of title\n            # ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n            ax.axis(\"on\")\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:21:18.085683Z","iopub.execute_input":"2026-09-13T03:21:18.086192Z","iopub.status.idle":"2026-09-13T03:21:18.092307Z","shell.execute_reply.started":"2026-09-13T03:21:18.086162Z","shell.execute_reply":"2026-09-13T03:21:18.091293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\nprint(train_images.shape, len(train_labels))\nplot_exmaple(train_images, train_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:21:21.420581Z","iopub.execute_input":"2026-09-13T03:21:21.421349Z","iopub.status.idle":"2026-09-13T03:21:30.459452Z","shell.execute_reply.started":"2026-09-13T03:21:21.421313Z","shell.execute_reply":"2026-09-13T03:21:30.458278Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:21:30.461782Z","iopub.execute_input":"2026-09-13T03:21:30.462266Z","iopub.status.idle":"2026-09-13T03:21:39.211030Z","shell.execute_reply.started":"2026-09-13T03:21:30.462223Z","shell.execute_reply":"2026-09-13T03:21:39.209536Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images, indices):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(indices[i]))  # ตั้งค่า title ด้วย index จาก list/array indices\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.422659Z","iopub.status.idle":"2026-09-12T13:57:12.423035Z","shell.execute_reply.started":"2026-09-12T13:57:12.422877Z","shell.execute_reply":"2026-09-12T13:57:12.422893Z"},"jupyter":{"source_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images, test_labels = test_it.__next__()  # หรือ next(test_it)\nprint(f\"{test_images.shape=}, {test_labels.shape}\")\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple(test_images, test_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:22:56.607684Z","iopub.execute_input":"2026-09-13T03:22:56.608565Z","iopub.status.idle":"2026-09-13T03:23:05.435405Z","shell.execute_reply.started":"2026-09-13T03:22:56.608528Z","shell.execute_reply":"2026-09-13T03:23:05.432936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import numpy as np\n\n\n# # 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\n# sample_indices = np.random.choice(len(test_images), size=10, replace=False)\n# sample_images = test_images[sample_indices]\n\n# # 2. Predict \n# predictions = model_1.predict(sample_images)\n# predicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# # 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\n# fig, axes = plt.subplots(2, 5, figsize=(15, 6))\n# axes = axes.flatten()\n\n# for i, ax in enumerate(axes):\n#     ax.imshow(sample_images[i])\n#     # แสดง Index เดิม และ Class ที่ทายได้\n#     ax.set_title(f\"Idx: {sample_indices[i]}\\nPred: {predicted_classes[i]}\")\n#     ax.axis(\"off\")\n\n# plt.tight_layout()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.429269Z","iopub.status.idle":"2026-09-12T13:57:12.429599Z","shell.execute_reply.started":"2026-09-12T13:57:12.429448Z","shell.execute_reply":"2026-09-12T13:57:12.429462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:12.430613Z","iopub.status.idle":"2026-09-12T13:57:12.430981Z","shell.execute_reply.started":"2026-09-12T13:57:12.430785Z","shell.execute_reply":"2026-09-12T13:57:12.430799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2026-09-13\n# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:07:33.624129Z","iopub.execute_input":"2026-09-12T14:07:33.625179Z","iopub.status.idle":"2026-09-12T14:07:33.628731Z","shell.execute_reply.started":"2026-09-12T14:07:33.625146Z","shell.execute_reply":"2026-09-12T14:07:33.627721Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it), id(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:24:01.419059Z","iopub.execute_input":"2026-09-13T03:24:01.419932Z","iopub.status.idle":"2026-09-13T03:24:01.425384Z","shell.execute_reply.started":"2026-09-13T03:24:01.419902Z","shell.execute_reply":"2026-09-13T03:24:01.424509Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Hyperparameter => changable\nIMAGE_SIZE = 224\nBATCH_SIE = 64\nEPOCHS = 20\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\nvgg16 = define_model_vgg16()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:25:16.961370Z","iopub.execute_input":"2026-09-13T03:25:16.961855Z","iopub.status.idle":"2026-09-13T03:25:19.486551Z","shell.execute_reply.started":"2026-09-13T03:25:16.961811Z","shell.execute_reply":"2026-09-13T03:25:19.485775Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_vgg16_top = VGG16(include_top=True,\n                        input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)\n                       )\nmodel_vgg16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:25:51.397891Z","iopub.execute_input":"2026-09-13T03:25:51.398694Z","iopub.status.idle":"2026-09-13T03:26:09.344888Z","shell.execute_reply.started":"2026-09-13T03:25:51.398658Z","shell.execute_reply":"2026-09-13T03:26:09.343749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_16_feature_extractor = VGG16(include_top=False,\n                                   input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)\n                                  )\nmodel_16_feature_extractor.summary() #feature extractor as a backbone","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:28:36.418515Z","iopub.execute_input":"2026-09-13T03:28:36.419313Z","iopub.status.idle":"2026-09-13T03:28:36.757632Z","shell.execute_reply.started":"2026-09-13T03:28:36.419280Z","shell.execute_reply":"2026-09-13T03:28:36.755635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n\t\tprint(index, layer.trainable, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:29:50.011332Z","iopub.execute_input":"2026-09-13T03:29:50.012291Z","iopub.status.idle":"2026-09-13T03:29:50.017444Z","shell.execute_reply.started":"2026-09-13T03:29:50.012254Z","shell.execute_reply":"2026-09-13T03:29:50.016535Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n    if index <= 15:\n        layer.trainable = False\n\nfor index, layer in enumerate(model_16_feature_extractor.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:30:50.239709Z","iopub.execute_input":"2026-09-13T03:30:50.242157Z","iopub.status.idle":"2026-09-13T03:30:50.247855Z","shell.execute_reply.started":"2026-09-13T03:30:50.242124Z","shell.execute_reply":"2026-09-13T03:30:50.246821Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:31:43.011497Z","iopub.execute_input":"2026-09-13T03:31:43.012487Z","iopub.status.idle":"2026-09-13T03:31:43.018685Z","shell.execute_reply.started":"2026-09-13T03:31:43.012439Z","shell.execute_reply":"2026-09-13T03:31:43.017807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use functional API\nflat1 = Flatten()(model_16_feature_extractor.layers[-1].output)\nprint(flat1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:32:35.125926Z","iopub.execute_input":"2026-09-13T03:32:35.126741Z","iopub.status.idle":"2026-09-13T03:32:35.136513Z","shell.execute_reply.started":"2026-09-13T03:32:35.126706Z","shell.execute_reply":"2026-09-13T03:32:35.135729Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\nprint(class1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:32:57.935567Z","iopub.execute_input":"2026-09-13T03:32:57.936449Z","iopub.status.idle":"2026-09-13T03:32:57.953432Z","shell.execute_reply.started":"2026-09-13T03:32:57.936416Z","shell.execute_reply":"2026-09-13T03:32:57.952610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output = Dense(1, activation='sigmoid')(class1)\nprint(output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:33:06.721901Z","iopub.execute_input":"2026-09-13T03:33:06.722869Z","iopub.status.idle":"2026-09-13T03:33:06.738903Z","shell.execute_reply.started":"2026-09-13T03:33:06.722822Z","shell.execute_reply":"2026-09-13T03:33:06.737928Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model to be trained\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.001, momentum=0.9)\n\nmodel_vgg16.compile(optimizer=opt,\n                    loss='binary_crossentropy',\n                    metrics=['accuracy']\n                   )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:34:00.417694Z","iopub.execute_input":"2026-09-13T03:34:00.418557Z","iopub.status.idle":"2026-09-13T03:34:00.433063Z","shell.execute_reply.started":"2026-09-13T03:34:00.418524Z","shell.execute_reply":"2026-09-13T03:34:00.432269Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:34:17.696483Z","iopub.execute_input":"2026-09-13T03:34:17.697252Z","iopub.status.idle":"2026-09-13T03:34:17.745191Z","shell.execute_reply.started":"2026-09-13T03:34:17.697220Z","shell.execute_reply":"2026-09-13T03:34:17.744283Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:34:48.169981Z","iopub.execute_input":"2026-09-13T03:34:48.170697Z","iopub.status.idle":"2026-09-13T03:34:48.176069Z","shell.execute_reply.started":"2026-09-13T03:34:48.170665Z","shell.execute_reply":"2026-09-13T03:34:48.175347Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model_vgg16 = define_model_vgg16()\n# print(model_vgg16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:07:39.669866Z","iopub.execute_input":"2026-09-12T14:07:39.670242Z","iopub.status.idle":"2026-09-12T14:07:40.059920Z","shell.execute_reply.started":"2026-09-12T14:07:39.670206Z","shell.execute_reply":"2026-09-12T14:07:40.058893Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nimport tensorflow as tf\n\n# 1. Verify that TensorFlow can communicate with the GPU hardware\nphysical_devices = tf.config.list_physical_devices('GPU')\nprint(f\"Hardware status: {len(physical_devices)} GPU(s) detected.\")\n\nif len(physical_devices) > 0:\n    # Optional but highly recommended: Prevent TF from pre-allocating 100% of VRAM\n    try:\n        tf.config.experimental.set_memory_growth(physical_devices[0], True)\n    except Exception as e:\n        print(f\"Memory growth configuration failed: {e}\")\n\n    # 2. Explicitly bind the execution to the primary GPU\n    with tf.device('/GPU:0'):\n        \n        print(f\"Model ID: {id(model_vgg16)}\")\n        \n        # Note: reset_states() is strictly for stateful RNNs (LSTMs/GRUs). \n        # For a feed-forward CNN like VGG16, this method has no effect and can be removed.\n        model_vgg16.reset_states() \n        \n        model_vgg16_history = model_vgg16.fit(\n            train_it, \n            steps_per_epoch=len(train_it),\n            validation_data=val_it,\n            validation_steps=len(val_it),\n            epochs=1, \n            verbose=1,\n            callbacks=[PlotLossesKeras()]\n        )\nelse:\n    print(\"WARNING: No GPU detected. Execution will proceed on the CPU, which will be significantly slower.\")\n    # Fallback to standard execution\n    model_vgg16_history = model_vgg16.fit(\n        train_it, \n        steps_per_epoch=len(train_it),\n        validation_data=val_it,\n        validation_steps=len(val_it),\n        epochs=1, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:35:52.491793Z","iopub.execute_input":"2026-09-13T03:35:52.492520Z","iopub.status.idle":"2026-09-13T03:38:07.348952Z","shell.execute_reply.started":"2026-09-13T03:35:52.492485Z","shell.execute_reply":"2026-09-13T03:38:07.348265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:38:58.355777Z","iopub.execute_input":"2026-09-13T03:38:58.356573Z","iopub.status.idle":"2026-09-13T03:38:58.692391Z","shell.execute_reply.started":"2026-09-13T03:38:58.356538Z","shell.execute_reply":"2026-09-13T03:38:58.691647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_vgg16.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:39:14.691673Z","iopub.execute_input":"2026-09-13T03:39:14.691974Z","iopub.status.idle":"2026-09-13T03:39:30.299273Z","shell.execute_reply.started":"2026-09-13T03:39:14.691951Z","shell.execute_reply":"2026-09-13T03:39:30.298402Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model for the test set\n_, test_acc = model_vgg16.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (test_acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:39:38.603215Z","iopub.execute_input":"2026-09-13T03:39:38.603912Z","iopub.status.idle":"2026-09-13T03:40:18.946374Z","shell.execute_reply.started":"2026-09-13T03:39:38.603879Z","shell.execute_reply":"2026-09-13T03:40:18.945520Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. Reset the generator state to ensure alignment from index 0\ntest_it.reset()\n\n# 2. Extract the ordered ground truth labels from the generator\ny_true = test_it.classes\nprint(y_true.shape)\n\n# 3. Execute the forward pass over the entire test dataset\n# Calculate exact steps to prevent infinite looping or partial evaluation\nsteps = np.ceil(test_it.samples / test_it.batch_size)\nprobabilities = model_vgg16.predict(test_it, steps=steps, verbose=1).squeeze()\nprint(probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:44:02.504388Z","iopub.execute_input":"2026-09-13T03:44:02.505196Z","iopub.status.idle":"2026-09-13T03:44:28.390203Z","shell.execute_reply.started":"2026-09-13T03:44:02.505162Z","shell.execute_reply":"2026-09-13T03:44:28.389255Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:44:35.319010Z","iopub.execute_input":"2026-09-13T03:44:35.319782Z","iopub.status.idle":"2026-09-13T03:44:35.325724Z","shell.execute_reply.started":"2026-09-13T03:44:35.319752Z","shell.execute_reply":"2026-09-13T03:44:35.324792Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:45:27.820606Z","iopub.execute_input":"2026-09-13T03:45:27.821760Z","iopub.status.idle":"2026-09-13T03:45:27.827947Z","shell.execute_reply.started":"2026-09-13T03:45:27.821713Z","shell.execute_reply":"2026-09-13T03:45:27.826942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 4. Discretize continuous logistic probabilities into binary class predictions\ny_pred = (probabilities > 0.5).astype(int)\nprint(y_pred.shape)\n\n# 5. Extract dynamic class labels mapping (e.g., {'cats': 0, 'dogs': 1})\n# This ensures the report correctly maps index 0 and 1 to your string labels\ntarget_names = list(test_it.class_indices.keys())\n\n# 6. Compute and output the classification report\nreport = classification_report(y_true, y_pred, target_names=target_names)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:45:41.526287Z","iopub.execute_input":"2026-09-13T03:45:41.526971Z","iopub.status.idle":"2026-09-13T03:45:41.546681Z","shell.execute_reply.started":"2026-09-13T03:45:41.526940Z","shell.execute_reply":"2026-09-13T03:45:41.545724Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:42:52.769698Z","iopub.execute_input":"2026-09-13T03:42:52.770012Z","iopub.status.idle":"2026-09-13T03:42:52.776719Z","shell.execute_reply.started":"2026-09-13T03:42:52.769987Z","shell.execute_reply":"2026-09-13T03:42:52.775668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. Aggregate sufficient samples from the iterator\nimages_list = []\nlabels_list = []\n\n# Fetch 2 batches (2 * 64 = 128 samples) to ensure we have pool > 100\nfor _ in range(2):\n    batch_images, batch_labels = next(test_it)\n    images_list.append(batch_images)\n    labels_list.append(batch_labels)\n\n# Concatenate into a single tensor\nall_images = np.concatenate(images_list, axis=0)\nall_labels = np.concatenate(labels_list, axis=0)\n\n# 2. Stochastically sample 100 unique indices\nnp.random.seed(42) # For reproducibility\nrandom_indices = np.random.choice(all_images.shape[0], size=100, replace=False)\n\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\n\n# 3. Execute the forward pass\n# Squeeze is used to convert shape (100, 1) to (100,)\nprobabilities = model_vgg16.predict(sample_images).squeeze()\n\n# 4. Thresholding (Assuming standard mapping: 0 = Cat, 1 = Dog)\npredictions = (probabilities > 0.5).astype(int)\nclass_mapping = {0: 'Cat', 1: 'Dog'}\n\nprint(\"Done.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:46:47.481779Z","iopub.execute_input":"2026-09-13T03:46:47.482394Z","iopub.status.idle":"2026-09-13T03:46:54.470790Z","shell.execute_reply.started":"2026-09-13T03:46:47.482360Z","shell.execute_reply":"2026-09-13T03:46:54.469762Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-13T03:47:07.812207Z","iopub.execute_input":"2026-09-13T03:47:07.812531Z","iopub.status.idle":"2026-09-13T03:47:15.796127Z","shell.execute_reply.started":"2026-09-13T03:47:07.812507Z","shell.execute_reply":"2026-09-13T03:47:15.794514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:21.980765Z","iopub.status.idle":"2026-09-12T14:09:21.981271Z","shell.execute_reply.started":"2026-09-12T14:09:21.981026Z","shell.execute_reply":"2026-09-12T14:09:21.981050Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# InceptionV3","metadata":{}},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        # layer.trainable = True #try to test\n    \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n    # output = Dense(1, activation='sigmoid')(flat1)\n    output = Dense(2, activation='softmax')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:21.983104Z","iopub.status.idle":"2026-09-12T14:09:21.983610Z","shell.execute_reply.started":"2026-09-12T14:09:21.983353Z","shell.execute_reply":"2026-09-12T14:09:21.983376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-09-12T14:09:21.985238Z","iopub.status.idle":"2026-09-12T14:09:21.985696Z","shell.execute_reply.started":"2026-09-12T14:09:21.985453Z","shell.execute_reply":"2026-09-12T14:09:21.985475Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:21.987706Z","iopub.status.idle":"2026-09-12T14:09:21.988054Z","shell.execute_reply.started":"2026-09-12T14:09:21.987905Z","shell.execute_reply":"2026-09-12T14:09:21.987921Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nfor w in model_inceptionv3.trainable_weights:\n    print(w.name, K.count_params(w))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:21.989062Z","iopub.status.idle":"2026-09-12T14:09:21.989335Z","shell.execute_reply.started":"2026-09-12T14:09:21.989208Z","shell.execute_reply":"2026-09-12T14:09:21.989220Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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-09-12T14:09:21.990524Z","iopub.status.idle":"2026-09-12T14:09:21.990799Z","shell.execute_reply.started":"2026-09-12T14:09:21.990665Z","shell.execute_reply":"2026-09-12T14:09:21.990678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:21.991799Z","iopub.status.idle":"2026-09-12T14:09:21.992181Z","shell.execute_reply.started":"2026-09-12T14:09:21.992037Z","shell.execute_reply":"2026-09-12T14:09:21.992052Z"}},"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-09-12T14:09:21.993271Z","iopub.status.idle":"2026-09-12T14:09:21.993619Z","shell.execute_reply.started":"2026-09-12T14:09:21.993474Z","shell.execute_reply":"2026-09-12T14:09:21.993489Z"}},"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-09-12T14:09:21.995318Z","iopub.status.idle":"2026-09-12T14:09:21.995645Z","shell.execute_reply.started":"2026-09-12T14:09:21.995499Z","shell.execute_reply":"2026-09-12T14:09:21.995514Z"}},"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-09-12T14:09:21.996782Z","iopub.status.idle":"2026-09-12T14:09:21.997163Z","shell.execute_reply.started":"2026-09-12T14:09:21.997018Z","shell.execute_reply":"2026-09-12T14:09:21.997034Z"}},"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-09-12T14:09:21.998391Z","iopub.status.idle":"2026-09-12T14:09:21.998666Z","shell.execute_reply.started":"2026-09-12T14:09:21.998542Z","shell.execute_reply":"2026-09-12T14:09:21.998555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:22.000259Z","iopub.status.idle":"2026-09-12T14:09:22.000624Z","shell.execute_reply.started":"2026-09-12T14:09:22.000460Z","shell.execute_reply":"2026-09-12T14:09:22.000476Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5 first img: 1, 0, 1, 1, 0\nimages_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:09:22.002462Z","iopub.status.idle":"2026-09-12T14:09:22.002786Z","shell.execute_reply.started":"2026-09-12T14:09:22.002641Z","shell.execute_reply":"2026-09-12T14:09:22.002656Z"}},"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-09-12T14:09:22.004949Z","iopub.status.idle":"2026-09-12T14:09:22.005276Z","shell.execute_reply.started":"2026-09-12T14:09:22.005130Z","shell.execute_reply":"2026-09-12T14:09:22.005145Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}