{"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-01-16T17:21:55.930491Z","iopub.execute_input":"2026-01-16T17:21:55.93088Z","iopub.status.idle":"2026-01-16T17:21:55.939129Z","shell.execute_reply.started":"2026-01-16T17:21:55.93084Z","shell.execute_reply":"2026-01-16T17:21:55.938393Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:21:55.941189Z","iopub.execute_input":"2026-01-16T17:21:55.941496Z","iopub.status.idle":"2026-01-16T17:21:56.959224Z","shell.execute_reply.started":"2026-01-16T17:21:55.941473Z","shell.execute_reply":"2026-01-16T17:21:56.958041Z"}},"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-01-16T17:21:56.960789Z","iopub.execute_input":"2026-01-16T17:21:56.961057Z","iopub.status.idle":"2026-01-16T17:22:05.704781Z","shell.execute_reply.started":"2026-01-16T17:21:56.961034Z","shell.execute_reply":"2026-01-16T17:22:05.703836Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"!ls train","metadata":{"execution":{"iopub.status.busy":"2024-01-08T06:57:18.293035Z","iopub.execute_input":"2024-01-08T06:57:18.293457Z","iopub.status.idle":"2024-01-08T06:57:19.311078Z","shell.execute_reply.started":"2024-01-08T06:57:18.293422Z","shell.execute_reply":"2024-01-08T06:57:19.309969Z"}}},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:05.706557Z","iopub.execute_input":"2026-01-16T17:22:05.706814Z","iopub.status.idle":"2026-01-16T17:22:06.709273Z","shell.execute_reply.started":"2026-01-16T17:22:05.706792Z","shell.execute_reply":"2026-01-16T17:22:06.708117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:06.710935Z","iopub.execute_input":"2026-01-16T17:22:06.711204Z","iopub.status.idle":"2026-01-16T17:22:07.835415Z","shell.execute_reply.started":"2026-01-16T17:22:06.711181Z","shell.execute_reply":"2026-01-16T17:22:07.834424Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:07.836842Z","iopub.execute_input":"2026-01-16T17:22:07.837138Z","iopub.status.idle":"2026-01-16T17:22:09.045385Z","shell.execute_reply.started":"2026-01-16T17:22:07.83711Z","shell.execute_reply":"2026-01-16T17:22:09.044282Z"}},"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-01-16T17:22:09.047128Z","iopub.execute_input":"2026-01-16T17:22:09.047518Z","iopub.status.idle":"2026-01-16T17:22:10.045126Z","shell.execute_reply.started":"2026-01-16T17:22:09.047483Z","shell.execute_reply":"2026-01-16T17:22:10.044195Z"},"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-01-16T17:22:10.046551Z","iopub.execute_input":"2026-01-16T17:22:10.046919Z","iopub.status.idle":"2026-01-16T17:22:10.902232Z","shell.execute_reply.started":"2026-01-16T17:22:10.046885Z","shell.execute_reply":"2026-01-16T17:22:10.901437Z"},"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-01-16T17:22:10.904799Z","iopub.execute_input":"2026-01-16T17:22:10.90507Z","iopub.status.idle":"2026-01-16T17:22:10.909927Z","shell.execute_reply.started":"2026-01-16T17:22:10.905048Z","shell.execute_reply":"2026-01-16T17:22:10.909076Z"}},"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-01-16T17:22:10.911114Z","iopub.execute_input":"2026-01-16T17:22:10.911744Z","iopub.status.idle":"2026-01-16T17:22:10.919786Z","shell.execute_reply.started":"2026-01-16T17:22:10.911713Z","shell.execute_reply":"2026-01-16T17:22:10.91915Z"},"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":"\n# 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-01-16T17:22:10.9209Z","iopub.execute_input":"2026-01-16T17:22:10.921201Z","iopub.status.idle":"2026-01-16T17:22:10.930837Z","shell.execute_reply.started":"2026-01-16T17:22:10.921173Z","shell.execute_reply":"2026-01-16T17:22:10.930068Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] ##test-->validate\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-01-16T17:22:10.93185Z","iopub.execute_input":"2026-01-16T17:22:10.932724Z","iopub.status.idle":"2026-01-16T17:22:10.942788Z","shell.execute_reply.started":"2026-01-16T17:22:10.932691Z","shell.execute_reply":"2026-01-16T17:22:10.942002Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:10.943984Z","iopub.execute_input":"2026-01-16T17:22:10.94455Z","iopub.status.idle":"2026-01-16T17:22:11.954318Z","shell.execute_reply.started":"2026-01-16T17:22:10.94452Z","shell.execute_reply":"2026-01-16T17:22:11.953174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:11.955935Z","iopub.execute_input":"2026-01-16T17:22:11.956223Z","iopub.status.idle":"2026-01-16T17:22:12.957555Z","shell.execute_reply.started":"2026-01-16T17:22:11.956198Z","shell.execute_reply":"2026-01-16T17:22:12.956599Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:12.958903Z","iopub.execute_input":"2026-01-16T17:22:12.959193Z","iopub.status.idle":"2026-01-16T17:22:13.968551Z","shell.execute_reply.started":"2026-01-16T17:22:12.959167Z","shell.execute_reply":"2026-01-16T17:22:13.96748Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:13.970164Z","iopub.execute_input":"2026-01-16T17:22:13.971001Z","iopub.status.idle":"2026-01-16T17:22:14.990955Z","shell.execute_reply.started":"2026-01-16T17:22:13.970962Z","shell.execute_reply":"2026-01-16T17:22:14.989418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:22:14.992952Z","iopub.execute_input":"2026-01-16T17:22:14.993467Z","iopub.status.idle":"2026-01-16T17:22:17.891281Z","shell.execute_reply.started":"2026-01-16T17:22:14.99342Z","shell.execute_reply":"2026-01-16T17:22:17.890554Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print (src)\nprint (dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:17.892378Z","iopub.execute_input":"2026-01-16T17:22:17.892633Z","iopub.status.idle":"2026-01-16T17:22:17.897071Z","shell.execute_reply.started":"2026-01-16T17:22:17.892611Z","shell.execute_reply":"2026-01-16T17:22:17.896241Z"}},"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-01-16T17:22:17.898184Z","iopub.execute_input":"2026-01-16T17:22:17.898769Z","iopub.status.idle":"2026-01-16T17:22:20.063705Z","shell.execute_reply.started":"2026-01-16T17:22:17.898738Z","shell.execute_reply":"2026-01-16T17:22:20.062392Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!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-01-16T17:22:20.065194Z","iopub.execute_input":"2026-01-16T17:22:20.065504Z","iopub.status.idle":"2026-01-16T17:22:22.159056Z","shell.execute_reply.started":"2026-01-16T17:22:20.065476Z","shell.execute_reply":"2026-01-16T17:22:22.157955Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:22:22.160661Z","iopub.execute_input":"2026-01-16T17:22:22.161587Z","iopub.status.idle":"2026-01-16T17:22:30.361941Z","shell.execute_reply.started":"2026-01-16T17:22:22.161549Z","shell.execute_reply":"2026-01-16T17:22:30.360756Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:22:30.363313Z","iopub.execute_input":"2026-01-16T17:22:30.363574Z","iopub.status.idle":"2026-01-16T17:22:30.368002Z","shell.execute_reply.started":"2026-01-16T17:22:30.36355Z","shell.execute_reply":"2026-01-16T17:22:30.367138Z"},"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":"markdown","source":"## https://keras.io/api/applications/","metadata":{}},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.xception import Xception\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","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:22:30.368946Z","iopub.execute_input":"2026-01-16T17:22:30.36915Z","iopub.status.idle":"2026-01-16T17:22:30.383222Z","shell.execute_reply.started":"2026-01-16T17:22:30.369131Z","shell.execute_reply":"2026-01-16T17:22:30.382606Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"xcep_model = Xception(include_top=False, input_shape=(299, 299, 3))\nxcep_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-27T04:11:23.494572Z","iopub.execute_input":"2024-01-27T04:11:23.495217Z","iopub.status.idle":"2024-01-27T04:11:26.579883Z","shell.execute_reply.started":"2024-01-27T04:11:23.495182Z","shell.execute_reply":"2024-01-27T04:11:26.578335Z"}}},{"cell_type":"code","source":"#define cnn model\ndef define_model_1():\n    # 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    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\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\n\nmodel_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:30.388558Z","iopub.execute_input":"2026-01-16T17:22:30.388861Z","iopub.status.idle":"2026-01-16T17:22:30.781769Z","shell.execute_reply.started":"2026-01-16T17:22:30.388834Z","shell.execute_reply":"2026-01-16T17:22:30.776915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:30.782903Z","iopub.execute_input":"2026-01-16T17:22:30.783144Z","iopub.status.idle":"2026-01-16T17:22:30.788512Z","shell.execute_reply.started":"2026-01-16T17:22:30.783117Z","shell.execute_reply":"2026-01-16T17:22:30.787723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model\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))\n\t# learning curves\n\tsummarize_diagnostics(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:30.789483Z","iopub.execute_input":"2026-01-16T17:22:30.7897Z","iopub.status.idle":"2026-01-16T17:22:30.83754Z","shell.execute_reply.started":"2026-01-16T17:22:30.789679Z","shell.execute_reply":"2026-01-16T17:22:30.836622Z"}},"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-01-16T17:22:30.838573Z","iopub.execute_input":"2026-01-16T17:22:30.838827Z","iopub.status.idle":"2026-01-16T17:22:31.222795Z","shell.execute_reply.started":"2026-01-16T17:22:30.838805Z","shell.execute_reply":"2026-01-16T17:22:31.222152Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\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-01-16T17:22:31.223697Z","iopub.execute_input":"2026-01-16T17:22:31.223922Z","iopub.status.idle":"2026-01-16T17:22:31.872706Z","shell.execute_reply.started":"2026-01-16T17:22:31.223902Z","shell.execute_reply":"2026-01-16T17:22:31.872028Z"}},"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-01-16T17:22:31.873892Z","iopub.execute_input":"2026-01-16T17:22:31.874547Z","iopub.status.idle":"2026-01-16T17:22:31.880822Z","shell.execute_reply.started":"2026-01-16T17:22:31.874514Z","shell.execute_reply":"2026-01-16T17:22:31.880015Z"}},"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-01-16T17:22:31.881975Z","iopub.execute_input":"2026-01-16T17:22:31.882207Z","iopub.status.idle":"2026-01-16T17:22:31.892462Z","shell.execute_reply.started":"2026-01-16T17:22:31.882186Z","shell.execute_reply":"2026-01-16T17:22:31.891671Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Flatten\nfrom livelossplot import PlotLossesKeras\n\n# Define image dimensions\nimage_height = 150  # Set your desired image height\nimage_width = 150   # Set your desired image width\n\n# Define the model\nmodel_1 = Sequential()\nmodel_1.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(image_height, image_width, 3)))\nmodel_1.add(Flatten())\nmodel_1.add(Dense(2, activation='softmax'))\n\n# Compile the model\nmodel_1.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Define the data generators\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_it = train_datagen.flow_from_directory(\n    '/kaggle/working/dataset_dogs_vs_cats/train',  # Update this path\n    target_size=(image_height, image_width),\n    batch_size=32,  # Set your desired batch size\n    class_mode='categorical'\n)\n\ntest_it = test_datagen.flow_from_directory(\n    '/kaggle/working/dataset_dogs_vs_cats/test',  # Update this path\n    target_size=(image_height, image_width),\n    batch_size=32,  # Set your desired batch size\n    class_mode='categorical'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:31.893448Z","iopub.execute_input":"2026-01-16T17:22:31.893835Z","iopub.status.idle":"2026-01-16T17:22:32.262502Z","shell.execute_reply.started":"2026-01-16T17:22:31.893801Z","shell.execute_reply":"2026-01-16T17:22:32.261634Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Check the shape of a batch of data and labels\nx_batch, y_batch = next(train_it)\nprint(\"Data shape:\", x_batch.shape)  # Should be (batch_size, image_height, image_width, channels)\nprint(\"Labels shape:\", y_batch.shape)  # Should be (batch_size, num_classes)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:22:32.263672Z","iopub.execute_input":"2026-01-16T17:22:32.264267Z","iopub.status.idle":"2026-01-16T17:22:32.320246Z","shell.execute_reply.started":"2026-01-16T17:22:32.264234Z","shell.execute_reply":"2026-01-16T17:22:32.31949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history_1 = model_1.fit(\n    train_it, steps_per_epoch=len(train_it),\n    validation_data=test_it,\n    validation_steps=len(test_it),\n    epochs=20, verbose=1,\n    callbacks=[PlotLossesKeras()]\n)","metadata":{"trusted":true,"execution":{"execution_failed":"2026-01-16T19:17:03.106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_it.class_indices)\nprint(test_it.class_indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:34:07.880013Z","iopub.execute_input":"2026-01-16T17:34:07.880263Z","iopub.status.idle":"2026-01-16T17:34:07.885161Z","shell.execute_reply.started":"2026-01-16T17:34:07.880241Z","shell.execute_reply":"2026-01-16T17:34:07.884273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Image Augmentatioin\n\nfrom keras.preprocessing.image import ImageDataGenerator\n# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    # fill_mode='nearest',\n    fill_mode='reflect',\n)\n# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:07.886336Z","iopub.execute_input":"2026-01-16T17:34:07.886679Z","iopub.status.idle":"2026-01-16T17:34:08.552518Z","shell.execute_reply.started":"2026-01-16T17:34:07.88665Z","shell.execute_reply":"2026-01-16T17:34:08.551812Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = train_it.__next__()\nprint(images.shape, labels.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:34:08.553668Z","iopub.execute_input":"2026-01-16T17:34:08.554419Z","iopub.status.idle":"2026-01-16T17:34:09.250032Z","shell.execute_reply.started":"2026-01-16T17:34:08.554383Z","shell.execute_reply":"2026-01-16T17:34:09.249046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T17:34:09.25107Z","iopub.execute_input":"2026-01-16T17:34:09.25137Z","iopub.status.idle":"2026-01-16T17:34:09.257659Z","shell.execute_reply.started":"2026-01-16T17:34:09.251319Z","shell.execute_reply":"2026-01-16T17:34:09.256558Z"}},"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-01-16T17:34:09.258944Z","iopub.execute_input":"2026-01-16T17:34:09.260271Z","iopub.status.idle":"2026-01-16T17:34:09.270824Z","shell.execute_reply.started":"2026-01-16T17:34:09.260245Z","shell.execute_reply":"2026-01-16T17:34:09.269837Z"}},"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-01-16T17:34:09.272481Z","iopub.execute_input":"2026-01-16T17:34:09.272865Z","iopub.status.idle":"2026-01-16T17:34:11.113916Z","shell.execute_reply.started":"2026-01-16T17:34:09.272829Z","shell.execute_reply":"2026-01-16T17:34:11.113051Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\nmodel = VGG16(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:11.115062Z","iopub.execute_input":"2026-01-16T17:34:11.11538Z","iopub.status.idle":"2026-01-16T17:34:11.474744Z","shell.execute_reply.started":"2026-01-16T17:34:11.115351Z","shell.execute_reply":"2026-01-16T17:34:11.473912Z"},"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,"execution":{"iopub.status.busy":"2026-01-16T17:34:11.475812Z","iopub.execute_input":"2026-01-16T17:34:11.476065Z","iopub.status.idle":"2026-01-16T17:34:11.48078Z","shell.execute_reply.started":"2026-01-16T17:34:11.476043Z","shell.execute_reply":"2026-01-16T17:34:11.479959Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# mark loaded layers as not trainable\nfor index, layer in enumerate(model.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:11.481858Z","iopub.execute_input":"2026-01-16T17:34:11.482092Z","iopub.status.idle":"2026-01-16T17:34:11.494435Z","shell.execute_reply.started":"2026-01-16T17:34:11.482073Z","shell.execute_reply":"2026-01-16T17:34:11.493663Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:11.495426Z","iopub.execute_input":"2026-01-16T17:34:11.495659Z","iopub.status.idle":"2026-01-16T17:34:11.515989Z","shell.execute_reply.started":"2026-01-16T17:34:11.495639Z","shell.execute_reply":"2026-01-16T17:34:11.515382Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model.summary()","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:11.517005Z","iopub.execute_input":"2026-01-16T17:34:11.517222Z","iopub.status.idle":"2026-01-16T17:34:11.591035Z","shell.execute_reply.started":"2026-01-16T17:34:11.517203Z","shell.execute_reply":"2026-01-16T17:34:11.590017Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":" # fit model\nmy_model.reset_states()\nhistory = my_model.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=10, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\nsummarize_diagnostics(history)\n\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2026-01-16T17:34:11.597813Z","iopub.execute_input":"2026-01-16T17:34:11.598049Z","iopub.status.idle":"2026-01-16T18:23:29.420116Z","shell.execute_reply.started":"2026-01-16T17:34:11.598028Z","shell.execute_reply":"2026-01-16T18:23:29.418469Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.42109Z","iopub.status.idle":"2026-01-16T18:23:29.421469Z","shell.execute_reply.started":"2026-01-16T18:23:29.421279Z","shell.execute_reply":"2026-01-16T18:23:29.421296Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"# make a prediction for a new image.\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.423278Z","iopub.status.idle":"2026-01-16T18:23:29.423653Z","shell.execute_reply.started":"2026-01-16T18:23:29.423503Z","shell.execute_reply":"2026-01-16T18:23:29.423519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img\n\n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.424561Z","iopub.status.idle":"2026-01-16T18:23:29.424863Z","shell.execute_reply.started":"2026-01-16T18:23:29.424717Z","shell.execute_reply":"2026-01-16T18:23:29.424731Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Create Transfer Learning**","metadata":{}},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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-01-16T18:23:29.426188Z","iopub.status.idle":"2026-01-16T18:23:29.426486Z","shell.execute_reply.started":"2026-01-16T18:23:29.426323Z","shell.execute_reply":"2026-01-16T18:23:29.426358Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# vgg16 model used for transfer learning on the dogs and cats dataset\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():\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\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\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=10, verbose=1)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.427726Z","iopub.status.idle":"2026-01-16T18:23:29.428009Z","shell.execute_reply.started":"2026-01-16T18:23:29.427873Z","shell.execute_reply":"2026-01-16T18:23:29.427887Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.428932Z","iopub.status.idle":"2026-01-16T18:23:29.429189Z","shell.execute_reply.started":"2026-01-16T18:23:29.429061Z","shell.execute_reply":"2026-01-16T18:23:29.429073Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score\n\n# Ensure both lists have the same length\ny_true = [0, 0, 0, 0, 1, 1, 1, 1]  # 8 elements\ny_pred = [0, 1, 0, 0, 1, 1, 1, 1]  # 8 elements (truncated to match y_true)\n\n# Calculate accuracy\naccuracy = accuracy_score(y_true, y_pred)\naccuracy_norm = accuracy_score(y_true, y_pred, normalize=False)\n\nprint(accuracy, accuracy_norm)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.430175Z","iopub.status.idle":"2026-01-16T18:23:29.431069Z","shell.execute_reply.started":"2026-01-16T18:23:29.430825Z","shell.execute_reply":"2026-01-16T18:23:29.430856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report\nprint(classification_report(y_true,y_pred, target_name=my_labels))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-16T18:23:29.432306Z","iopub.status.idle":"2026-01-16T18:23:29.4326Z","shell.execute_reply.started":"2026-01-16T18:23:29.432471Z","shell.execute_reply":"2026-01-16T18:23:29.432484Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}