{"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":7487348,"sourceType":"datasetVersion","datasetId":4359057}],"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-01-26T16:06:22.375983Z","iopub.execute_input":"2024-01-26T16:06:22.376823Z","iopub.status.idle":"2024-01-26T16:06:22.383925Z","shell.execute_reply.started":"2024-01-26T16:06:22.376790Z","shell.execute_reply":"2024-01-26T16:06:22.383019Z"},"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-01-26T16:06:23.228453Z","iopub.execute_input":"2024-01-26T16:06:23.229163Z","iopub.status.idle":"2024-01-26T16:06:37.761756Z","shell.execute_reply.started":"2024-01-26T16:06:23.229129Z","shell.execute_reply":"2024-01-26T16:06:37.760931Z"},"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\ntrain_folder = '/kaggle/working/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-01-26T16:07:29.500449Z","iopub.execute_input":"2024-01-26T16:07:29.501302Z","iopub.status.idle":"2024-01-26T16:07:30.672204Z","shell.execute_reply.started":"2024-01-26T16:07:29.501270Z","shell.execute_reply":"2024-01-26T16:07:30.671297Z"},"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-01-26T16:07:34.399839Z","iopub.execute_input":"2024-01-26T16:07:34.400843Z","iopub.status.idle":"2024-01-26T16:07:35.470821Z","shell.execute_reply.started":"2024-01-26T16:07:34.400798Z","shell.execute_reply":"2024-01-26T16:07:35.469884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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\n# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T16:07:37.713099Z","iopub.execute_input":"2024-01-26T16:07:37.713481Z","iopub.status.idle":"2024-01-26T16:09:05.378871Z","shell.execute_reply.started":"2024-01-26T16:07:37.713454Z","shell.execute_reply":"2024-01-26T16:09:05.378008Z"},"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-01-26T16:09:05.382119Z","iopub.execute_input":"2024-01-26T16:09:05.382477Z"},"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-01-26T16:12:20.623165Z","iopub.execute_input":"2024-01-26T16:12:20.623626Z","iopub.status.idle":"2024-01-26T16:12:36.089580Z","shell.execute_reply.started":"2024-01-26T16:12:20.623591Z","shell.execute_reply":"2024-01-26T16:12:36.088688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\n\n# Create a Sequential model\nmodel = Sequential()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:35:25.592906Z","iopub.execute_input":"2024-01-26T08:35:25.593313Z","iopub.status.idle":"2024-01-26T08:35:25.647461Z","shell.execute_reply.started":"2024-01-26T08:35:25.593280Z","shell.execute_reply":"2024-01-26T08:35:25.646548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# block 1\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\n# block 2\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\n# block 3\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:35:47.072730Z","iopub.execute_input":"2024-01-26T08:35:47.073740Z","iopub.status.idle":"2024-01-26T08:35:47.134620Z","shell.execute_reply.started":"2024-01-26T08:35:47.073700Z","shell.execute_reply":"2024-01-26T08:35:47.133663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom keras.optimizers import SGD","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:37:58.517297Z","iopub.execute_input":"2024-01-26T08:37:58.517696Z","iopub.status.idle":"2024-01-26T08:37:58.522710Z","shell.execute_reply.started":"2024-01-26T08:37:58.517664Z","shell.execute_reply":"2024-01-26T08:37:58.521627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:38:00.707869Z","iopub.execute_input":"2024-01-26T08:38:00.708826Z","iopub.status.idle":"2024-01-26T08:38:00.715767Z","shell.execute_reply.started":"2024-01-26T08:38:00.708791Z","shell.execute_reply":"2024-01-26T08:38:00.714847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define model\nmodel = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:38:01.210661Z","iopub.execute_input":"2024-01-26T08:38:01.211077Z","iopub.status.idle":"2024-01-26T08:38:01.274329Z","shell.execute_reply.started":"2024-01-26T08:38:01.211043Z","shell.execute_reply":"2024-01-26T08:38:01.273586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:38:24.550828Z","iopub.execute_input":"2024-01-26T08:38:24.551238Z","iopub.status.idle":"2024-01-26T08:38:24.555962Z","shell.execute_reply.started":"2024-01-26T08:38:24.551209Z","shell.execute_reply":"2024-01-26T08:38:24.554865Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:38:25.446575Z","iopub.execute_input":"2024-01-26T08:38:25.447478Z","iopub.status.idle":"2024-01-26T08:38:25.451991Z","shell.execute_reply.started":"2024-01-26T08:38:25.447439Z","shell.execute_reply":"2024-01-26T08:38:25.450859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:38:43.101413Z","iopub.execute_input":"2024-01-26T08:38:43.101798Z","iopub.status.idle":"2024-01-26T08:38:44.129244Z","shell.execute_reply.started":"2024-01-26T08:38:43.101767Z","shell.execute_reply":"2024-01-26T08:38:44.128246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_it, steps_per_epoch=len(train_it),\n                    validation_data=test_it, validation_steps=len(test_it),\n                    epochs=20, verbose=0)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:43:44.569005Z","iopub.execute_input":"2024-01-26T08:43:44.569778Z","iopub.status.idle":"2024-01-26T08:58:47.607651Z","shell.execute_reply.started":"2024-01-26T08:43:44.569743Z","shell.execute_reply":"2024-01-26T08:58:47.606627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:58:47.609430Z","iopub.execute_input":"2024-01-26T08:58:47.609746Z","iopub.status.idle":"2024-01-26T08:59:00.187388Z","shell.execute_reply.started":"2024-01-26T08:58:47.609717Z","shell.execute_reply":"2024-01-26T08:59:00.186361Z"},"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-01-26T08:59:33.320186Z","iopub.execute_input":"2024-01-26T08:59:33.321012Z","iopub.status.idle":"2024-01-26T08:59:33.328643Z","shell.execute_reply.started":"2024-01-26T08:59:33.320976Z","shell.execute_reply":"2024-01-26T08:59:33.327618Z"},"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=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T08:59:44.041114Z","iopub.execute_input":"2024-01-26T08:59:44.041523Z","iopub.status.idle":"2024-01-26T09:14:50.139508Z","shell.execute_reply.started":"2024-01-26T08:59:44.041489Z","shell.execute_reply":"2024-01-26T09:14:50.138584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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","metadata":{"execution":{"iopub.status.busy":"2024-01-26T09:19:57.361154Z","iopub.execute_input":"2024-01-26T09:19:57.361956Z","iopub.status.idle":"2024-01-26T09:19:57.368849Z","shell.execute_reply.started":"2024-01-26T09:19:57.361920Z","shell.execute_reply":"2024-01-26T09:19:57.367733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2024-01-26T09:20:17.638129Z","iopub.execute_input":"2024-01-26T09:20:17.638544Z","iopub.status.idle":"2024-01-26T09:20:17.646318Z","shell.execute_reply.started":"2024-01-26T09:20:17.638510Z","shell.execute_reply":"2024-01-26T09:20:17.645424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2024-01-26T09:21:02.759085Z","iopub.execute_input":"2024-01-26T09:21:02.759481Z","iopub.status.idle":"2024-01-26T09:21:02.768720Z","shell.execute_reply.started":"2024-01-26T09:21:02.759453Z","shell.execute_reply":"2024-01-26T09:21:02.767772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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(Dropout(0.2))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dropout(0.5))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2024-01-26T09:21:14.445565Z","iopub.execute_input":"2024-01-26T09:21:14.446481Z","iopub.status.idle":"2024-01-26T09:21:14.455742Z","shell.execute_reply.started":"2024-01-26T09:21:14.446443Z","shell.execute_reply":"2024-01-26T09:21:14.454761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# baseline model with dropout 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.layers import Dropout\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(Dropout(0.2))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dropout(0.5))\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 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_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=50, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T09:21:21.701635Z","iopub.execute_input":"2024-01-26T09:21:21.702686Z","iopub.status.idle":"2024-01-26T10:01:40.051151Z","shell.execute_reply.started":"2024-01-26T09:21:21.702646Z","shell.execute_reply":"2024-01-26T10:01:40.050065Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generators\ntrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n# prepare iterators\ntrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T10:06:32.370045Z","iopub.execute_input":"2024-01-26T10:06:32.370764Z","iopub.status.idle":"2024-01-26T10:06:33.343503Z","shell.execute_reply.started":"2024-01-26T10:06:32.370725Z","shell.execute_reply":"2024-01-26T10:06:33.342525Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# baseline model with data augmentation 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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\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 generators\n\ttrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\t\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\n\ttest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = test_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=50, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T10:06:44.924603Z","iopub.execute_input":"2024-01-26T10:06:44.925386Z","iopub.status.idle":"2024-01-26T13:17:33.316536Z","shell.execute_reply.started":"2024-01-26T10:06:44.925352Z","shell.execute_reply":"2024-01-26T13:17:33.315475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2024-01-26T16:02:23.109760Z","iopub.execute_input":"2024-01-26T16:02:23.110592Z","iopub.status.idle":"2024-01-26T16:02:23.122402Z","shell.execute_reply.started":"2024-01-26T16:02:23.110559Z","shell.execute_reply":"2024-01-26T16:02:23.121454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# vgg16 model used for transfer learning on the dogs and cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T16:12:49.356805Z","iopub.execute_input":"2024-01-26T16:12:49.357773Z","iopub.status.idle":"2024-01-26T16:31:52.160344Z","shell.execute_reply.started":"2024-01-26T16:12:49.357732Z","shell.execute_reply":"2024-01-26T16:31:52.159458Z"},"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\n# create directories\ndataset_home = 'finalize_dogs_vs_cats/'\n# create label subdirectories\nlabeldirs = ['dogs/', 'cats/']\nfor labldir in labeldirs:\n\tnewdir = dataset_home + labldir\n\tmakedirs(newdir, exist_ok=True)\n# copy training dataset images into subdirectories\nsrc_directory = '/kaggle/working/train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T17:00:20.750131Z","iopub.execute_input":"2024-01-26T17:00:20.750517Z","iopub.status.idle":"2024-01-26T17:00:24.197365Z","shell.execute_reply.started":"2024-01-26T17:00:20.750491Z","shell.execute_reply":"2024-01-26T17:00:24.196510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n# 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('finalize_dogs_vs_cats/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\t# fit model\n\tmodel.fit_generator(train_it, steps_per_epoch=len(train_it), epochs=10, verbose=0)\n\t# save model\n\tmodel.save('final_model.h5')\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T16:34:56.062370Z","iopub.execute_input":"2024-01-26T16:34:56.062755Z","iopub.status.idle":"2024-01-26T16:52:57.045373Z","shell.execute_reply.started":"2024-01-26T16:34:56.062728Z","shell.execute_reply":"2024-01-26T16:52:57.044381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img","metadata":{"execution":{"iopub.status.busy":"2024-01-26T17:02:11.031252Z","iopub.execute_input":"2024-01-26T17:02:11.032229Z","iopub.status.idle":"2024-01-26T17:02:11.037715Z","shell.execute_reply.started":"2024-01-26T17:02:11.032195Z","shell.execute_reply":"2024-01-26T17:02:11.036769Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predict the class\nresult = model.predict(img)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T17:02:15.883012Z","iopub.execute_input":"2024-01-26T17:02:15.883906Z","iopub.status.idle":"2024-01-26T17:02:15.920920Z","shell.execute_reply.started":"2024-01-26T17:02:15.883868Z","shell.execute_reply":"2024-01-26T17:02:15.919762Z"},"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\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img\n\n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T17:02:23.289386Z","iopub.execute_input":"2024-01-26T17:02:23.289765Z","iopub.status.idle":"2024-01-26T17:02:23.386485Z","shell.execute_reply.started":"2024-01-26T17:02:23.289733Z","shell.execute_reply":"2024-01-26T17:02:23.385147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}