{"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":"2024-02-08T01:25:14.599638Z","iopub.execute_input":"2024-02-08T01:25:14.600071Z","iopub.status.idle":"2024-02-08T01:25:14.960748Z","shell.execute_reply.started":"2024-02-08T01:25:14.600024Z","shell.execute_reply":"2024-02-08T01:25:14.959811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python --version","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:25:14.963008Z","iopub.execute_input":"2024-02-08T01:25:14.963517Z","iopub.status.idle":"2024-02-08T01:25:15.916738Z","shell.execute_reply.started":"2024-02-08T01:25:14.963480Z","shell.execute_reply":"2024-02-08T01:25:15.915694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nprint('Tensorflow ' + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:25:15.918225Z","iopub.execute_input":"2024-02-08T01:25:15.918547Z","iopub.status.idle":"2024-02-08T01:25:28.349254Z","shell.execute_reply.started":"2024-02-08T01:25:15.918518Z","shell.execute_reply":"2024-02-08T01:25:28.348243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-08T01:25:28.350581Z","iopub.execute_input":"2024-02-08T01:25:28.351160Z","iopub.status.idle":"2024-02-08T01:25:42.465302Z","shell.execute_reply.started":"2024-02-08T01:25:28.351130Z","shell.execute_reply":"2024-02-08T01:25:42.464456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\ntrain_folder = 'train/'\n\n# define location of dataset\nfolder = train_folder\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":"2024-02-08T01:25:42.467783Z","iopub.execute_input":"2024-02-08T01:25:42.468100Z","iopub.status.idle":"2024-02-08T01:25:43.683138Z","shell.execute_reply.started":"2024-02-08T01:25:42.468074Z","shell.execute_reply":"2024-02-08T01:25:43.682254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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":"2024-02-08T01:25:43.684224Z","iopub.execute_input":"2024-02-08T01:25:43.684474Z","iopub.status.idle":"2024-02-08T01:25:44.869449Z","shell.execute_reply.started":"2024-02-08T01:25:43.684451Z","shell.execute_reply":"2024-02-08T01:25:44.868488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:25:44.870732Z","iopub.execute_input":"2024-02-08T01:25:44.871092Z","iopub.status.idle":"2024-02-08T01:25:44.877123Z","shell.execute_reply.started":"2024-02-08T01:25:44.871056Z","shell.execute_reply":"2024-02-08T01:25:44.876240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-08T01:25:44.878430Z","iopub.execute_input":"2024-02-08T01:25:44.878799Z","iopub.status.idle":"2024-02-08T01:25:44.888030Z","shell.execute_reply.started":"2024-02-08T01:25:44.878765Z","shell.execute_reply":"2024-02-08T01:25:44.887099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n#for file in listdir(folder[:10_000]): # select 10_000 images\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-02-08T01:25:44.889271Z","iopub.execute_input":"2024-02-08T01:25:44.889651Z","iopub.status.idle":"2024-02-08T01:27:11.933009Z","shell.execute_reply.started":"2024-02-08T01:25:44.889602Z","shell.execute_reply":"2024-02-08T01:27:11.931910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:27:11.936212Z","iopub.execute_input":"2024-02-08T01:27:11.936590Z","iopub.status.idle":"2024-02-08T01:27:13.319934Z","shell.execute_reply.started":"2024-02-08T01:27:11.936561Z","shell.execute_reply":"2024-02-08T01:27:13.318701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')\nprint(photos.shape, labels.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:28:07.344252Z","iopub.execute_input":"2024-02-08T01:28:07.345047Z","iopub.status.idle":"2024-02-08T01:28:55.313685Z","shell.execute_reply.started":"2024-02-08T01:28:07.345007Z","shell.execute_reply":"2024-02-08T01:28:55.312685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directories\nimport os\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tos.makedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:28:55.315423Z","iopub.execute_input":"2024-02-08T01:28:55.315768Z","iopub.status.idle":"2024-02-08T01:28:55.321584Z","shell.execute_reply.started":"2024-02-08T01:28:55.315740Z","shell.execute_reply":"2024-02-08T01:28:55.320703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:28:55.322841Z","iopub.execute_input":"2024-02-08T01:28:55.323144Z","iopub.status.idle":"2024-02-08T01:29:11.059225Z","shell.execute_reply.started":"2024-02-08T01:28:55.323120Z","shell.execute_reply":"2024-02-08T01:29:11.058054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:29:11.062010Z","iopub.execute_input":"2024-02-08T01:29:11.062443Z","iopub.status.idle":"2024-02-08T01:29:12.254069Z","shell.execute_reply.started":"2024-02-08T01:29:11.062404Z","shell.execute_reply":"2024-02-08T01:29:12.252936Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:29:12.255688Z","iopub.execute_input":"2024-02-08T01:29:12.256054Z","iopub.status.idle":"2024-02-08T01:29:13.344114Z","shell.execute_reply.started":"2024-02-08T01:29:12.256018Z","shell.execute_reply":"2024-02-08T01:29:13.343000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"!ls test1\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T03:01:48.472037Z","iopub.execute_input":"2024-01-13T03:01:48.473336Z","iopub.status.idle":"2024-01-13T03:01:49.583287Z","shell.execute_reply.started":"2024-01-13T03:01:48.47329Z","shell.execute_reply":"2024-01-13T03:01:49.58225Z"}}},{"cell_type":"markdown","source":"# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\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\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(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=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)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:29:13.345821Z","iopub.execute_input":"2024-02-08T01:29:13.346677Z","iopub.status.idle":"2024-02-08T01:29:23.020137Z","shell.execute_reply.started":"2024-02-08T01:29:13.346615Z","shell.execute_reply":"2024-02-08T01:29:23.019065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:29:23.021477Z","iopub.execute_input":"2024-02-08T01:29:23.022221Z","iopub.status.idle":"2024-02-08T01:29:37.187305Z","shell.execute_reply.started":"2024-02-08T01:29:23.022177Z","shell.execute_reply":"2024-02-08T01:29:37.186014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:29:37.188777Z","iopub.execute_input":"2024-02-08T01:29:37.189085Z","iopub.status.idle":"2024-02-08T01:29:37.205757Z","shell.execute_reply.started":"2024-02-08T01:29:37.189058Z","shell.execute_reply":"2024-02-08T01:29:37.204643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1# VGG16","metadata":{}},{"cell_type":"code","source":"import 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    # 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[:15]:\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.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# 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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    # create data generator\n    datagen = 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    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=15, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:43:17.419436Z","iopub.execute_input":"2024-02-08T01:43:17.419837Z","iopub.status.idle":"2024-02-08T01:43:17.436260Z","shell.execute_reply.started":"2024-02-08T01:43:17.419802Z","shell.execute_reply":"2024-02-08T01:43:17.435382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:43:18.216913Z","iopub.execute_input":"2024-02-08T01:43:18.217667Z","iopub.status.idle":"2024-02-08T01:43:18.570444Z","shell.execute_reply.started":"2024-02-08T01:43:18.217612Z","shell.execute_reply":"2024-02-08T01:43:18.569673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:43:19.305008Z","iopub.execute_input":"2024-02-08T01:43:19.305894Z","iopub.status.idle":"2024-02-08T01:43:19.357939Z","shell.execute_reply.started":"2024-02-08T01:43:19.305856Z","shell.execute_reply":"2024-02-08T01:43:19.357070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T01:43:20.538293Z","iopub.execute_input":"2024-02-08T01:43:20.539365Z","iopub.status.idle":"2024-02-08T03:19:40.695718Z","shell.execute_reply.started":"2024-02-08T01:43:20.539323Z","shell.execute_reply":"2024-02-08T03:19:40.694796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2# VGG19","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg19 import VGG19\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_1():\n    # load model\n    model_1 = VGG19(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model_1.layers[:15]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model_1.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_1 = Model(inputs=model_1.inputs, outputs=output)  # Corrected typo here\n    # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model_1.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model_1\n\n# plot diagnostic learning curves\ndef summarize_diagnostics_1(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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness_1():\n    # define model\n    model_1 = define_model_1()\n    # create data generator\n    datagen = 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    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model_1.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=15, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model_1.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics_1(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T03:26:10.739005Z","iopub.execute_input":"2024-02-08T03:26:10.740244Z","iopub.status.idle":"2024-02-08T03:26:10.758223Z","shell.execute_reply.started":"2024-02-08T03:26:10.740201Z","shell.execute_reply":"2024-02-08T03:26:10.757140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_1 = define_model_1()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T03:26:16.208686Z","iopub.execute_input":"2024-02-08T03:26:16.209670Z","iopub.status.idle":"2024-02-08T03:26:17.149326Z","shell.execute_reply.started":"2024-02-08T03:26:16.209632Z","shell.execute_reply":"2024-02-08T03:26:17.148443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_1.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T03:26:21.131818Z","iopub.execute_input":"2024-02-08T03:26:21.132219Z","iopub.status.idle":"2024-02-08T03:26:21.193084Z","shell.execute_reply.started":"2024-02-08T03:26:21.132187Z","shell.execute_reply":"2024-02-08T03:26:21.192091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness_1()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T03:26:27.803012Z","iopub.execute_input":"2024-02-08T03:26:27.803857Z","iopub.status.idle":"2024-02-08T05:04:09.008996Z","shell.execute_reply.started":"2024-02-08T03:26:27.803817Z","shell.execute_reply":"2024-02-08T05:04:09.007798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3# ResNet50","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.resnet50 import ResNet50\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_2():\n    # load model\n    model_2 = ResNet50(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model_2.layers[:15]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model_2.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_2 = Model(inputs=model_2.inputs, outputs=output)  # Corrected typo here\n    # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model_2.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model_2\n\n# plot diagnostic learning curves\ndef summarize_diagnostics_2(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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness_2():\n    # define model\n    model_2 = define_model_2()\n    # create data generator\n    datagen = 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    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model_2.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=15, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model_2.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics_2(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T05:05:43.953855Z","iopub.execute_input":"2024-02-08T05:05:43.954554Z","iopub.status.idle":"2024-02-08T05:05:43.969812Z","shell.execute_reply.started":"2024-02-08T05:05:43.954517Z","shell.execute_reply":"2024-02-08T05:05:43.968851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2 = define_model_2()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T05:05:50.662943Z","iopub.execute_input":"2024-02-08T05:05:50.663855Z","iopub.status.idle":"2024-02-08T05:05:53.207304Z","shell.execute_reply.started":"2024-02-08T05:05:50.663818Z","shell.execute_reply":"2024-02-08T05:05:53.206449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T05:06:08.400857Z","iopub.execute_input":"2024-02-08T05:06:08.401636Z","iopub.status.idle":"2024-02-08T05:06:08.871799Z","shell.execute_reply.started":"2024-02-08T05:06:08.401593Z","shell.execute_reply":"2024-02-08T05:06:08.870806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness_2()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T05:06:27.977102Z","iopub.execute_input":"2024-02-08T05:06:27.978101Z","iopub.status.idle":"2024-02-08T06:43:18.564582Z","shell.execute_reply.started":"2024-02-08T05:06:27.978058Z","shell.execute_reply":"2024-02-08T06:43:18.563454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4# Xception","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\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\n\n# define cnn model\ndef define_model_3():\n    # load model\n    base_model = Xception(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in base_model.layers[:15]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(base_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_3 = Model(inputs=base_model.input, outputs=output)\n    # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model_3.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model_3\n\n# plot diagnostic learning curves\ndef summarize_diagnostics_3(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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness_3():\n    # define model\n    model_3 = define_model_3()\n    # create data generator\n    datagen = 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    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model_3.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=15, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model_3.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics_3(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T06:51:05.840528Z","iopub.execute_input":"2024-02-08T06:51:05.840990Z","iopub.status.idle":"2024-02-08T06:51:05.858106Z","shell.execute_reply.started":"2024-02-08T06:51:05.840957Z","shell.execute_reply":"2024-02-08T06:51:05.857037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_3 = define_model_3()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T06:52:13.613898Z","iopub.execute_input":"2024-02-08T06:52:13.614868Z","iopub.status.idle":"2024-02-08T06:52:15.163614Z","shell.execute_reply.started":"2024-02-08T06:52:13.614829Z","shell.execute_reply":"2024-02-08T06:52:15.162805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_3.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T06:52:18.384221Z","iopub.execute_input":"2024-02-08T06:52:18.385008Z","iopub.status.idle":"2024-02-08T06:52:18.751068Z","shell.execute_reply.started":"2024-02-08T06:52:18.384971Z","shell.execute_reply":"2024-02-08T06:52:18.750022Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness_3()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T06:52:55.807463Z","iopub.execute_input":"2024-02-08T06:52:55.808408Z","iopub.status.idle":"2024-02-08T08:31:27.501505Z","shell.execute_reply.started":"2024-02-08T06:52:55.808369Z","shell.execute_reply":"2024-02-08T08:31:27.500676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 5# MobileNet","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.mobilenet import MobileNet\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_4():\n    # load model\n    model_4 = MobileNet(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model_4.layers[:15]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model_4.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_4 = Model(inputs=model_4.inputs, outputs=output)  # Corrected typo here\n    # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model_4.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model_4\n\n# plot diagnostic learning curves\ndef summarize_diagnostics_4(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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness_4():\n    # define model\n    model_4 = define_model_4()\n    # create data generator\n    datagen = 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    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model_4.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=15, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model_4.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics_1(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:36:54.064780Z","iopub.execute_input":"2024-02-08T08:36:54.065171Z","iopub.status.idle":"2024-02-08T08:36:54.080936Z","shell.execute_reply.started":"2024-02-08T08:36:54.065140Z","shell.execute_reply":"2024-02-08T08:36:54.079995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_4 = define_model_4()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:37:03.575437Z","iopub.execute_input":"2024-02-08T08:37:03.576461Z","iopub.status.idle":"2024-02-08T08:37:04.825577Z","shell.execute_reply.started":"2024-02-08T08:37:03.576419Z","shell.execute_reply":"2024-02-08T08:37:04.824809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_4.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:37:18.719947Z","iopub.execute_input":"2024-02-08T08:37:18.720737Z","iopub.status.idle":"2024-02-08T08:37:18.914119Z","shell.execute_reply.started":"2024-02-08T08:37:18.720704Z","shell.execute_reply":"2024-02-08T08:37:18.913198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness_4()","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:37:30.056032Z","iopub.execute_input":"2024-02-08T08:37:30.057329Z","iopub.status.idle":"2024-02-08T10:12:17.649946Z","shell.execute_reply.started":"2024-02-08T08:37:30.057271Z","shell.execute_reply":"2024-02-08T10:12:17.649003Z"},"trusted":true},"execution_count":null,"outputs":[]}]}