{"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":"gpu","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-06T05:33:16.548201Z","iopub.execute_input":"2024-02-06T05:33:16.548827Z","iopub.status.idle":"2024-02-06T05:33:16.559328Z","shell.execute_reply.started":"2024-02-06T05:33:16.548790Z","shell.execute_reply":"2024-02-06T05:33:16.558343Z"},"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-06T05:33:16.561448Z","iopub.execute_input":"2024-02-06T05:33:16.561713Z","iopub.status.idle":"2024-02-06T05:33:27.296996Z","shell.execute_reply.started":"2024-02-06T05:33:16.561689Z","shell.execute_reply":"2024-02-06T05:33:27.296066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-06T05:33:27.298182Z","iopub.execute_input":"2024-02-06T05:33:27.298505Z","iopub.status.idle":"2024-02-06T05:33:28.550916Z","shell.execute_reply.started":"2024-02-06T05:33:27.298475Z","shell.execute_reply":"2024-02-06T05:33:28.549944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-06T05:33:28.552110Z","iopub.execute_input":"2024-02-06T05:33:28.552421Z","iopub.status.idle":"2024-02-06T05:33:29.608880Z","shell.execute_reply.started":"2024-02-06T05:33:28.552393Z","shell.execute_reply":"2024-02-06T05:33:29.607978Z"},"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 os import makedirs\nfrom numpy import asarray\nfrom numpy import save\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:29.611694Z","iopub.execute_input":"2024-02-06T05:33:29.612051Z","iopub.status.idle":"2024-02-06T05:33:29.617904Z","shell.execute_reply.started":"2024-02-06T05:33:29.612006Z","shell.execute_reply":"2024-02-06T05:33:29.617057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:29.619283Z","iopub.execute_input":"2024-02-06T05:33:29.619539Z","iopub.status.idle":"2024-02-06T05:33:29.632247Z","shell.execute_reply.started":"2024-02-06T05:33:29.619514Z","shell.execute_reply":"2024-02-06T05:33:29.631548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-06T05:33:29.633157Z","iopub.execute_input":"2024-02-06T05:33:29.633429Z","iopub.status.idle":"2024-02-06T05:33:33.156454Z","shell.execute_reply.started":"2024-02-06T05:33:29.633405Z","shell.execute_reply":"2024-02-06T05:33:33.155607Z"},"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-06T05:33:33.157794Z","iopub.execute_input":"2024-02-06T05:33:33.158116Z","iopub.status.idle":"2024-02-06T05:33:34.249678Z","shell.execute_reply.started":"2024-02-06T05:33:33.158089Z","shell.execute_reply":"2024-02-06T05:33:34.248473Z"},"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-06T05:33:34.251482Z","iopub.execute_input":"2024-02-06T05:33:34.251829Z","iopub.status.idle":"2024-02-06T05:33:35.328796Z","shell.execute_reply.started":"2024-02-06T05:33:34.251795Z","shell.execute_reply":"2024-02-06T05:33:35.327580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:35.330520Z","iopub.execute_input":"2024-02-06T05:33:35.330846Z","iopub.status.idle":"2024-02-06T05:33:47.032127Z","shell.execute_reply.started":"2024-02-06T05:33:35.330814Z","shell.execute_reply":"2024-02-06T05:33:47.030965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.033535Z","iopub.execute_input":"2024-02-06T05:33:47.033829Z","iopub.status.idle":"2024-02-06T05:33:47.038596Z","shell.execute_reply.started":"2024-02-06T05:33:47.033799Z","shell.execute_reply":"2024-02-06T05:33:47.037700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Dropout Regularization","metadata":{}},{"cell_type":"markdown","source":"# Vgg16 model","metadata":{}},{"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.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.vgg16 import VGG16","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.039737Z","iopub.execute_input":"2024-02-06T05:33:47.040006Z","iopub.status.idle":"2024-02-06T05:33:47.050683Z","shell.execute_reply.started":"2024-02-06T05:33:47.039982Z","shell.execute_reply":"2024-02-06T05:33:47.049856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load model\nmodel = VGG16(include_top=False, \n              weights='imagenet', \n              input_shape=(224, 224, 3))\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.055460Z","iopub.execute_input":"2024-02-06T05:33:47.055749Z","iopub.status.idle":"2024-02-06T05:33:47.449717Z","shell.execute_reply.started":"2024-02-06T05:33:47.055726Z","shell.execute_reply":"2024-02-06T05:33:47.448813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-02-06T05:33:47.450998Z","iopub.execute_input":"2024-02-06T05:33:47.451380Z","iopub.status.idle":"2024-02-06T05:33:47.459716Z","shell.execute_reply.started":"2024-02-06T05:33:47.451345Z","shell.execute_reply":"2024-02-06T05:33:47.458884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.460943Z","iopub.execute_input":"2024-02-06T05:33:47.461282Z","iopub.status.idle":"2024-02-06T05:33:47.472347Z","shell.execute_reply.started":"2024-02-06T05:33:47.461219Z","shell.execute_reply":"2024-02-06T05:33:47.471523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    # load model\n    model = VGG16(include_top=False, \n              weights='imagenet', \n              input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:-4]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-4].output)\n    class1 = Dense(64, activation='relu', kernel_initializer='he_uniform')(flat1)\n    dropout1 = Dropout(0.5)(class1)  # Add dropout regularization\n    class2 = Dense(32, activation='relu', kernel_initializer='he_uniform')(dropout1)\n    output = Dense(1, activation='sigmoid')(class2)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.473381Z","iopub.execute_input":"2024-02-06T05:33:47.473671Z","iopub.status.idle":"2024-02-06T05:33:47.482171Z","shell.execute_reply.started":"2024-02-06T05:33:47.473647Z","shell.execute_reply":"2024-02-06T05:33:47.481344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.483321Z","iopub.execute_input":"2024-02-06T05:33:47.483647Z","iopub.status.idle":"2024-02-06T05:33:47.491080Z","shell.execute_reply.started":"2024-02-06T05:33:47.483615Z","shell.execute_reply":"2024-02-06T05:33:47.490275Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\t# create data generator\n\tdatagen\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=512, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=512, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:47.492113Z","iopub.execute_input":"2024-02-06T05:33:47.492374Z","iopub.status.idle":"2024-02-06T05:33:48.521008Z","shell.execute_reply.started":"2024-02-06T05:33:47.492350Z","shell.execute_reply":"2024-02-06T05:33:48.520129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-02-06T05:33:48.522316Z","iopub.execute_input":"2024-02-06T05:33:48.522937Z","iopub.status.idle":"2024-02-06T05:33:48.529729Z","shell.execute_reply.started":"2024-02-06T05:33:48.522900Z","shell.execute_reply":"2024-02-06T05:33:48.528849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# data generator\n\tdatagen \n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# fit model\n\thistory = model.fit(train_it,steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1,callbacks=[PlotLossesKeras()])\n\t# evaluate model\n\t_, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\tmdvgg16 = '/kaggle/working/final_vgg16.hdf5'\n\tmodel.save(mdvgg16)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:48.530717Z","iopub.execute_input":"2024-02-06T05:33:48.531027Z","iopub.status.idle":"2024-02-06T05:33:48.539904Z","shell.execute_reply.started":"2024-02-06T05:33:48.530992Z","shell.execute_reply":"2024-02-06T05:33:48.539071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T05:33:48.541087Z","iopub.execute_input":"2024-02-06T05:33:48.541352Z","iopub.status.idle":"2024-02-06T06:22:52.584211Z","shell.execute_reply.started":"2024-02-06T05:33:48.541329Z","shell.execute_reply":"2024-02-06T06:22:52.583347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **VGG16 >> 92.083**","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\n# Load the model\nmdvgg16 = '/kaggle/working/final_vgg16.hdf5'\nloaded_model = load_model(mdvgg16)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:52.585447Z","iopub.execute_input":"2024-02-06T06:22:52.585748Z","iopub.status.idle":"2024-02-06T06:22:53.100443Z","shell.execute_reply.started":"2024-02-06T06:22:52.585722Z","shell.execute_reply":"2024-02-06T06:22:53.099581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ----------------------------","metadata":{}},{"cell_type":"markdown","source":"# Load pre-trained ResNet50 model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.layers import Input\n\n# Load pre-trained ResNet50 model\nmodel_resnet = ResNet50(weights='imagenet', input_tensor=Input(shape=(224, 224, 3)))\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:53.101642Z","iopub.execute_input":"2024-02-06T06:22:53.101946Z","iopub.status.idle":"2024-02-06T06:22:55.837921Z","shell.execute_reply.started":"2024-02-06T06:22:53.101918Z","shell.execute_reply":"2024-02-06T06:22:55.837065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    # load model\n    # Load pre-trained InceptionV3 model\n    model = model_resnet\n    # mark loaded layers as not trainable\n    for layer in model.layers[:-4]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-4].output)\n    class1 = Dense(64, activation='relu', kernel_initializer='he_uniform')(flat1)\n    dropout1 = Dropout(0.5)(class1)  # Add dropout regularization\n    class2 = Dense(32, activation='relu', kernel_initializer='he_uniform')(dropout1)\n    output = Dense(1, activation='sigmoid')(class2)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:55.839122Z","iopub.execute_input":"2024-02-06T06:22:55.839402Z","iopub.status.idle":"2024-02-06T06:22:55.846769Z","shell.execute_reply.started":"2024-02-06T06:22:55.839377Z","shell.execute_reply":"2024-02-06T06:22:55.845785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:55.847858Z","iopub.execute_input":"2024-02-06T06:22:55.848143Z","iopub.status.idle":"2024-02-06T06:22:55.861867Z","shell.execute_reply.started":"2024-02-06T06:22:55.848119Z","shell.execute_reply":"2024-02-06T06:22:55.860996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\t# create data generator\n\tdatagen\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=1024, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=1024, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:55.862979Z","iopub.execute_input":"2024-02-06T06:22:55.863254Z","iopub.status.idle":"2024-02-06T06:22:56.931959Z","shell.execute_reply.started":"2024-02-06T06:22:55.863231Z","shell.execute_reply":"2024-02-06T06:22:56.931230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-02-06T06:22:56.933198Z","iopub.execute_input":"2024-02-06T06:22:56.933783Z","iopub.status.idle":"2024-02-06T06:22:56.940982Z","shell.execute_reply.started":"2024-02-06T06:22:56.933745Z","shell.execute_reply":"2024-02-06T06:22:56.940063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# data generator\n\tdatagen \n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# fit model\n\thistory = model.fit(train_it,steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1,callbacks=[PlotLossesKeras()])\n\t# evaluate model\n\t_, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\tMdResNet50 = '/kaggle/working/final_ResNet50.hdf5'\n\tmodel.save(MdResNet50)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:56.942137Z","iopub.execute_input":"2024-02-06T06:22:56.942398Z","iopub.status.idle":"2024-02-06T06:22:56.955428Z","shell.execute_reply.started":"2024-02-06T06:22:56.942374Z","shell.execute_reply":"2024-02-06T06:22:56.954701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T06:22:56.956398Z","iopub.execute_input":"2024-02-06T06:22:56.956654Z","iopub.status.idle":"2024-02-06T07:12:17.322325Z","shell.execute_reply.started":"2024-02-06T06:22:56.956630Z","shell.execute_reply":"2024-02-06T07:12:17.321463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\n# Load the model\nMdResNet50 = '/kaggle/working/final_ResNet50.hdf5'\nloaded_model = load_model(MdResNet50)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:17.323705Z","iopub.execute_input":"2024-02-06T07:12:17.324034Z","iopub.status.idle":"2024-02-06T07:12:19.242995Z","shell.execute_reply.started":"2024-02-06T07:12:17.323994Z","shell.execute_reply":"2024-02-06T07:12:19.242182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load pre-trained InceptionV3 model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.layers import Input\n\n# Load pre-trained InceptionV3 model\nmodel = InceptionV3(weights='imagenet', \n                              input_tensor=Input(shape=(299, 299, 3)))\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:19.244418Z","iopub.execute_input":"2024-02-06T07:12:19.244769Z","iopub.status.idle":"2024-02-06T07:12:23.047942Z","shell.execute_reply.started":"2024-02-06T07:12:19.244734Z","shell.execute_reply":"2024-02-06T07:12:23.046991Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    # load model\n    # Load pre-trained InceptionV3 model\n    model = InceptionV3(weights='imagenet',input_tensor=Input(shape=(299, 299, 3)))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:-4]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-4].output)\n    class1 = Dense(64, activation='relu', kernel_initializer='he_uniform')(flat1)\n    dropout1 = Dropout(0.5)(class1)  # Add dropout regularization\n    class2 = Dense(32, activation='relu', kernel_initializer='he_uniform')(dropout1)\n    output = Dense(1, activation='sigmoid')(class2)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:23.049232Z","iopub.execute_input":"2024-02-06T07:12:23.049520Z","iopub.status.idle":"2024-02-06T07:12:23.057289Z","shell.execute_reply.started":"2024-02-06T07:12:23.049493Z","shell.execute_reply":"2024-02-06T07:12:23.056212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:23.058673Z","iopub.execute_input":"2024-02-06T07:12:23.059323Z","iopub.status.idle":"2024-02-06T07:12:23.092456Z","shell.execute_reply.started":"2024-02-06T07:12:23.059288Z","shell.execute_reply":"2024-02-06T07:12:23.091527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\t# create data generator\n\tdatagen\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=512, target_size=(299, 299))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=512, target_size=(299, 299))","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:23.093630Z","iopub.execute_input":"2024-02-06T07:12:23.093898Z","iopub.status.idle":"2024-02-06T07:12:24.153418Z","shell.execute_reply.started":"2024-02-06T07:12:23.093873Z","shell.execute_reply":"2024-02-06T07:12:24.152472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-02-06T07:12:24.154789Z","iopub.execute_input":"2024-02-06T07:12:24.155179Z","iopub.status.idle":"2024-02-06T07:12:24.162645Z","shell.execute_reply.started":"2024-02-06T07:12:24.155143Z","shell.execute_reply":"2024-02-06T07:12:24.161714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# data generator\n\tdatagen \n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# fit model\n\thistory = model.fit(train_it,steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1,callbacks=[PlotLossesKeras()])\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\tInceptionV3 = '/kaggle/working/final_InceptionV3.hdf5'\n\tmodel.save(InceptionV3)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:24.163793Z","iopub.execute_input":"2024-02-06T07:12:24.164136Z","iopub.status.idle":"2024-02-06T07:12:24.176918Z","shell.execute_reply.started":"2024-02-06T07:12:24.164111Z","shell.execute_reply":"2024-02-06T07:12:24.176067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T07:12:24.183183Z","iopub.execute_input":"2024-02-06T07:12:24.183469Z","iopub.status.idle":"2024-02-06T08:34:50.930433Z","shell.execute_reply.started":"2024-02-06T07:12:24.183438Z","shell.execute_reply":"2024-02-06T08:34:50.929548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\n# Load the model\nInceptionV3 = '/kaggle/working/final_InceptionV3.hdf5'\nloaded_model = load_model(InceptionV3)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:50.931898Z","iopub.execute_input":"2024-02-06T08:34:50.932201Z","iopub.status.idle":"2024-02-06T08:34:53.256893Z","shell.execute_reply.started":"2024-02-06T08:34:50.932174Z","shell.execute_reply":"2024-02-06T08:34:53.256060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **InceptionV3 >> 98.064**","metadata":{}},{"cell_type":"markdown","source":"# Load pre-trained MobileNetV2 model","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import Input\n\n# Load pre-trained MobileNetV2 model\nmodel_mobilenet = MobileNetV2(weights='imagenet', input_tensor=Input(shape=(224, 224, 3)))\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:53.258354Z","iopub.execute_input":"2024-02-06T08:34:53.258621Z","iopub.status.idle":"2024-02-06T08:34:55.632276Z","shell.execute_reply.started":"2024-02-06T08:34:53.258598Z","shell.execute_reply":"2024-02-06T08:34:55.631337Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    # load model\n    # Load pre-trained InceptionV3 model\n    model = MobileNetV2(weights='imagenet',input_tensor=Input(shape=(299, 299, 3)))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:-4]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-4].output)\n    class1 = Dense(64, activation='relu', kernel_initializer='he_uniform')(flat1)\n    dropout1 = Dropout(0.5)(class1)  # Add dropout regularization\n    class2 = Dense(32, activation='relu', kernel_initializer='he_uniform')(dropout1)\n    output = Dense(1, activation='sigmoid')(class2)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:55.633489Z","iopub.execute_input":"2024-02-06T08:34:55.633772Z","iopub.status.idle":"2024-02-06T08:34:55.641732Z","shell.execute_reply.started":"2024-02-06T08:34:55.633746Z","shell.execute_reply":"2024-02-06T08:34:55.640748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=20,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.1,\n    zoom_range=0.1,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:55.643100Z","iopub.execute_input":"2024-02-06T08:34:55.643385Z","iopub.status.idle":"2024-02-06T08:34:55.656396Z","shell.execute_reply.started":"2024-02-06T08:34:55.643360Z","shell.execute_reply":"2024-02-06T08:34:55.655332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-02-06T08:34:55.657770Z","iopub.execute_input":"2024-02-06T08:34:55.658165Z","iopub.status.idle":"2024-02-06T08:34:55.667670Z","shell.execute_reply.started":"2024-02-06T08:34:55.658120Z","shell.execute_reply":"2024-02-06T08:34:55.666592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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# data generator\n\tdatagen \n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# fit model\n\thistory = model.fit(train_it,steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1,callbacks=[PlotLossesKeras()])\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\tmbnv2 = '/kaggle/working/mbnv2.hdf5'\n\tmodel.save(mbnv2)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:55.668856Z","iopub.execute_input":"2024-02-06T08:34:55.669137Z","iopub.status.idle":"2024-02-06T08:34:55.678518Z","shell.execute_reply.started":"2024-02-06T08:34:55.669113Z","shell.execute_reply":"2024-02-06T08:34:55.677671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T08:34:55.679845Z","iopub.execute_input":"2024-02-06T08:34:55.680187Z","iopub.status.idle":"2024-02-06T09:57:16.532290Z","shell.execute_reply.started":"2024-02-06T08:34:55.680161Z","shell.execute_reply":"2024-02-06T09:57:16.531308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import load_model\n\n# Load the model\nmbnv2 = '/kaggle/working/mbnv2.hdf5'\nloaded_model = load_model(mbnv2)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T09:57:16.533731Z","iopub.execute_input":"2024-02-06T09:57:16.534059Z","iopub.status.idle":"2024-02-06T09:57:18.266315Z","shell.execute_reply.started":"2024-02-06T09:57:16.534006Z","shell.execute_reply":"2024-02-06T09:57:18.265441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"6610210486 & 6610210505","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}