{"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\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-09-12T20:45:45.707556Z","iopub.execute_input":"2026-09-12T20:45:45.708275Z","iopub.status.idle":"2026-09-12T20:45:45.721925Z","shell.execute_reply.started":"2026-09-12T20:45:45.708243Z","shell.execute_reply":"2026-09-12T20:45:45.721043Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:45.723643Z","iopub.execute_input":"2026-09-12T20:45:45.724032Z","iopub.status.idle":"2026-09-12T20:45:46.782979Z","shell.execute_reply.started":"2026-09-12T20:45:45.724009Z","shell.execute_reply":"2026-09-12T20:45:46.781967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:46.784368Z","iopub.execute_input":"2026-09-12T20:45:46.784813Z","iopub.status.idle":"2026-09-12T20:45:47.822906Z","shell.execute_reply.started":"2026-09-12T20:45:46.784786Z","shell.execute_reply":"2026-09-12T20:45:47.821848Z"}},"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-12T20:45:47.824315Z","iopub.execute_input":"2026-09-12T20:45:47.824647Z","iopub.status.idle":"2026-09-12T20:45:55.331631Z","shell.execute_reply.started":"2026-09-12T20:45:47.824620Z","shell.execute_reply":"2026-09-12T20:45:55.325514Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.332380Z","iopub.status.idle":"2026-09-12T20:45:55.332723Z","shell.execute_reply.started":"2026-09-12T20:45:55.332539Z","shell.execute_reply":"2026-09-12T20:45:55.332553Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.334147Z","iopub.status.idle":"2026-09-12T20:45:55.334609Z","shell.execute_reply.started":"2026-09-12T20:45:55.334369Z","shell.execute_reply":"2026-09-12T20:45:55.334390Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.335989Z","iopub.status.idle":"2026-09-12T20:45:55.336283Z","shell.execute_reply.started":"2026-09-12T20:45:55.336128Z","shell.execute_reply":"2026-09-12T20:45:55.336141Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.337642Z","iopub.status.idle":"2026-09-12T20:45:55.338048Z","shell.execute_reply.started":"2026-09-12T20:45:55.337902Z","shell.execute_reply":"2026-09-12T20:45:55.337917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.339838Z","iopub.status.idle":"2026-09-12T20:45:55.340185Z","shell.execute_reply.started":"2026-09-12T20:45:55.340037Z","shell.execute_reply":"2026-09-12T20:45:55.340052Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.341895Z","iopub.status.idle":"2026-09-12T20:45:55.342252Z","shell.execute_reply.started":"2026-09-12T20:45:55.342100Z","shell.execute_reply":"2026-09-12T20:45:55.342114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.343600Z","iopub.status.idle":"2026-09-12T20:45:55.343973Z","shell.execute_reply.started":"2026-09-12T20:45:55.343823Z","shell.execute_reply":"2026-09-12T20:45:55.343838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.344808Z","iopub.status.idle":"2026-09-12T20:45:55.345090Z","shell.execute_reply.started":"2026-09-12T20:45:55.344948Z","shell.execute_reply":"2026-09-12T20:45:55.344960Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.346287Z","iopub.status.idle":"2026-09-12T20:45:55.346608Z","shell.execute_reply.started":"2026-09-12T20:45:55.346431Z","shell.execute_reply":"2026-09-12T20:45:55.346462Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.348838Z","iopub.status.idle":"2026-09-12T20:45:55.349121Z","shell.execute_reply.started":"2026-09-12T20:45:55.348975Z","shell.execute_reply":"2026-09-12T20:45:55.348987Z"}},"outputs":[],"execution_count":null},{"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-09-12T20:45:55.349924Z","iopub.status.idle":"2026-09-12T20:45:55.350215Z","shell.execute_reply.started":"2026-09-12T20:45:55.350071Z","shell.execute_reply":"2026-09-12T20:45:55.350083Z"},"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-12T20:45:55.351760Z","iopub.status.idle":"2026-09-12T20:45:55.352082Z","shell.execute_reply.started":"2026-09-12T20:45:55.351939Z","shell.execute_reply":"2026-09-12T20:45:55.351953Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.353265Z","iopub.status.idle":"2026-09-12T20:45:55.353577Z","shell.execute_reply.started":"2026-09-12T20:45:55.353439Z","shell.execute_reply":"2026-09-12T20:45:55.353452Z"}},"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-12T20:45:55.354807Z","iopub.status.idle":"2026-09-12T20:45:55.355080Z","shell.execute_reply.started":"2026-09-12T20:45:55.354949Z","shell.execute_reply":"2026-09-12T20:45:55.354961Z"}},"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-12T20:45:55.356524Z","iopub.status.idle":"2026-09-12T20:45:55.356888Z","shell.execute_reply.started":"2026-09-12T20:45:55.356675Z","shell.execute_reply":"2026-09-12T20:45:55.356739Z"},"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-12T20:45:55.357816Z","iopub.status.idle":"2026-09-12T20:45:55.358095Z","shell.execute_reply.started":"2026-09-12T20:45:55.357949Z","shell.execute_reply":"2026-09-12T20:45:55.357961Z"},"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-12T20:45:55.359246Z","iopub.status.idle":"2026-09-12T20:45:55.359506Z","shell.execute_reply.started":"2026-09-12T20:45:55.359376Z","shell.execute_reply":"2026-09-12T20:45:55.359388Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.360426Z","iopub.status.idle":"2026-09-12T20:45:55.360813Z","shell.execute_reply.started":"2026-09-12T20:45:55.360617Z","shell.execute_reply":"2026-09-12T20:45:55.360631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.362083Z","iopub.status.idle":"2026-09-12T20:45:55.362349Z","shell.execute_reply.started":"2026-09-12T20:45:55.362222Z","shell.execute_reply":"2026-09-12T20:45:55.362234Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.363646Z","iopub.status.idle":"2026-09-12T20:45:55.364103Z","shell.execute_reply.started":"2026-09-12T20:45:55.363879Z","shell.execute_reply":"2026-09-12T20:45:55.363900Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.365484Z","iopub.status.idle":"2026-09-12T20:45:55.366058Z","shell.execute_reply.started":"2026-09-12T20:45:55.365718Z","shell.execute_reply":"2026-09-12T20:45:55.365740Z"}},"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-12T20:45:55.368028Z","iopub.status.idle":"2026-09-12T20:45:55.368481Z","shell.execute_reply.started":"2026-09-12T20:45:55.368240Z","shell.execute_reply":"2026-09-12T20:45:55.368260Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.370074Z","iopub.status.idle":"2026-09-12T20:45:55.370449Z","shell.execute_reply.started":"2026-09-12T20:45:55.370276Z","shell.execute_reply":"2026-09-12T20:45:55.370293Z"}},"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-12T20:45:55.372031Z","iopub.status.idle":"2026-09-12T20:45:55.372310Z","shell.execute_reply.started":"2026-09-12T20:45:55.372174Z","shell.execute_reply":"2026-09-12T20:45:55.372188Z"},"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-12T20:45:55.373172Z","iopub.status.idle":"2026-09-12T20:45:55.373461Z","shell.execute_reply.started":"2026-09-12T20:45:55.373312Z","shell.execute_reply":"2026-09-12T20:45:55.373325Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-12T20:45:55.374503Z","iopub.status.idle":"2026-09-12T20:45:55.374848Z","shell.execute_reply.started":"2026-09-12T20:45:55.374646Z","shell.execute_reply":"2026-09-12T20:45:55.374658Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-12T20:45:55.376321Z","iopub.status.idle":"2026-09-12T20:45:55.376748Z","shell.execute_reply.started":"2026-09-12T20:45:55.376537Z","shell.execute_reply":"2026-09-12T20:45:55.376553Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.378978Z","iopub.status.idle":"2026-09-12T20:45:55.379290Z","shell.execute_reply.started":"2026-09-12T20:45:55.379144Z","shell.execute_reply":"2026-09-12T20:45:55.379160Z"}},"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-12T20:45:55.380653Z","iopub.status.idle":"2026-09-12T20:45:55.380993Z","shell.execute_reply.started":"2026-09-12T20:45:55.380855Z","shell.execute_reply":"2026-09-12T20:45:55.380869Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.383101Z","iopub.status.idle":"2026-09-12T20:45:55.383422Z","shell.execute_reply.started":"2026-09-12T20:45:55.383279Z","shell.execute_reply":"2026-09-12T20:45:55.383292Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, \n                 (3, 3), \n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.384846Z","iopub.status.idle":"2026-09-12T20:45:55.385183Z","shell.execute_reply.started":"2026-09-12T20:45:55.385032Z","shell.execute_reply":"2026-09-12T20:45:55.385046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, \n                 (3, 3), \n                 activation='relu',\n                 input_shape=(200, 200, 3)\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-12T20:45:55.386553Z","iopub.status.idle":"2026-09-12T20:45:55.386922Z","shell.execute_reply.started":"2026-09-12T20:45:55.386755Z","shell.execute_reply":"2026-09-12T20:45:55.386781Z"}},"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', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\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-12T20:45:55.388350Z","iopub.status.idle":"2026-09-12T20:45:55.388771Z","shell.execute_reply.started":"2026-09-12T20:45:55.388553Z","shell.execute_reply":"2026-09-12T20:45:55.388568Z"}},"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-12T20:45:55.390228Z","iopub.status.idle":"2026-09-12T20:45:55.390579Z","shell.execute_reply.started":"2026-09-12T20:45:55.390425Z","shell.execute_reply":"2026-09-12T20:45:55.390441Z"}},"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-12T20:45:55.391803Z","iopub.status.idle":"2026-09-12T20:45:55.392126Z","shell.execute_reply.started":"2026-09-12T20:45:55.391983Z","shell.execute_reply":"2026-09-12T20:45:55.391997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model, not recommend to call this function\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.393809Z","iopub.status.idle":"2026-09-12T20:45:55.394247Z","shell.execute_reply.started":"2026-09-12T20:45:55.394013Z","shell.execute_reply":"2026-09-12T20:45:55.394033Z"}},"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-12T20:45:55.395615Z","iopub.status.idle":"2026-09-12T20:45:55.395995Z","shell.execute_reply.started":"2026-09-12T20:45:55.395846Z","shell.execute_reply":"2026-09-12T20:45:55.395861Z"}},"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-12T20:45:55.397909Z","iopub.status.idle":"2026-09-12T20:45:55.398351Z","shell.execute_reply.started":"2026-09-12T20:45:55.398117Z","shell.execute_reply":"2026-09-12T20:45:55.398137Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary',\n    batch_size=64,\n    target_size=(200, 200)\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.399820Z","iopub.status.idle":"2026-09-12T20:45:55.400256Z","shell.execute_reply.started":"2026-09-12T20:45:55.400025Z","shell.execute_reply":"2026-09-12T20:45:55.400046Z"}},"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-12T20:45:55.401092Z","iopub.status.idle":"2026-09-12T20:45:55.401523Z","shell.execute_reply.started":"2026-09-12T20:45:55.401303Z","shell.execute_reply":"2026-09-12T20:45:55.401324Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary',\n    batch_size=64, \n    target_size=(200, 200)\n)\ntype(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.403017Z","iopub.status.idle":"2026-09-12T20:45:55.403350Z","shell.execute_reply.started":"2026-09-12T20:45:55.403200Z","shell.execute_reply":"2026-09-12T20:45:55.403215Z"}},"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-12T20:45:55.404815Z","iopub.status.idle":"2026-09-12T20:45:55.405165Z","shell.execute_reply.started":"2026-09-12T20:45:55.405009Z","shell.execute_reply":"2026-09-12T20:45:55.405023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit(\n    train_it, steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=1, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.406635Z","iopub.status.idle":"2026-09-12T20:45:55.407041Z","shell.execute_reply.started":"2026-09-12T20:45:55.406890Z","shell.execute_reply":"2026-09-12T20:45:55.406906Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.408352Z","iopub.status.idle":"2026-09-12T20:45:55.408631Z","shell.execute_reply.started":"2026-09-12T20:45:55.408499Z","shell.execute_reply":"2026-09-12T20:45:55.408512Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.410496Z","iopub.status.idle":"2026-09-12T20:45:55.410964Z","shell.execute_reply.started":"2026-09-12T20:45:55.410738Z","shell.execute_reply":"2026-09-12T20:45:55.410759Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.411999Z","iopub.status.idle":"2026-09-12T20:45:55.412445Z","shell.execute_reply.started":"2026-09-12T20:45:55.412196Z","shell.execute_reply":"2026-09-12T20:45:55.412215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.413617Z","iopub.status.idle":"2026-09-12T20:45:55.414025Z","shell.execute_reply.started":"2026-09-12T20:45:55.413820Z","shell.execute_reply":"2026-09-12T20:45:55.413839Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = 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-12T20:45:55.415240Z","iopub.status.idle":"2026-09-12T20:45:55.415639Z","shell.execute_reply.started":"2026-09-12T20:45:55.415428Z","shell.execute_reply":"2026-09-12T20:45:55.415447Z"}},"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-12T20:45:55.417380Z","iopub.status.idle":"2026-09-12T20:45:55.417858Z","shell.execute_reply.started":"2026-09-12T20:45:55.417608Z","shell.execute_reply":"2026-09-12T20:45:55.417630Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.418871Z","iopub.status.idle":"2026-09-12T20:45:55.419275Z","shell.execute_reply.started":"2026-09-12T20:45:55.419060Z","shell.execute_reply":"2026-09-12T20:45:55.419078Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.420474Z","iopub.status.idle":"2026-09-12T20:45:55.420898Z","shell.execute_reply.started":"2026-09-12T20:45:55.420666Z","shell.execute_reply":"2026-09-12T20:45:55.420705Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(12)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.422306Z","iopub.status.idle":"2026-09-12T20:45:55.422646Z","shell.execute_reply.started":"2026-09-12T20:45:55.422486Z","shell.execute_reply":"2026-09-12T20:45:55.422500Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.424252Z","iopub.status.idle":"2026-09-12T20:45:55.424518Z","shell.execute_reply.started":"2026-09-12T20:45:55.424388Z","shell.execute_reply":"2026-09-12T20:45:55.424400Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (224, 224)\n\n#datagen = ImageDataGenerator(rescale=1.0/255.0,\n#                            horizontal_flip=True,)\n#print(IMAGE_SIZE)\n# prepare iterators\n#train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n#    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n#val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n#    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen_test = ImageDataGenerator(rescale=1./255,\n                                 vertical_flip=True)\n\n# Create the data generator using the DataFrame\ntest_it = datagen_test.flow_from_dataframe(\n    dataframe=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=64,\n    class_mode=None,       # Since there are no labels\n    # shuffle=True,         # Usually testing data should not be shuffled\n    shuffle=False,\n)\ntype(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.425306Z","iopub.status.idle":"2026-09-12T20:45:55.425636Z","shell.execute_reply.started":"2026-09-12T20:45:55.425490Z","shell.execute_reply":"2026-09-12T20:45:55.425504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_exmaple(images):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        if i < images.shape[0]:\n            ax.imshow(images[i])\n        #ax.axis('off')  # Turn off axis ticks/labels for clarity\n        ax.axis('on')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.427510Z","iopub.status.idle":"2026-09-12T20:45:55.427894Z","shell.execute_reply.started":"2026-09-12T20:45:55.427733Z","shell.execute_reply":"2026-09-12T20:45:55.427758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\ntrain_images.shape\nplot_exmaple(train_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.429468Z","iopub.status.idle":"2026-09-12T20:45:55.429871Z","shell.execute_reply.started":"2026-09-12T20:45:55.429659Z","shell.execute_reply":"2026-09-12T20:45:55.429674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images)\nval_labels[:8]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.431218Z","iopub.status.idle":"2026-09-12T20:45:55.431494Z","shell.execute_reply.started":"2026-09-12T20:45:55.431366Z","shell.execute_reply":"2026-09-12T20:45:55.431378Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape\nplot_exmaple(test_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.432548Z","iopub.status.idle":"2026-09-12T20:45:55.432875Z","shell.execute_reply.started":"2026-09-12T20:45:55.432735Z","shell.execute_reply":"2026-09-12T20:45:55.432749Z"}},"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# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.434525Z","iopub.status.idle":"2026-09-12T20:45:55.434859Z","shell.execute_reply.started":"2026-09-12T20:45:55.434667Z","shell.execute_reply":"2026-09-12T20:45:55.434679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model = VGG16(include_top=False, input_shape=(224, 224, 3))\n# mark loaded layers as not trainable\n# for layer in model.layers:\n#     layer.trainable = False\n\n# print(model.layers[-1].output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.435737Z","iopub.status.idle":"2026-09-12T20:45:55.436014Z","shell.execute_reply.started":"2026-09-12T20:45:55.435881Z","shell.execute_reply":"2026-09-12T20:45:55.435894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_feature_extractor = VGG16(include_top=False, input_shape=(224, 224, 3))\n# model_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.437289Z","iopub.status.idle":"2026-09-12T20:45:55.437583Z","shell.execute_reply.started":"2026-09-12T20:45:55.437440Z","shell.execute_reply":"2026-09-12T20:45:55.437454Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model_16_feature_extractor.layers):\n# \t\tprint(index, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.438672Z","iopub.status.idle":"2026-09-12T20:45:55.439001Z","shell.execute_reply.started":"2026-09-12T20:45:55.438871Z","shell.execute_reply":"2026-09-12T20:45:55.438885Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_top = VGG16(include_top=True, input_shape=(224, 224, 3))\n# model_16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.440377Z","iopub.status.idle":"2026-09-12T20:45:55.440636Z","shell.execute_reply.started":"2026-09-12T20:45:55.440510Z","shell.execute_reply":"2026-09-12T20:45:55.440522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.441772Z","iopub.status.idle":"2026-09-12T20:45:55.442080Z","shell.execute_reply.started":"2026-09-12T20:45:55.441942Z","shell.execute_reply":"2026-09-12T20:45:55.441956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.443396Z","iopub.status.idle":"2026-09-12T20:45:55.443665Z","shell.execute_reply.started":"2026-09-12T20:45:55.443538Z","shell.execute_reply":"2026-09-12T20:45:55.443550Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     print(index, layer.name, layer.trainable)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.445026Z","iopub.status.idle":"2026-09-12T20:45:55.445294Z","shell.execute_reply.started":"2026-09-12T20:45:55.445164Z","shell.execute_reply":"2026-09-12T20:45:55.445176Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     layer.trainable = True\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.446322Z","iopub.status.idle":"2026-09-12T20:45:55.446675Z","shell.execute_reply.started":"2026-09-12T20:45:55.446511Z","shell.execute_reply":"2026-09-12T20:45:55.446534Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     if index >= 15:\n#         layer.trainable = True\n\n# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.448230Z","iopub.status.idle":"2026-09-12T20:45:55.448540Z","shell.execute_reply.started":"2026-09-12T20:45:55.448402Z","shell.execute_reply":"2026-09-12T20:45:55.448418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.451805Z","iopub.status.idle":"2026-09-12T20:45:55.452109Z","shell.execute_reply.started":"2026-09-12T20:45:55.451974Z","shell.execute_reply":"2026-09-12T20:45:55.451988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nprint(id(vgg16_model))\nvgg16_model.reset_states()\nvgg16_model_history = vgg16_model.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-12T20:45:55.453355Z","iopub.status.idle":"2026-09-12T20:45:55.453617Z","shell.execute_reply.started":"2026-09-12T20:45:55.453490Z","shell.execute_reply":"2026-09-12T20:45:55.453503Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(vgg16_model_history)\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.454603Z","iopub.status.idle":"2026-09-12T20:45:55.454943Z","shell.execute_reply.started":"2026-09-12T20:45:55.454789Z","shell.execute_reply":"2026-09-12T20:45:55.454804Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        # layer.trainable = True #try to test\n    \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n    # output = Dense(1, activation='sigmoid')(flat1)\n    output = Dense(2, activation='softmax')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.455964Z","iopub.status.idle":"2026-09-12T20:45:55.456231Z","shell.execute_reply.started":"2026-09-12T20:45:55.456092Z","shell.execute_reply":"2026-09-12T20:45:55.456105Z"}},"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-12T20:45:55.457619Z","iopub.status.idle":"2026-09-12T20:45:55.457992Z","shell.execute_reply.started":"2026-09-12T20:45:55.457842Z","shell.execute_reply":"2026-09-12T20:45:55.457857Z"},"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-12T20:45:55.459970Z","iopub.status.idle":"2026-09-12T20:45:55.460280Z","shell.execute_reply.started":"2026-09-12T20:45:55.460138Z","shell.execute_reply":"2026-09-12T20:45:55.460151Z"}},"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-12T20:45:55.461305Z","iopub.status.idle":"2026-09-12T20:45:55.461563Z","shell.execute_reply.started":"2026-09-12T20:45:55.461436Z","shell.execute_reply":"2026-09-12T20:45:55.461449Z"}},"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-12T20:45:55.462794Z","iopub.status.idle":"2026-09-12T20:45:55.463118Z","shell.execute_reply.started":"2026-09-12T20:45:55.462973Z","shell.execute_reply":"2026-09-12T20:45:55.462987Z"}},"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-12T20:45:55.464279Z","iopub.status.idle":"2026-09-12T20:45:55.464581Z","shell.execute_reply.started":"2026-09-12T20:45:55.464445Z","shell.execute_reply":"2026-09-12T20:45:55.464458Z"}},"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-12T20:45:55.465946Z","iopub.status.idle":"2026-09-12T20:45:55.466255Z","shell.execute_reply.started":"2026-09-12T20:45:55.466113Z","shell.execute_reply":"2026-09-12T20:45:55.466126Z"}},"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-12T20:45:55.467883Z","iopub.status.idle":"2026-09-12T20:45:55.468174Z","shell.execute_reply.started":"2026-09-12T20:45:55.468036Z","shell.execute_reply":"2026-09-12T20:45:55.468049Z"}},"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-12T20:45:55.469179Z","iopub.status.idle":"2026-09-12T20:45:55.469542Z","shell.execute_reply.started":"2026-09-12T20:45:55.469390Z","shell.execute_reply":"2026-09-12T20:45:55.469405Z"}},"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-12T20:45:55.470413Z","iopub.status.idle":"2026-09-12T20:45:55.470675Z","shell.execute_reply.started":"2026-09-12T20:45:55.470550Z","shell.execute_reply":"2026-09-12T20:45:55.470562Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:45:55.472394Z","iopub.status.idle":"2026-09-12T20:45:55.472819Z","shell.execute_reply.started":"2026-09-12T20:45:55.472589Z","shell.execute_reply":"2026-09-12T20:45:55.472608Z"}},"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-12T20:45:55.473977Z","iopub.status.idle":"2026-09-12T20:45:55.474290Z","shell.execute_reply.started":"2026-09-12T20:45:55.474148Z","shell.execute_reply":"2026-09-12T20:45:55.474166Z"}},"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-12T20:45:55.475676Z","iopub.status.idle":"2026-09-12T20:45:55.476101Z","shell.execute_reply.started":"2026-09-12T20:45:55.475892Z","shell.execute_reply":"2026-09-12T20:45:55.475912Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nprint(\"TensorFlow:\", tf.__version__)\nprint(\"GPU:\", tf.config.list_physical_devices(\"GPU\"))\nDATA_PATH = \"/kaggle/input/dogs-vs-cats\"\nTRAIN_ZIP = f\"{DATA_PATH}/train.zip\"\nTEST_ZIP = f\"{DATA_PATH}/test1.zip\"\n\nif not os.path.isdir(\"train\"):\n    with zipfile.ZipFile(TRAIN_ZIP, \"r\") as z:\n        z.extractall(\".\")\nif not os.path.isdir(\"test1\"):\n    with zipfile.ZipFile(TEST_ZIP, \"r\") as z:\n        z.extractall(\".\")\n\nprint(\"train:\", len(os.listdir(\"train\")))\nprint(\"test1:\", len(os.listdir(\"test1\")))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:56:25.685899Z","iopub.execute_input":"2026-09-12T20:56:25.686227Z","iopub.status.idle":"2026-09-12T20:56:25.705989Z","shell.execute_reply.started":"2026-09-12T20:56:25.686202Z","shell.execute_reply":"2026-09-12T20:56:25.705231Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from pathlib import Path\nfrom shutil import copy2\nimport random\n\nSEED = 1337\nVAL_RATIO = 0.25\n\ndataset_home = Path(\"dataset_dogs_vs_cats\")\ntrain_dir = dataset_home / \"train\"\nval_dir = dataset_home / \"val\"\n\nfor d in [train_dir / \"cats\", train_dir / \"dogs\",\n          val_dir / \"cats\", val_dir / \"dogs\"]:\n    d.mkdir(parents=True, exist_ok=True)\n\nexisting = sum(len(list((train_dir / c).glob(\"*.jpg\"))) for c in [\"cats\",\"dogs\"])\nif existing == 0:\n    random.seed(SEED)\n    files = list(Path(\"train\").glob(\"*.jpg\"))\n    random.shuffle(files)\n\n    for f in files:\n        cls = \"cat\" if f.name.startswith(\"cat.\") else \"dog\"\n        target_root = val_dir if random.random() < VAL_RATIO else train_dir\n        copy2(f, target_root / ((\"cats\" if cls == \"cat\" else \"dogs\")) / f.name)\n\nprint(\"Train cats:\", len(list((train_dir/\"cats\").glob(\"*.jpg\"))))\nprint(\"Train dogs:\", len(list((train_dir/\"dogs\").glob(\"*.jpg\"))))\nprint(\"Val cats:\", len(list((val_dir/\"cats\").glob(\"*.jpg\"))))\nprint(\"Val dogs:\", len(list((val_dir/\"dogs\").glob(\"*.jpg\"))))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:56:28.245133Z","iopub.execute_input":"2026-09-12T20:56:28.245492Z","iopub.status.idle":"2026-09-12T20:56:28.291393Z","shell.execute_reply.started":"2026-09-12T20:56:28.245469Z","shell.execute_reply":"2026-09-12T20:56:28.290572Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nIMAGE_SIZE = (224, 224)\nBATCH_SIZE = 32\n\ntrain_datagen = ImageDataGenerator(\n    preprocessing_function=tf.keras.applications.vgg16.preprocess_input,\n    rotation_range=15,\n    width_shift_range=0.10,\n    height_shift_range=0.10,\n    zoom_range=0.15,\n    horizontal_flip=True\n)\n\nval_datagen = ImageDataGenerator(\n    preprocessing_function=tf.keras.applications.vgg16.preprocess_input\n)\n\ntrain_it = train_datagen.flow_from_directory(\n    str(train_dir),\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=\"binary\",\n    shuffle=True,\n    seed=SEED\n)\n\nval_it = val_datagen.flow_from_directory(\n    str(val_dir),\n    target_size=IMAGE_SIZE,\n    batch_size=BATCH_SIZE,\n    class_mode=\"binary\",\n    shuffle=False\n)\n\nprint(\"Class mapping:\", train_it.class_indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:56:31.334958Z","iopub.execute_input":"2026-09-12T20:56:31.335320Z","iopub.status.idle":"2026-09-12T20:56:31.519669Z","shell.execute_reply.started":"2026-09-12T20:56:31.335295Z","shell.execute_reply":"2026-09-12T20:56:31.518876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import VGG16\nfrom tensorflow.keras import layers, Model\nbase_model = VGG16(\n    weights=\"imagenet\",\n    include_top=False,\n    input_shape=(224, 224, 3))\nbase_model.trainable = False\ninputs = layers.Input(shape=(224, 224, 3))\nx = base_model(inputs, training=False)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Dense(256, activation=\"relu\")(x)\nx = layers.Dropout(0.5)(x)\noutputs = layers.Dense(1, activation=\"sigmoid\")(x)\nmodel = Model(inputs, outputs)\nmodel.compile(\n    optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),\n    loss=\"binary_crossentropy\",\n    metrics=[\"accuracy\"])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:56:34.956062Z","iopub.execute_input":"2026-09-12T20:56:34.956910Z","iopub.status.idle":"2026-09-12T20:56:35.374265Z","shell.execute_reply.started":"2026-09-12T20:56:34.956877Z","shell.execute_reply":"2026-09-12T20:56:35.373339Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from glob import glob\n\ntest_files = sorted(glob(\"/kaggle/working/test1/*.jpg\"))\ntest_df = pd.DataFrame({\"filename\": test_files})\n\ntest_datagen = ImageDataGenerator(\n    preprocessing_function=tf.keras.applications.vgg16.preprocess_input\n)\n\ntest_it = test_datagen.flow_from_dataframe(\n    dataframe=test_df,\n    x_col=\"filename\",\n    y_col=None,\n    target_size=IMAGE_SIZE,\n    batch_size=32,\n    class_mode=None,\n    shuffle=False\n)\n\nprint(\"Test images:\", len(test_df))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:56:40.424876Z","iopub.execute_input":"2026-09-12T20:56:40.425196Z","iopub.status.idle":"2026-09-12T20:56:40.535295Z","shell.execute_reply.started":"2026-09-12T20:56:40.425172Z","shell.execute_reply":"2026-09-12T20:56:40.534328Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Test images:\", len(test_df))\n\npred_prob = model.predict(test_it).flatten()\npred_label = [\"dog\" if p >= 0.5 else \"cat\" for p in pred_prob]\n\nN = 10\nfig, axes = plt.subplots(2, 5, figsize=(18, 8))\naxes = axes.ravel()\n\nfor i in range(N):\n    img = load_img(test_df[\"filename\"].iloc[i], target_size=IMAGE_SIZE)\n    axes[i].imshow(img)\n    axes[i].set_title(f\"{pred_label[i]} | dog={pred_prob[i]:.3f}\")\n    axes[i].axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:04:08.512667Z","iopub.execute_input":"2026-09-12T21:04:08.513828Z","iopub.status.idle":"2026-09-12T21:05:03.748471Z","shell.execute_reply.started":"2026-09-12T21:04:08.513793Z","shell.execute_reply":"2026-09-12T21:05:03.745926Z"}},"outputs":[],"execution_count":null}]}