{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":3362,"databundleVersionId":31148}],"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\nimport os\nfor 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-02-20T02:56:14.610781Z","iopub.execute_input":"2026-02-20T02:56:14.611629Z","iopub.status.idle":"2026-02-20T02:56:14.923230Z","shell.execute_reply.started":"2026-02-20T02:56:14.611589Z","shell.execute_reply":"2026-02-20T02:56:14.922347Z"},"trusted":true},"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-02-20T02:56:14.924817Z","iopub.execute_input":"2026-02-20T02:56:14.925181Z","iopub.status.idle":"2026-02-20T02:56:24.892588Z","shell.execute_reply.started":"2026-02-20T02:56:14.925158Z","shell.execute_reply":"2026-02-20T02:56:24.891681Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" #  Dogs vs. Cats Dataset Preparation\n","metadata":{}},{"cell_type":"markdown","source":"## Plot Dog and Cat Photos","metadata":{"execution":{"iopub.status.busy":"2024-01-08T06:57:18.293035Z","iopub.execute_input":"2024-01-08T06:57:18.293457Z","iopub.status.idle":"2024-01-08T06:57:19.311078Z","shell.execute_reply.started":"2024-01-08T06:57:18.293422Z","shell.execute_reply":"2024-01-08T06:57:19.309969Z"}}},{"cell_type":"code","source":"# plot dog 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 + '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-02-20T02:56:24.893695Z","iopub.execute_input":"2026-02-20T02:56:24.893989Z","iopub.status.idle":"2026-02-20T02:56:25.985835Z","shell.execute_reply.started":"2026-02-20T02:56:24.893966Z","shell.execute_reply":"2026-02-20T02:56:25.985089Z"},"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-02-20T02:56:25.986983Z","iopub.execute_input":"2026-02-20T02:56:25.987343Z","iopub.status.idle":"2026-02-20T02:56:26.807259Z","shell.execute_reply.started":"2026-02-20T02:56:25.987311Z","shell.execute_reply":"2026-02-20T02:56:26.806515Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Select Standardized Photo Size","metadata":{}},{"cell_type":"markdown","source":"## Pre-Process Photo Sizes (Optional)","metadata":{}},{"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\n# 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":"2026-02-20T02:56:26.810549Z","iopub.execute_input":"2026-02-20T02:56:26.811194Z","iopub.status.idle":"2026-02-20T02:57:56.023601Z","shell.execute_reply.started":"2026-02-20T02:56:26.811168Z","shell.execute_reply":"2026-02-20T02:57:56.022413Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')\nprint(photos.shape, labels.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:00:03.872212Z","iopub.execute_input":"2026-02-20T03:00:03.872824Z","iopub.status.idle":"2026-02-20T03:00:18.777971Z","shell.execute_reply.started":"2026-02-20T03:00:03.872793Z","shell.execute_reply":"2026-02-20T03:00:18.777125Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Pre-Process Photos into Standard Directories","metadata":{}},{"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-02-20T03:00:47.231986Z","iopub.execute_input":"2026-02-20T03:00:47.232343Z","iopub.status.idle":"2026-02-20T03:00:47.236745Z","shell.execute_reply.started":"2026-02-20T03:00:47.232314Z","shell.execute_reply":"2026-02-20T03:00:47.235765Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:00:49.192246Z","iopub.execute_input":"2026-02-20T03:00:49.192600Z","iopub.status.idle":"2026-02-20T03:00:49.197583Z","shell.execute_reply.started":"2026-02-20T03:00:49.192570Z","shell.execute_reply":"2026-02-20T03:00:49.196963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\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-02-20T03:37:47.692988Z","iopub.execute_input":"2026-02-20T03:37:47.693662Z","iopub.status.idle":"2026-02-20T03:37:51.031114Z","shell.execute_reply.started":"2026-02-20T03:37:47.693634Z","shell.execute_reply":"2026-02-20T03:37:51.030314Z"}},"outputs":[],"execution_count":null},{"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\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\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-02-20T03:37:55.191539Z","iopub.execute_input":"2026-02-20T03:37:55.192122Z","iopub.status.idle":"2026-02-20T03:37:57.984081Z","shell.execute_reply.started":"2026-02-20T03:37:55.192092Z","shell.execute_reply":"2026-02-20T03:37:57.983274Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nmodel = Sequential()\n# block 1\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\n# block 2\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\n# block 3\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:38:07.561466Z","iopub.execute_input":"2026-02-20T03:38:07.562122Z","iopub.status.idle":"2026-02-20T03:38:07.608769Z","shell.execute_reply.started":"2026-02-20T03:38:07.562088Z","shell.execute_reply":"2026-02-20T03:38:07.608089Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(learning_rate=0.001, momentum=0.9)\nmodel.compile(\n                optimizer=opt, \n                loss='binary_crossentropy', \n                metrics=['accuracy']\n            )\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:38:09.800693Z","iopub.execute_input":"2026-02-20T03:38:09.801054Z","iopub.status.idle":"2026-02-20T03:38:09.851818Z","shell.execute_reply.started":"2026-02-20T03:38:09.801022Z","shell.execute_reply":"2026-02-20T03:38:09.850936Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:38:18.632014Z","iopub.execute_input":"2026-02-20T03:38:18.632289Z","iopub.status.idle":"2026-02-20T03:38:18.636293Z","shell.execute_reply.started":"2026-02-20T03:38:18.632257Z","shell.execute_reply":"2026-02-20T03:38:18.635411Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n           class_mode='binary', \n           batch_size=64, \n           target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:38:14.456500Z","iopub.execute_input":"2026-02-20T03:38:14.457177Z","iopub.status.idle":"2026-02-20T03:38:15.155923Z","shell.execute_reply.started":"2026-02-20T03:38:14.457144Z","shell.execute_reply":"2026-02-20T03:38:15.155228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory = model.fit_generator(train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=test_it, \n    validation_steps=len(test_it), \n    epochs=20, \n    verbose=1 \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:38:20.721303Z","iopub.execute_input":"2026-02-20T03:38:20.721650Z","iopub.status.idle":"2026-02-20T03:52:35.599599Z","shell.execute_reply.started":"2026-02-20T03:38:20.721623Z","shell.execute_reply":"2026-02-20T03:52:35.598838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:55:14.948048Z","iopub.execute_input":"2026-02-20T03:55:14.948735Z","iopub.status.idle":"2026-02-20T03:55:24.929306Z","shell.execute_reply.started":"2026-02-20T03:55:14.948701Z","shell.execute_reply":"2026-02-20T03:55:24.928507Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from matplotlib import pyplot\n\npyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\npyplot.legend()\n\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\npyplot.legend()\n\t# save plot to file\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:55:26.079822Z","iopub.execute_input":"2026-02-20T03:55:26.080223Z","iopub.status.idle":"2026-02-20T03:55:26.568786Z","shell.execute_reply.started":"2026-02-20T03:55:26.080195Z","shell.execute_reply":"2026-02-20T03:55:26.568013Z"}},"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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:55:31.057004Z","iopub.execute_input":"2026-02-20T03:55:31.057344Z","iopub.status.idle":"2026-02-20T03:55:31.062271Z","shell.execute_reply.started":"2026-02-20T03:55:31.057320Z","shell.execute_reply":"2026-02-20T03:55:31.061312Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:55:32.897311Z","iopub.execute_input":"2026-02-20T03:55:32.897632Z","iopub.status.idle":"2026-02-20T03:55:32.946455Z","shell.execute_reply.started":"2026-02-20T03:55:32.897608Z","shell.execute_reply":"2026-02-20T03:55:32.945786Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\t# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\nhistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=1)\n\t# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T03:55:35.201759Z","iopub.execute_input":"2026-02-20T03:55:35.202473Z","iopub.status.idle":"2026-02-20T04:09:08.022386Z","shell.execute_reply.started":"2026-02-20T03:55:35.202440Z","shell.execute_reply":"2026-02-20T04:09:08.021468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\nfilename = sys.argv[0].split('/')[-1]\npyplot.savefig(filename + '_plot.png')\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:10:41.451634Z","iopub.execute_input":"2026-02-20T04:10:41.452395Z","iopub.status.idle":"2026-02-20T04:10:41.910789Z","shell.execute_reply.started":"2026-02-20T04:10:41.452362Z","shell.execute_reply":"2026-02-20T04:10:41.909939Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## One Block VGG Model","metadata":{}},{"cell_type":"code","source":"# define cnn model\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:10:45.441953Z","iopub.execute_input":"2026-02-20T04:10:45.442945Z","iopub.status.idle":"2026-02-20T04:10:45.494748Z","shell.execute_reply.started":"2026-02-20T04:10:45.442899Z","shell.execute_reply":"2026-02-20T04:10:45.493853Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit_generator(train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=test_it, \n    validation_steps=len(test_it), \n    epochs=12, \n    verbose=1 \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:10:47.852303Z","iopub.execute_input":"2026-02-20T04:10:47.852646Z","iopub.status.idle":"2026-02-20T04:18:53.307052Z","shell.execute_reply.started":"2026-02-20T04:10:47.852618Z","shell.execute_reply":"2026-02-20T04:18:53.306247Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\npyplot.legend()\n\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\npyplot.legend()\n\t# save plot to file\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:19:18.302616Z","iopub.execute_input":"2026-02-20T04:19:18.303041Z","iopub.status.idle":"2026-02-20T04:19:18.746879Z","shell.execute_reply.started":"2026-02-20T04:19:18.303007Z","shell.execute_reply":"2026-02-20T04:19:18.746066Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Two Block VGG Model","metadata":{}},{"cell_type":"code","source":"# define cnn model\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:19:21.851681Z","iopub.execute_input":"2026-02-20T04:19:21.852356Z","iopub.status.idle":"2026-02-20T04:19:21.914816Z","shell.execute_reply.started":"2026-02-20T04:19:21.852323Z","shell.execute_reply":"2026-02-20T04:19:21.914149Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit_generator(train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=test_it, \n    validation_steps=len(test_it), \n    epochs=12, \n    verbose=1 \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:19:24.306233Z","iopub.execute_input":"2026-02-20T04:19:24.306589Z","iopub.status.idle":"2026-02-20T04:27:26.245788Z","shell.execute_reply.started":"2026-02-20T04:19:24.306560Z","shell.execute_reply":"2026-02-20T04:27:26.245062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\npyplot.legend()\n\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\npyplot.legend()\n\t# save plot to file\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:27:45.212296Z","iopub.execute_input":"2026-02-20T04:27:45.213080Z","iopub.status.idle":"2026-02-20T04:27:45.675991Z","shell.execute_reply.started":"2026-02-20T04:27:45.213044Z","shell.execute_reply":"2026-02-20T04:27:45.675198Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Three Block VGG Model","metadata":{}},{"cell_type":"code","source":"# define cnn model\nfrom keras.layers import Dropout\n\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:28:12.321472Z","iopub.execute_input":"2026-02-20T04:28:12.321821Z","iopub.status.idle":"2026-02-20T04:28:12.408741Z","shell.execute_reply.started":"2026-02-20T04:28:12.321792Z","shell.execute_reply":"2026-02-20T04:28:12.407851Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit_generator(train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=test_it, \n    validation_steps=len(test_it), \n    epochs=12, \n    verbose=1 \n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:28:15.682136Z","iopub.execute_input":"2026-02-20T04:28:15.683026Z","iopub.status.idle":"2026-02-20T04:37:51.543649Z","shell.execute_reply.started":"2026-02-20T04:28:15.682985Z","shell.execute_reply":"2026-02-20T04:37:51.542768Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\npyplot.legend()\n\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\npyplot.legend()\n\t# save plot to file\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:40:29.257383Z","iopub.execute_input":"2026-02-20T04:40:29.258077Z","iopub.status.idle":"2026-02-20T04:40:29.604983Z","shell.execute_reply.started":"2026-02-20T04:40:29.258042Z","shell.execute_reply":"2026-02-20T04:40:29.604103Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Dropout Regularization\n","metadata":{}},{"cell_type":"code","source":"# baseline model with dropout 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.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# plot diagnostic learning curves\n\t# plot loss\n\n\n# run the test harness for evaluating a model\n\t# define model\n\t# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\nhistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\tvalidation_data=test_it, validation_steps=len(test_it), epochs=50, verbose=1)\n\t# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n\t# learning curves\nsummarize_diagnostics(history)\n\n# entry point, run the test harness\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T04:41:06.521643Z","iopub.execute_input":"2026-02-20T04:41:06.522326Z","iopub.status.idle":"2026-02-20T05:21:08.191936Z","shell.execute_reply.started":"2026-02-20T04:41:06.522293Z","shell.execute_reply":"2026-02-20T05:21:08.190802Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\npyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\npyplot.legend()\n\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\npyplot.legend()\n\t# save plot to file\npyplot.tight_layout()\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T05:25:36.241457Z","iopub.execute_input":"2026-02-20T05:25:36.241929Z","iopub.status.idle":"2026-02-20T05:25:36.578281Z","shell.execute_reply.started":"2026-02-20T05:25:36.241883Z","shell.execute_reply":"2026-02-20T05:25:36.577430Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Image Data Augmentation","metadata":{}},{"cell_type":"code","source":"# create data generators\ntrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n# prepare iterators\ntrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T05:25:50.327875Z","iopub.execute_input":"2026-02-20T05:25:50.328735Z","iopub.status.idle":"2026-02-20T05:25:51.107588Z","shell.execute_reply.started":"2026-02-20T05:25:50.328705Z","shell.execute_reply":"2026-02-20T05:25:51.106948Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model with data augmentation 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\n\n# define cnn model\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\ntrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\ntrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\nhistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\tvalidation_data=test_it, validation_steps=len(test_it), epochs=50, verbose=1)\n\t# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T06:15:58.732818Z","iopub.execute_input":"2026-02-20T06:15:58.733544Z","iopub.status.idle":"2026-02-20T08:33:52.748442Z","shell.execute_reply.started":"2026-02-20T06:15:58.733510Z","shell.execute_reply":"2026-02-20T08:33:52.747376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\nfilename = sys.argv[0].split('/')[-1]\npyplot.savefig(filename + '_plot.png')\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T08:33:53.177959Z","iopub.execute_input":"2026-02-20T08:33:53.178280Z","iopub.status.idle":"2026-02-20T08:33:53.604037Z","shell.execute_reply.started":"2026-02-20T08:33:53.178254Z","shell.execute_reply":"2026-02-20T08:33:53.603122Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Explore Transfer Learning\n","metadata":{}},{"cell_type":"code","source":"import sys\nimport tensorflow as tf\nfrom matplotlib import pyplot\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.optimizers import Adam,SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\n\n\t# load model\nmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\nfor layer in model.layers:\n\tlayer.trainable = False\n\t# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\nmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\nopt = SGD(lr=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n\n\n\t# create data generator\ndatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\ndatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\t# fit model\nhistory = model.fit(train_it, steps_per_epoch=len(train_it),\n\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=1)\n\t# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n\n\t# learning curves\npyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\nfilename = sys.argv[0].split('/')[-1]\npyplot.savefig(filename + '_plot.png')\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T08:35:03.518700Z","iopub.execute_input":"2026-02-20T08:35:03.519538Z","iopub.status.idle":"2026-02-20T09:14:11.495398Z","shell.execute_reply.started":"2026-02-20T08:35:03.519503Z","shell.execute_reply":"2026-02-20T09:14:11.494345Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\nbase_model = VGG16(\n    weights='imagenet', \n    include_top=False, \n    input_shape=(224, 224, 3)\n)\n\n\nfor layer in base_model.layers:\n    layer.trainable = False\n\n\nx = Flatten()(base_model.output)\nx = Dense(128, activation='relu', kernel_initializer='he_uniform')(x)\noutput = Dense(1, activation='sigmoid')(x) \n\nmodel = Model(inputs=base_model.input, outputs=output)\n\nmodel.compile(\n    optimizer=Adam(learning_rate=0.001), \n    loss='binary_crossentropy',\n    metrics=['accuracy']\n)\n\nhistory = model.fit(\n    train_it,             \n    epochs=10,\n    validation_data=test_it,\n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T09:15:00.443166Z","iopub.execute_input":"2026-02-20T09:15:00.444373Z","iopub.status.idle":"2026-02-20T09:34:13.715587Z","shell.execute_reply.started":"2026-02-20T09:15:00.444333Z","shell.execute_reply":"2026-02-20T09:34:13.714830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pyplot.subplot(211)\npyplot.title('Cross Entropy Loss')\npyplot.plot(history.history['loss'], color='blue', label='train')\npyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\npyplot.subplot(212)\npyplot.title('Classification Accuracy')\npyplot.plot(history.history['accuracy'], color='blue', label='train')\npyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\nfilename = sys.argv[0].split('/')[-1]\npyplot.savefig(filename + '_plot.png')\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T09:34:45.447996Z","iopub.execute_input":"2026-02-20T09:34:45.448356Z","iopub.status.idle":"2026-02-20T09:34:45.893523Z","shell.execute_reply.started":"2026-02-20T09:34:45.448331Z","shell.execute_reply":"2026-02-20T09:34:45.892438Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nprint(\"\\nRandom Inference (5 Cats and 5 Dogs):\")\n\nplt.figure(figsize=(15, 6))\n\ncat_images, dog_images = [], []\ncat_labels, dog_labels = [], []\n\nfor imgs, labels in test_it:\n    for i in range(len(imgs)):\n        if labels[i] == 0 and len(cat_images) < 5:\n            cat_images.append(imgs[i])\n            cat_labels.append(labels[i])\n        elif labels[i] == 1 and len(dog_images) < 5:\n            dog_images.append(imgs[i])\n            dog_labels.append(labels[i])\n            \n    if len(cat_images) == 5 and len(dog_images) == 5:\n        break\n\nall_imgs = cat_images + dog_images\nall_labels = cat_labels + dog_labels\n\nfor i in range(10):\n    ax = plt.subplot(2, 5, i + 1)\n    \n    img = all_imgs[i]\n    img_display = ((img - img.min()) * (255 / (img.max() - img.min()))).astype(\"uint8\")\n    plt.imshow(img_display)\n    \n    img_input = tf.expand_dims(img, 0)\n    prediction = model.predict(img_input, verbose=0)[0][0]\n    \n    pred_label = \"Dog\" if prediction > 0.5 else \"Cat\"\n    true_label = \"Dog\" if all_labels[i] == 1 else \"Cat\"\n    color = \"green\" if pred_label == true_label else \"red\"\n    score = prediction if prediction > 0.5 else 1 - prediction\n    \n    plt.title(f\"True: {true_label}\\nPred: {pred_label}\\n({score:.2%})\", color=color, fontsize=10)\n    plt.axis(\"off\")\n    print(prediction)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-20T09:35:42.234846Z","iopub.execute_input":"2026-02-20T09:35:42.235248Z","iopub.status.idle":"2026-02-20T09:35:44.734959Z","shell.execute_reply.started":"2026-02-20T09:35:42.235216Z","shell.execute_reply":"2026-02-20T09:35:44.733792Z"}},"outputs":[],"execution_count":null}]}