{"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-06T03:38:00.008955Z","iopub.execute_input":"2026-09-06T03:38:00.009204Z","iopub.status.idle":"2026-09-06T03:38:00.355174Z","shell.execute_reply.started":"2026-09-06T03:38:00.009182Z","shell.execute_reply":"2026-09-06T03:38:00.354205Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:00.357358Z","iopub.execute_input":"2026-09-06T03:38:00.357789Z","iopub.status.idle":"2026-09-06T03:38:01.474265Z","shell.execute_reply.started":"2026-09-06T03:38:00.357764Z","shell.execute_reply":"2026-09-06T03:38:01.473035Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"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-09-06T03:38:01.478967Z","iopub.execute_input":"2026-09-06T03:38:01.479864Z","iopub.status.idle":"2026-09-06T03:38:14.867973Z","shell.execute_reply.started":"2026-09-06T03:38:01.479806Z","shell.execute_reply":"2026-09-06T03:38:14.866900Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:14.869544Z","iopub.execute_input":"2026-09-06T03:38:14.870428Z","iopub.status.idle":"2026-09-06T03:38:15.868929Z","shell.execute_reply.started":"2026-09-06T03:38:14.870392Z","shell.execute_reply":"2026-09-06T03:38:15.867582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:15.870497Z","iopub.execute_input":"2026-09-06T03:38:15.870847Z","iopub.status.idle":"2026-09-06T03:38:16.860731Z","shell.execute_reply.started":"2026-09-06T03:38:15.870798Z","shell.execute_reply":"2026-09-06T03:38:16.859922Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:16.864676Z","iopub.execute_input":"2026-09-06T03:38:16.865056Z","iopub.status.idle":"2026-09-06T03:38:17.979141Z","shell.execute_reply.started":"2026-09-06T03:38:16.865022Z","shell.execute_reply":"2026-09-06T03:38:17.977927Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:17.980936Z","iopub.execute_input":"2026-09-06T03:38:17.981349Z","iopub.status.idle":"2026-09-06T03:38:19.075581Z","shell.execute_reply.started":"2026-09-06T03:38:17.981310Z","shell.execute_reply":"2026-09-06T03:38:19.074445Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:19.077202Z","iopub.execute_input":"2026-09-06T03:38:19.077560Z","iopub.status.idle":"2026-09-06T03:38:19.081788Z","shell.execute_reply.started":"2026-09-06T03:38:19.077528Z","shell.execute_reply":"2026-09-06T03:38:19.081158Z"}},"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-06T03:38:19.083338Z","iopub.execute_input":"2026-09-06T03:38:19.083969Z","iopub.status.idle":"2026-09-06T03:38:20.136260Z","shell.execute_reply.started":"2026-09-06T03:38:19.083936Z","shell.execute_reply":"2026-09-06T03:38:20.135378Z"},"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-06T03:38:20.137379Z","iopub.execute_input":"2026-09-06T03:38:20.137652Z","iopub.status.idle":"2026-09-06T03:38:21.070951Z","shell.execute_reply.started":"2026-09-06T03:38:20.137628Z","shell.execute_reply":"2026-09-06T03:38:21.069756Z"},"trusted":true},"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-06T03:38:21.072209Z","iopub.execute_input":"2026-09-06T03:38:21.072502Z","iopub.status.idle":"2026-09-06T03:38:37.391576Z","shell.execute_reply.started":"2026-09-06T03:38:21.072477Z","shell.execute_reply":"2026-09-06T03:38:37.390741Z"}},"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-06T03:38:37.392658Z","iopub.execute_input":"2026-09-06T03:38:37.393276Z","iopub.status.idle":"2026-09-06T03:38:37.398978Z","shell.execute_reply.started":"2026-09-06T03:38:37.393250Z","shell.execute_reply":"2026-09-06T03:38:37.397177Z"},"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-06T03:38:37.400498Z","iopub.execute_input":"2026-09-06T03:38:37.400882Z","iopub.status.idle":"2026-09-06T03:38:37.421005Z","shell.execute_reply.started":"2026-09-06T03:38:37.400824Z","shell.execute_reply":"2026-09-06T03:38:37.420201Z"},"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-06T03:38:37.422185Z","iopub.execute_input":"2026-09-06T03:38:37.422548Z","iopub.status.idle":"2026-09-06T03:38:37.432755Z","shell.execute_reply.started":"2026-09-06T03:38:37.422499Z","shell.execute_reply":"2026-09-06T03:38:37.432002Z"},"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-06T03:38:37.433976Z","iopub.execute_input":"2026-09-06T03:38:37.434961Z","iopub.status.idle":"2026-09-06T03:38:38.447122Z","shell.execute_reply.started":"2026-09-06T03:38:37.434933Z","shell.execute_reply":"2026-09-06T03:38:38.446054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:38.448448Z","iopub.execute_input":"2026-09-06T03:38:38.448877Z","iopub.status.idle":"2026-09-06T03:38:39.466673Z","shell.execute_reply.started":"2026-09-06T03:38:38.448809Z","shell.execute_reply":"2026-09-06T03:38:39.465602Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:39.468278Z","iopub.execute_input":"2026-09-06T03:38:39.468577Z","iopub.status.idle":"2026-09-06T03:38:40.468928Z","shell.execute_reply.started":"2026-09-06T03:38:39.468551Z","shell.execute_reply":"2026-09-06T03:38:40.467653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:40.470484Z","iopub.execute_input":"2026-09-06T03:38:40.470876Z","iopub.status.idle":"2026-09-06T03:38:41.480551Z","shell.execute_reply.started":"2026-09-06T03:38:40.470818Z","shell.execute_reply":"2026-09-06T03:38:41.479622Z"}},"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-06T03:38:41.483225Z","iopub.execute_input":"2026-09-06T03:38:41.483910Z","iopub.status.idle":"2026-09-06T03:38:43.502993Z","shell.execute_reply.started":"2026-09-06T03:38:41.483882Z","shell.execute_reply":"2026-09-06T03:38:43.501776Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:38:43.504425Z","iopub.execute_input":"2026-09-06T03:38:43.504774Z","iopub.status.idle":"2026-09-06T03:38:43.510297Z","shell.execute_reply.started":"2026-09-06T03:38:43.504741Z","shell.execute_reply":"2026-09-06T03:38:43.509500Z"}},"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-06T03:38:43.517095Z","iopub.execute_input":"2026-09-06T03:38:43.517711Z","iopub.status.idle":"2026-09-06T03:38:45.678426Z","shell.execute_reply.started":"2026-09-06T03:38:43.517689Z","shell.execute_reply":"2026-09-06T03:38:45.676716Z"},"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-06T03:38:45.680615Z","iopub.execute_input":"2026-09-06T03:38:45.681179Z","iopub.status.idle":"2026-09-06T03:38:47.752985Z","shell.execute_reply.started":"2026-09-06T03:38:45.681128Z","shell.execute_reply":"2026-09-06T03:38:47.751918Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-06T03:38:47.754349Z","iopub.execute_input":"2026-09-06T03:38:47.754641Z","iopub.status.idle":"2026-09-06T03:38:58.732663Z","shell.execute_reply.started":"2026-09-06T03:38:47.754617Z","shell.execute_reply":"2026-09-06T03:38:58.731267Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-06T03:38:58.734181Z","iopub.execute_input":"2026-09-06T03:38:58.734485Z","iopub.status.idle":"2026-09-06T03:38:58.750879Z","shell.execute_reply.started":"2026-09-06T03:38:58.734460Z","shell.execute_reply":"2026-09-06T03:38:58.749897Z"},"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-06T03:38:58.752050Z","iopub.execute_input":"2026-09-06T03:38:58.752560Z","iopub.status.idle":"2026-09-06T03:38:58.756350Z","shell.execute_reply.started":"2026-09-06T03:38:58.752537Z","shell.execute_reply":"2026-09-06T03:38:58.755688Z"}},"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-06T03:38:58.760428Z","iopub.execute_input":"2026-09-06T03:38:58.760640Z","iopub.status.idle":"2026-09-06T03:38:58.768883Z","shell.execute_reply.started":"2026-09-06T03:38:58.760621Z","shell.execute_reply":"2026-09-06T03:38:58.768261Z"}},"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-06T03:38:58.770073Z","iopub.execute_input":"2026-09-06T03:38:58.770869Z","iopub.status.idle":"2026-09-06T03:38:58.780212Z","shell.execute_reply.started":"2026-09-06T03:38:58.770803Z","shell.execute_reply":"2026-09-06T03:38:58.779567Z"}},"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-06T03:38:58.781226Z","iopub.execute_input":"2026-09-06T03:38:58.782102Z","iopub.status.idle":"2026-09-06T03:38:58.791611Z","shell.execute_reply.started":"2026-09-06T03:38:58.782064Z","shell.execute_reply":"2026-09-06T03:38:58.791018Z"}},"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-06T03:38:58.792633Z","iopub.execute_input":"2026-09-06T03:38:58.793361Z","iopub.status.idle":"2026-09-06T03:38:58.808014Z","shell.execute_reply.started":"2026-09-06T03:38:58.793339Z","shell.execute_reply":"2026-09-06T03:38:58.807174Z"}},"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-06T03:38:58.808814Z","iopub.execute_input":"2026-09-06T03:38:58.809161Z","iopub.status.idle":"2026-09-06T03:39:00.987910Z","shell.execute_reply.started":"2026-09-06T03:38:58.809129Z","shell.execute_reply":"2026-09-06T03:39:00.985993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:39:00.989422Z","iopub.execute_input":"2026-09-06T03:39:00.989789Z","iopub.status.idle":"2026-09-06T03:39:01.711983Z","shell.execute_reply.started":"2026-09-06T03:39:00.989753Z","shell.execute_reply":"2026-09-06T03:39:01.711219Z"}},"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-06T03:39:01.713010Z","iopub.execute_input":"2026-09-06T03:39:01.713350Z","iopub.status.idle":"2026-09-06T03:39:01.719689Z","shell.execute_reply.started":"2026-09-06T03:39:01.713326Z","shell.execute_reply":"2026-09-06T03:39:01.719058Z"}},"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-06T03:39:01.720979Z","iopub.execute_input":"2026-09-06T03:39:01.721236Z","iopub.status.idle":"2026-09-06T03:39:01.730655Z","shell.execute_reply.started":"2026-09-06T03:39:01.721216Z","shell.execute_reply":"2026-09-06T03:39:01.729934Z"}},"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_generator(\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-06T03:39:01.731755Z","iopub.execute_input":"2026-09-06T03:39:01.732117Z","iopub.status.idle":"2026-09-06T03:39:54.875974Z","shell.execute_reply.started":"2026-09-06T03:39:01.732086Z","shell.execute_reply":"2026-09-06T03:39:54.874681Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:39:54.877280Z","iopub.execute_input":"2026-09-06T03:39:54.877650Z","iopub.status.idle":"2026-09-06T03:39:55.238075Z","shell.execute_reply.started":"2026-09-06T03:39:54.877625Z","shell.execute_reply":"2026-09-06T03:39:55.237225Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:39:55.239290Z","iopub.execute_input":"2026-09-06T03:39:55.239635Z","iopub.status.idle":"2026-09-06T03:40:06.826038Z","shell.execute_reply.started":"2026-09-06T03:39:55.239608Z","shell.execute_reply":"2026-09-06T03:40:06.825103Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:06.827363Z","iopub.execute_input":"2026-09-06T03:40:06.827696Z","iopub.status.idle":"2026-09-06T03:40:07.855682Z","shell.execute_reply.started":"2026-09-06T03:40:06.827663Z","shell.execute_reply":"2026-09-06T03:40:07.854769Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:07.857157Z","iopub.execute_input":"2026-09-06T03:40:07.857463Z","iopub.status.idle":"2026-09-06T03:40:07.864817Z","shell.execute_reply.started":"2026-09-06T03:40:07.857438Z","shell.execute_reply":"2026-09-06T03:40:07.864130Z"}},"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-06T03:40:07.866042Z","iopub.execute_input":"2026-09-06T03:40:07.866451Z","iopub.status.idle":"2026-09-06T03:40:07.910699Z","shell.execute_reply.started":"2026-09-06T03:40:07.866427Z","shell.execute_reply":"2026-09-06T03:40:07.910035Z"}},"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-06T03:40:07.911939Z","iopub.execute_input":"2026-09-06T03:40:07.912237Z","iopub.status.idle":"2026-09-06T03:40:07.919201Z","shell.execute_reply.started":"2026-09-06T03:40:07.912212Z","shell.execute_reply":"2026-09-06T03:40:07.918063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:07.920492Z","iopub.execute_input":"2026-09-06T03:40:07.920804Z","iopub.status.idle":"2026-09-06T03:40:07.968435Z","shell.execute_reply.started":"2026-09-06T03:40:07.920774Z","shell.execute_reply":"2026-09-06T03:40:07.967529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:07.969460Z","iopub.execute_input":"2026-09-06T03:40:07.969706Z","iopub.status.idle":"2026-09-06T03:40:07.976501Z","shell.execute_reply.started":"2026-09-06T03:40:07.969685Z","shell.execute_reply":"2026-09-06T03:40:07.975565Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:07.977569Z","iopub.execute_input":"2026-09-06T03:40:07.978375Z","iopub.status.idle":"2026-09-06T03:40:07.990467Z","shell.execute_reply.started":"2026-09-06T03:40:07.978352Z","shell.execute_reply":"2026-09-06T03:40:07.989689Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:07.991589Z","iopub.execute_input":"2026-09-06T03:40:07.991938Z","iopub.status.idle":"2026-09-06T03:40:08.001613Z","shell.execute_reply.started":"2026-09-06T03:40:07.991912Z","shell.execute_reply":"2026-09-06T03:40:08.000691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (224, 224)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0,\n                            horizontal_flip=True,)\nprint(IMAGE_SIZE)\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\nval_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                                 horizontal_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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:08.002793Z","iopub.execute_input":"2026-09-06T03:40:08.003100Z","iopub.status.idle":"2026-09-06T03:40:08.760983Z","shell.execute_reply.started":"2026-09-06T03:40:08.003078Z","shell.execute_reply":"2026-09-06T03:40:08.760221Z"}},"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-06T03:40:08.762081Z","iopub.execute_input":"2026-09-06T03:40:08.762485Z","iopub.status.idle":"2026-09-06T03:40:08.768103Z","shell.execute_reply.started":"2026-09-06T03:40:08.762447Z","shell.execute_reply":"2026-09-06T03:40:08.767209Z"}},"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-06T03:40:08.769191Z","iopub.execute_input":"2026-09-06T03:40:08.769497Z","iopub.status.idle":"2026-09-06T03:40:18.251898Z","shell.execute_reply.started":"2026-09-06T03:40:08.769469Z","shell.execute_reply":"2026-09-06T03:40:18.250751Z"}},"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-06T03:40:18.253389Z","iopub.execute_input":"2026-09-06T03:40:18.253766Z","iopub.status.idle":"2026-09-06T03:40:27.733200Z","shell.execute_reply.started":"2026-09-06T03:40:18.253741Z","shell.execute_reply":"2026-09-06T03:40:27.731871Z"}},"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-06T03:40:27.735025Z","iopub.execute_input":"2026-09-06T03:40:27.735479Z","iopub.status.idle":"2026-09-06T03:40:37.351532Z","shell.execute_reply.started":"2026-09-06T03:40:27.735434Z","shell.execute_reply":"2026-09-06T03:40:37.349353Z"}},"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-06T03:40:37.352677Z","iopub.execute_input":"2026-09-06T03:40:37.353265Z","iopub.status.idle":"2026-09-06T03:40:37.360322Z","shell.execute_reply.started":"2026-09-06T03:40:37.353238Z","shell.execute_reply":"2026-09-06T03:40:37.359383Z"}},"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-06T03:40:37.361367Z","iopub.execute_input":"2026-09-06T03:40:37.361567Z","iopub.status.idle":"2026-09-06T03:40:37.377185Z","shell.execute_reply.started":"2026-09-06T03:40:37.361548Z","shell.execute_reply":"2026-09-06T03:40:37.376099Z"}},"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-06T03:40:37.378492Z","iopub.execute_input":"2026-09-06T03:40:37.378904Z","iopub.status.idle":"2026-09-06T03:40:37.385869Z","shell.execute_reply.started":"2026-09-06T03:40:37.378868Z","shell.execute_reply":"2026-09-06T03:40:37.385054Z"}},"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-06T03:40:37.386992Z","iopub.execute_input":"2026-09-06T03:40:37.387402Z","iopub.status.idle":"2026-09-06T03:40:37.396527Z","shell.execute_reply.started":"2026-09-06T03:40:37.387366Z","shell.execute_reply":"2026-09-06T03:40:37.395888Z"}},"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-06T03:40:37.397641Z","iopub.execute_input":"2026-09-06T03:40:37.398304Z","iopub.status.idle":"2026-09-06T03:40:37.408502Z","shell.execute_reply.started":"2026-09-06T03:40:37.398268Z","shell.execute_reply":"2026-09-06T03:40:37.407564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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-06T03:40:37.409560Z","iopub.execute_input":"2026-09-06T03:40:37.409970Z","iopub.status.idle":"2026-09-06T03:40:40.431184Z","shell.execute_reply.started":"2026-09-06T03:40:37.409933Z","shell.execute_reply":"2026-09-06T03:40:40.430267Z"}},"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-06T03:40:40.432330Z","iopub.execute_input":"2026-09-06T03:40:40.432611Z","iopub.status.idle":"2026-09-06T03:40:40.436565Z","shell.execute_reply.started":"2026-09-06T03:40:40.432588Z","shell.execute_reply":"2026-09-06T03:40:40.435898Z"}},"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-06T03:40:40.437859Z","iopub.execute_input":"2026-09-06T03:40:40.438163Z","iopub.status.idle":"2026-09-06T03:40:40.446510Z","shell.execute_reply.started":"2026-09-06T03:40:40.438133Z","shell.execute_reply":"2026-09-06T03:40:40.445792Z"}},"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-06T03:40:40.447956Z","iopub.execute_input":"2026-09-06T03:40:40.448269Z","iopub.status.idle":"2026-09-06T03:40:40.456053Z","shell.execute_reply.started":"2026-09-06T03:40:40.448238Z","shell.execute_reply":"2026-09-06T03:40:40.455131Z"}},"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-06T03:40:40.457020Z","iopub.execute_input":"2026-09-06T03:40:40.457286Z","iopub.status.idle":"2026-09-06T03:40:40.464493Z","shell.execute_reply.started":"2026-09-06T03:40:40.457266Z","shell.execute_reply":"2026-09-06T03:40:40.463622Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:40:40.465602Z","iopub.execute_input":"2026-09-06T03:40:40.465940Z","iopub.status.idle":"2026-09-06T03:40:40.479477Z","shell.execute_reply.started":"2026-09-06T03:40:40.465904Z","shell.execute_reply":"2026-09-06T03:40:40.478465Z"}},"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-06T03:40:40.481726Z","iopub.execute_input":"2026-09-06T03:40:40.482161Z","iopub.status.idle":"2026-09-06T03:46:39.700672Z","shell.execute_reply.started":"2026-09-06T03:40:40.482138Z","shell.execute_reply":"2026-09-06T03:46:39.699553Z"}},"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-06T03:46:39.702085Z","iopub.execute_input":"2026-09-06T03:46:39.703185Z","iopub.status.idle":"2026-09-06T03:47:41.713148Z","shell.execute_reply.started":"2026-09-06T03:46:39.703154Z","shell.execute_reply":"2026-09-06T03:47:41.712271Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"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-06T03:47:41.714233Z","iopub.execute_input":"2026-09-06T03:47:41.714597Z","iopub.status.idle":"2026-09-06T03:47:41.722075Z","shell.execute_reply.started":"2026-09-06T03:47:41.714571Z","shell.execute_reply":"2026-09-06T03:47:41.721163Z"}},"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-06T03:47:41.723215Z","iopub.execute_input":"2026-09-06T03:47:41.723478Z","iopub.status.idle":"2026-09-06T03:47:47.270891Z","shell.execute_reply.started":"2026-09-06T03:47:41.723456Z","shell.execute_reply":"2026-09-06T03:47:47.269900Z"},"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-06T03:47:47.272067Z","iopub.execute_input":"2026-09-06T03:47:47.272310Z","iopub.status.idle":"2026-09-06T03:47:47.278565Z","shell.execute_reply.started":"2026-09-06T03:47:47.272289Z","shell.execute_reply":"2026-09-06T03:47:47.277519Z"}},"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-06T03:47:47.285804Z","iopub.execute_input":"2026-09-06T03:47:47.286283Z","iopub.status.idle":"2026-09-06T03:47:47.292761Z","shell.execute_reply.started":"2026-09-06T03:47:47.286241Z","shell.execute_reply":"2026-09-06T03:47:47.291918Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_inceptionv3.reset_states()\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true},"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},"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages = tf.image.resize(images, (299, 299))\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:57:51.118179Z","iopub.execute_input":"2026-09-06T03:57:51.119025Z","iopub.status.idle":"2026-09-06T03:57:51.342664Z","shell.execute_reply.started":"2026-09-06T03:57:51.118992Z","shell.execute_reply":"2026-09-06T03:57:51.341631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:58:14.173993Z","iopub.execute_input":"2026-09-06T03:58:14.174759Z","iopub.status.idle":"2026-09-06T03:58:14.217567Z","shell.execute_reply.started":"2026-09-06T03:58:14.174728Z","shell.execute_reply":"2026-09-06T03:58:14.216617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T03:57:38.460591Z","iopub.execute_input":"2026-09-06T03:57:38.461462Z","iopub.status.idle":"2026-09-06T03:57:38.465491Z","shell.execute_reply.started":"2026-09-06T03:57:38.461425Z","shell.execute_reply":"2026-09-06T03:57:38.464427Z"}},"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-06T03:58:28.397927Z","iopub.execute_input":"2026-09-06T03:58:28.398290Z","iopub.status.idle":"2026-09-06T03:58:31.132733Z","shell.execute_reply.started":"2026-09-06T03:58:28.398260Z","shell.execute_reply":"2026-09-06T03:58:31.131912Z"}},"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-06T03:54:12.778880Z","iopub.execute_input":"2026-09-06T03:54:12.779815Z","iopub.status.idle":"2026-09-06T03:54:12.786133Z","shell.execute_reply.started":"2026-09-06T03:54:12.779781Z","shell.execute_reply":"2026-09-06T03:54:12.785152Z"}},"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-06T03:59:03.615122Z","iopub.execute_input":"2026-09-06T03:59:03.615955Z","iopub.status.idle":"2026-09-06T03:59:03.734561Z","shell.execute_reply.started":"2026-09-06T03:59:03.615924Z","shell.execute_reply":"2026-09-06T03:59:03.733857Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nlabels = [\"Cat\" if p[0] < 0.5 else \"Dog\" for p in probs]\n\nplt.figure(figsize=(12,4))\nfor i in range(5):\n    plt.subplot(1,5,i+1)\n    plt.imshow(images_to_predict[i])\n    plt.title(labels[i])\n    plt.axis(\"off\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-06T04:03:40.817213Z","iopub.execute_input":"2026-09-06T04:03:40.818013Z","iopub.status.idle":"2026-09-06T04:03:41.281487Z","shell.execute_reply.started":"2026-09-06T04:03:40.817976Z","shell.execute_reply":"2026-09-06T04:03:41.280589Z"}},"outputs":[],"execution_count":null}]}