{"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"},{"sourceId":7478644,"sourceType":"datasetVersion","datasetId":4353155}],"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-09T06:00:35.946701Z","iopub.execute_input":"2024-02-09T06:00:35.946977Z","iopub.status.idle":"2024-02-09T06:00:36.312629Z","shell.execute_reply.started":"2024-02-09T06:00:35.946952Z","shell.execute_reply":"2024-02-09T06:00:36.311578Z"},"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-09T06:00:36.314291Z","iopub.execute_input":"2024-02-09T06:00:36.314759Z","iopub.status.idle":"2024-02-09T06:00:52.404187Z","shell.execute_reply.started":"2024-02-09T06:00:36.314730Z","shell.execute_reply":"2024-02-09T06:00:52.403379Z"},"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-09T06:00:52.405774Z","iopub.execute_input":"2024-02-09T06:00:52.406161Z","iopub.status.idle":"2024-02-09T06:00:53.782721Z","shell.execute_reply.started":"2024-02-09T06:00:52.406121Z","shell.execute_reply":"2024-02-09T06:00:53.781851Z"},"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-09T06:00:53.784781Z","iopub.execute_input":"2024-02-09T06:00:53.785056Z","iopub.status.idle":"2024-02-09T06:00:54.990596Z","shell.execute_reply.started":"2024-02-09T06:00:53.785031Z","shell.execute_reply":"2024-02-09T06:00:54.989675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-09T06:00:54.991782Z","iopub.execute_input":"2024-02-09T06:00:54.992081Z","iopub.status.idle":"2024-02-09T06:00:54.998136Z","shell.execute_reply.started":"2024-02-09T06:00:54.992053Z","shell.execute_reply":"2024-02-09T06:00:54.997066Z"},"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-09T06:00:54.999409Z","iopub.execute_input":"2024-02-09T06:00:54.999680Z","iopub.status.idle":"2024-02-09T06:01:12.687358Z","shell.execute_reply.started":"2024-02-09T06:00:54.999656Z","shell.execute_reply":"2024-02-09T06:01:12.686362Z"},"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-09T06:01:12.688860Z","iopub.execute_input":"2024-02-09T06:01:12.689579Z","iopub.status.idle":"2024-02-09T06:02:41.368873Z","shell.execute_reply.started":"2024-02-09T06:01:12.689542Z","shell.execute_reply":"2024-02-09T06:02:41.367403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-09T06:02:41.370984Z","iopub.execute_input":"2024-02-09T06:02:41.371406Z","iopub.status.idle":"2024-02-09T06:02:42.905033Z","shell.execute_reply.started":"2024-02-09T06:02:41.371369Z","shell.execute_reply":"2024-02-09T06:02:42.904019Z"},"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-09T06:03:28.387651Z","iopub.execute_input":"2024-02-09T06:03:28.388061Z","iopub.status.idle":"2024-02-09T06:04:18.463927Z","shell.execute_reply.started":"2024-02-09T06:03:28.388027Z","shell.execute_reply":"2024-02-09T06:04:18.462942Z"},"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-09T06:04:18.465635Z","iopub.execute_input":"2024-02-09T06:04:18.465954Z","iopub.status.idle":"2024-02-09T06:04:18.471978Z","shell.execute_reply.started":"2024-02-09T06:04:18.465917Z","shell.execute_reply":"2024-02-09T06:04:18.470807Z"},"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-09T06:04:18.473408Z","iopub.execute_input":"2024-02-09T06:04:18.473783Z","iopub.status.idle":"2024-02-09T06:04:34.500546Z","shell.execute_reply.started":"2024-02-09T06:04:18.473749Z","shell.execute_reply":"2024-02-09T06:04:34.499647Z"},"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-09T06:04:34.502745Z","iopub.execute_input":"2024-02-09T06:04:34.503033Z","iopub.status.idle":"2024-02-09T06:04:35.725325Z","shell.execute_reply.started":"2024-02-09T06:04:34.503008Z","shell.execute_reply":"2024-02-09T06:04:35.724377Z"},"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-09T06:04:35.726864Z","iopub.execute_input":"2024-02-09T06:04:35.727316Z","iopub.status.idle":"2024-02-09T06:04:36.828514Z","shell.execute_reply.started":"2024-02-09T06:04:35.727282Z","shell.execute_reply":"2024-02-09T06:04:36.827523Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l test1 | wc","metadata":{"execution":{"iopub.status.busy":"2024-02-09T06:04:36.829933Z","iopub.execute_input":"2024-02-09T06:04:36.830253Z","iopub.status.idle":"2024-02-09T06:04:38.048273Z","shell.execute_reply.started":"2024-02-09T06:04:36.830226Z","shell.execute_reply":"2024-02-09T06:04:38.047301Z"},"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":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-09T06:04:38.050047Z","iopub.execute_input":"2024-02-09T06:04:38.050472Z","iopub.status.idle":"2024-02-09T06:04:54.164759Z","shell.execute_reply.started":"2024-02-09T06:04:38.050417Z","shell.execute_reply":"2024-02-09T06:04:54.163550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-09T06:04:54.166176Z","iopub.execute_input":"2024-02-09T06:04:54.166521Z","iopub.status.idle":"2024-02-09T06:04:54.185101Z","shell.execute_reply.started":"2024-02-09T06:04:54.166493Z","shell.execute_reply":"2024-02-09T06:04:54.184192Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-09T06:04:54.186460Z","iopub.execute_input":"2024-02-09T06:04:54.186747Z","iopub.status.idle":"2024-02-09T06:05:08.189851Z","shell.execute_reply.started":"2024-02-09T06:04:54.186718Z","shell.execute_reply":"2024-02-09T06:05:08.188899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","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=(200, 200, 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=(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(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                       )\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\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":{}},{"cell_type":"markdown","source":"# vgg16 model used for transfer learning on the dogs and cats dataset (round 2)\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=(200, 200, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers[:15]:\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(\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\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=(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(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                       )\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\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":{}},{"cell_type":"markdown","source":"# vgg16 model used for transfer learning on the dogs and cats dataset (round 3) current\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[:15]:\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.0001, 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(\n\t    rescale=1./255,\n\t    rotation_range=40,\n\t    width_shift_range=0.2,\n\t    height_shift_range=0.2,\n\t    shear_range=0.2,\n\t    zoom_range=0.2,\n\t    horizontal_flip=True,\n\t    fill_mode='nearest'\n\t)\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\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=1)\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":{}},{"cell_type":"code","source":"# vgg16 model used for transfer learning on the dogs and cats dataset (round 4)\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[:15]:\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.0001, 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(\n\t    rescale=1./255,\n\t    rotation_range=40,\n\t    width_shift_range=0.2,\n\t    height_shift_range=0.2,\n\t    shear_range=0.2,\n\t    zoom_range=0.2,\n\t    horizontal_flip=True,\n\t    fill_mode='nearest'\n\t)\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\t# fit model\n\thistory = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=13, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n    # save model\n\tmodel.save('final_model.h5')\n\n# run the test harness for evaluating a model\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T07:21:39.010285Z","iopub.execute_input":"2024-02-09T07:21:39.011226Z","iopub.status.idle":"2024-02-09T08:45:07.270952Z","shell.execute_reply.started":"2024-02-09T07:21:39.011191Z","shell.execute_reply":"2024-02-09T08:45:07.270089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-01-24T08:21:43.596773Z","iopub.execute_input":"2024-01-24T08:21:43.597207Z","iopub.status.idle":"2024-01-24T08:21:45.558714Z","shell.execute_reply.started":"2024-01-24T08:21:43.597169Z","shell.execute_reply":"2024-01-24T08:21:45.557571Z"}}},{"cell_type":"markdown","source":"run_test_harness()","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 \n# load and prepare the image\ndef load_image(filename):\n # load the image\n img = load_img(filename, target_size=(224, 224))\n # convert to array\n img = img_to_array(img)\n # reshape into a single sample with 3 channels\n img = img.reshape(1, 224, 224, 3)\n # center pixel data\n img = img.astype('float32')\n img = img - [123.68, 116.779, 103.939]\n return img\n \n# load an image and predict the class\ndef run_example():\n # load the image\n img = load_image('../input/sample-image/sample_image.jpg')\n # load model\n model = load_model('final_model.h5')\n # predict the class\n result = model.predict(img)\n print(result[0])\n \n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T08:45:07.272621Z","iopub.execute_input":"2024-02-09T08:45:07.272924Z","iopub.status.idle":"2024-02-09T08:45:08.660386Z","shell.execute_reply.started":"2024-02-09T08:45:07.272898Z","shell.execute_reply":"2024-02-09T08:45:08.659393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Xception model used for transfer learning on the dogs and cats dataset","metadata":{}},{"cell_type":"code","source":"# Xception 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.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():\n\t# load model\n\tmodel = Xception(include_top=False, input_shape=(299, 299, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers[:15]:\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.0001, 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(\n\t    rescale=1./255,\n\t    rotation_range=40,\n\t    width_shift_range=0.2,\n\t    height_shift_range=0.2,\n\t    shear_range=0.2,\n\t    zoom_range=0.2,\n\t    horizontal_flip=True,\n\t    fill_mode='nearest'\n\t)\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=(299, 299))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(299, 299))\n\t# fit model\n\thistory = 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\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n    # save model\n\tmodel.save('final_model2.h5')\n\n# run the test harness for evaluating a model\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T09:00:51.233036Z","iopub.execute_input":"2024-02-09T09:00:51.233486Z","iopub.status.idle":"2024-02-09T10:51:55.927263Z","shell.execute_reply.started":"2024-02-09T09:00:51.233452Z","shell.execute_reply":"2024-02-09T10:51:55.926396Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 \n# load and prepare the image\ndef load_image(filename):\n # load the image\n img = load_img(filename, target_size=(299, 299))\n # convert to array\n img = img_to_array(img)\n # reshape into a single sample with 3 channels\n img = img.reshape(1, 299, 299, 3)\n # center pixel data\n img = img.astype('float32')\n img = img - [123.68, 116.779, 103.939]\n return img\n \n# load an image and predict the class\ndef run_example():\n # load the image\n img = load_image('../input/sample-image/sample_image.jpg')\n # load model\n model = load_model('final_model2.h5')\n # predict the class\n result = model.predict(img)\n print(result[0])\n \n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T10:53:53.720017Z","iopub.execute_input":"2024-02-09T10:53:53.720443Z","iopub.status.idle":"2024-02-09T10:53:57.964492Z","shell.execute_reply.started":"2024-02-09T10:53:53.720409Z","shell.execute_reply":"2024-02-09T10:53:57.963565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# vgg19 model used for transfer learning on the dogs and cats dataset","metadata":{}},{"cell_type":"code","source":"# vgg19 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.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():\n\t# load model\n\tmodel = VGG19(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers[:15]:\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.0001, 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 + '_plot3.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(\n\t    rescale=1./255,\n\t    rotation_range=40,\n\t    width_shift_range=0.2,\n\t    height_shift_range=0.2,\n\t    shear_range=0.2,\n\t    zoom_range=0.2,\n\t    horizontal_flip=True,\n\t    fill_mode='nearest'\n\t)\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\t# fit model\n\thistory = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=5, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n    # save model\n\tmodel.save('final_model3.h5')\n\n# run the test harness for evaluating a model\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T11:04:53.827102Z","iopub.execute_input":"2024-02-09T11:04:53.827519Z","iopub.status.idle":"2024-02-09T11:38:14.935756Z","shell.execute_reply.started":"2024-02-09T11:04:53.827485Z","shell.execute_reply":"2024-02-09T11:38:14.934732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 \n# load and prepare the image\ndef load_image(filename):\n # load the image\n img = load_img(filename, target_size=(224, 224))\n # convert to array\n img = img_to_array(img)\n # reshape into a single sample with 3 channels\n img = img.reshape(1, 224, 224, 3)\n # center pixel data\n img = img.astype('float32')\n img = img - [123.68, 116.779, 103.939]\n return img\n \n# load an image and predict the class\ndef run_example():\n # load the image\n img = load_image('../input/sample-image/sample_image.jpg')\n # load model\n model = load_model('final_model3.h5')\n # predict the class\n result = model.predict(img)\n print(result[0])\n \n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T11:39:06.673296Z","iopub.execute_input":"2024-02-09T11:39:06.674263Z","iopub.status.idle":"2024-02-09T11:39:07.455777Z","shell.execute_reply.started":"2024-02-09T11:39:06.674229Z","shell.execute_reply":"2024-02-09T11:39:07.454691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# resnet50 model used for transfer learning on the dogs and cats dataset","metadata":{}},{"cell_type":"code","source":"# resnet50 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.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():\n\t# load model\n\tmodel = ResNet50(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers[:15]:\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.0001, 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 + '_plot4.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(\n\t    rescale=1./255,\n\t    rotation_range=40,\n\t    width_shift_range=0.2,\n\t    height_shift_range=0.2,\n\t    shear_range=0.2,\n\t    zoom_range=0.2,\n\t    horizontal_flip=True,\n\t    fill_mode='nearest'\n\t)\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\t# fit model\n\thistory = 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\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n    # save model\n\tmodel.save('final_model4.h5')\n\n# run the test harness for evaluating a model\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T12:29:35.928416Z","iopub.execute_input":"2024-02-09T12:29:35.929251Z","iopub.status.idle":"2024-02-09T14:04:47.388465Z","shell.execute_reply.started":"2024-02-09T12:29:35.929221Z","shell.execute_reply":"2024-02-09T14:04:47.387026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 \n# load and prepare the image\ndef load_image(filename):\n # load the image\n img = load_img(filename, target_size=(224, 224))\n # convert to array\n img = img_to_array(img)\n # reshape into a single sample with 3 channels\n img = img.reshape(1, 224, 224, 3)\n # center pixel data\n img = img.astype('float32')\n img = img - [123.68, 116.779, 103.939]\n return img\n \n# load an image and predict the class\ndef run_example():\n # load the image\n img = load_image('../input/sample-image/sample_image.jpg')\n # load model\n model = load_model('final_model4.h5')\n # predict the class\n result = model.predict(img)\n print(result[0])\n \n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T14:11:15.269985Z","iopub.execute_input":"2024-02-09T14:11:15.270800Z","iopub.status.idle":"2024-02-09T14:11:19.778372Z","shell.execute_reply.started":"2024-02-09T14:11:15.270763Z","shell.execute_reply":"2024-02-09T14:11:19.777252Z"},"trusted":true},"execution_count":null,"outputs":[]}]}