{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30635,"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","_kg_hide-input":false,"_kg_hide-output":false,"execution":{"iopub.status.busy":"2024-01-18T15:12:01.078801Z","iopub.execute_input":"2024-01-18T15:12:01.079097Z","iopub.status.idle":"2024-01-18T15:12:02.171528Z","shell.execute_reply.started":"2024-01-18T15:12:01.079070Z","shell.execute_reply":"2024-01-18T15:12:02.170626Z"},"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-18T15:12:07.443728Z","iopub.execute_input":"2024-01-18T15:12:07.444700Z","iopub.status.idle":"2024-01-18T15:12:22.417079Z","shell.execute_reply.started":"2024-01-18T15:12:07.444666Z","shell.execute_reply":"2024-01-18T15:12:22.416264Z"},"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-18T15:12:28.248652Z","iopub.execute_input":"2024-01-18T15:12:28.249022Z","iopub.status.idle":"2024-01-18T15:12:29.522135Z","shell.execute_reply.started":"2024-01-18T15:12:28.248992Z","shell.execute_reply":"2024-01-18T15:12:29.521215Z"},"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 # define subplot\n pyplot.subplot(330 + 1 + i)\n # define filename\n filename = folder + 'cat.' + str(i) + '.jpg'\n # load image pixels\n image = imread(filename)\n # plot raw pixel data\n pyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:12:33.649256Z","iopub.execute_input":"2024-01-18T15:12:33.649982Z","iopub.status.idle":"2024-01-18T15:12:34.717787Z","shell.execute_reply.started":"2024-01-18T15:12:33.649950Z","shell.execute_reply":"2024-01-18T15:12:34.716754Z"},"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-01-18T15:12:38.300916Z","iopub.execute_input":"2024-01-18T15:12:38.301276Z","iopub.status.idle":"2024-01-18T15:12:50.790958Z","shell.execute_reply.started":"2024-01-18T15:12:38.301246Z","shell.execute_reply":"2024-01-18T15:12:50.790188Z"},"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-01-18T15:13:12.618866Z","iopub.execute_input":"2024-01-18T15:13:12.619507Z","iopub.status.idle":"2024-01-18T15:14:38.767268Z","shell.execute_reply.started":"2024-01-18T15:13:12.619462Z","shell.execute_reply":"2024-01-18T15:14:38.766347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:14:46.215467Z","iopub.execute_input":"2024-01-18T15:14:46.215891Z","iopub.status.idle":"2024-01-18T15:14:47.522697Z","shell.execute_reply.started":"2024-01-18T15:14:46.215859Z","shell.execute_reply":"2024-01-18T15:14:47.521718Z"},"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-18T15:15:40.574718Z","iopub.execute_input":"2024-01-18T15:15:40.575082Z","iopub.status.idle":"2024-01-18T15:16:29.001421Z","shell.execute_reply.started":"2024-01-18T15:15:40.575051Z","shell.execute_reply":"2024-01-18T15:16:29.000417Z"},"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-01-18T15:16:37.932117Z","iopub.execute_input":"2024-01-18T15:16:37.932541Z","iopub.status.idle":"2024-01-18T15:16:37.939310Z","shell.execute_reply.started":"2024-01-18T15:16:37.932479Z","shell.execute_reply":"2024-01-18T15:16:37.938158Z"},"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-18T15:16:39.405952Z","iopub.execute_input":"2024-01-18T15:16:39.406453Z","iopub.status.idle":"2024-01-18T15:16:54.799355Z","shell.execute_reply.started":"2024-01-18T15:16:39.406406Z","shell.execute_reply":"2024-01-18T15:16:54.797940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l test1 | wc","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:17:02.083038Z","iopub.execute_input":"2024-01-18T15:17:02.083575Z","iopub.status.idle":"2024-01-18T15:17:03.375934Z","shell.execute_reply.started":"2024-01-18T15:17:02.083528Z","shell.execute_reply":"2024-01-18T15:17:03.374820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Develop a Baseline CNN Model¶","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:17:09.169411Z","iopub.execute_input":"2024-01-18T15:17:09.170151Z","iopub.status.idle":"2024-01-18T15:17:09.176199Z","shell.execute_reply.started":"2024-01-18T15:17:09.170113Z","shell.execute_reply":"2024-01-18T15:17:09.174795Z"}},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras; print(keras.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:17:40.393215Z","iopub.execute_input":"2024-01-18T15:17:40.394128Z","iopub.status.idle":"2024-01-18T15:17:49.954314Z","shell.execute_reply.started":"2024-01-18T15:17:40.394087Z","shell.execute_reply":"2024-01-18T15:17:49.953309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:17:52.369164Z","iopub.execute_input":"2024-01-18T15:17:52.369925Z","iopub.status.idle":"2024-01-18T15:18:06.159882Z","shell.execute_reply.started":"2024-01-18T15:17:52.369882Z","shell.execute_reply":"2024-01-18T15:18:06.158801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:18:22.488025Z","iopub.execute_input":"2024-01-18T15:18:22.489083Z","iopub.status.idle":"2024-01-18T15:18:22.504736Z","shell.execute_reply.started":"2024-01-18T15:18:22.489038Z","shell.execute_reply":"2024-01-18T15:18:22.503936Z"},"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 tensorflow.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-01-18T15:18:25.770265Z","iopub.execute_input":"2024-01-18T15:18:25.771129Z","iopub.status.idle":"2024-01-18T15:18:25.904676Z","shell.execute_reply.started":"2024-01-18T15:18:25.771095Z","shell.execute_reply":"2024-01-18T15:18:25.903857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:18:34.515236Z","iopub.execute_input":"2024-01-18T15:18:34.516108Z","iopub.status.idle":"2024-01-18T15:18:34.520242Z","shell.execute_reply.started":"2024-01-18T15:18:34.516072Z","shell.execute_reply":"2024-01-18T15:18:34.519252Z"},"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 tensorflow.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(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=30, 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\n#run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:18:35.838053Z","iopub.execute_input":"2024-01-18T15:18:35.839036Z","iopub.status.idle":"2024-01-18T15:18:35.854317Z","shell.execute_reply.started":"2024-01-18T15:18:35.838995Z","shell.execute_reply":"2024-01-18T15:18:35.852824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:18:40.708597Z","iopub.execute_input":"2024-01-18T15:18:40.708966Z","iopub.status.idle":"2024-01-18T15:18:44.639717Z","shell.execute_reply.started":"2024-01-18T15:18:40.708939Z","shell.execute_reply":"2024-01-18T15:18:44.638850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-18T15:19:13.016165Z","iopub.execute_input":"2024-01-18T15:19:13.016560Z","iopub.status.idle":"2024-01-18T15:19:13.021706Z","shell.execute_reply.started":"2024-01-18T15:19:13.016522Z","shell.execute_reply":"2024-01-18T15:19:13.020733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n class_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n class_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:19:23.514089Z","iopub.execute_input":"2024-01-18T15:19:23.514470Z","iopub.status.idle":"2024-01-18T15:19:24.567344Z","shell.execute_reply.started":"2024-01-18T15:19:23.514438Z","shell.execute_reply":"2024-01-18T15:19:24.566461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:26:35.835547Z","iopub.execute_input":"2024-01-18T15:26:35.836441Z","iopub.status.idle":"2024-01-18T15:26:35.840634Z","shell.execute_reply.started":"2024-01-18T15:26:35.836403Z","shell.execute_reply":"2024-01-18T15:26:35.839647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:26:38.368217Z","iopub.execute_input":"2024-01-18T15:26:38.369122Z","iopub.status.idle":"2024-01-18T15:26:38.373961Z","shell.execute_reply.started":"2024-01-18T15:26:38.369082Z","shell.execute_reply":"2024-01-18T15:26:38.372931Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:28:05.520052Z","iopub.execute_input":"2024-01-18T15:28:05.520474Z","iopub.status.idle":"2024-01-18T15:28:05.569211Z","shell.execute_reply.started":"2024-01-18T15:28:05.520439Z","shell.execute_reply":"2024-01-18T15:28:05.568303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-18T15:28:16.386656Z","iopub.execute_input":"2024-01-18T15:28:16.387051Z","iopub.status.idle":"2024-01-18T16:26:01.148177Z","shell.execute_reply.started":"2024-01-18T15:28:16.387017Z","shell.execute_reply":"2024-01-18T16:26:01.147349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}