{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:26:29.152700Z","iopub.execute_input":"2024-02-07T14:26:29.153096Z","iopub.status.idle":"2024-02-07T14:26:30.320349Z","shell.execute_reply.started":"2024-02-07T14:26:29.153064Z","shell.execute_reply":"2024-02-07T14:26:30.319222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07T14:32:41.910486Z","iopub.execute_input":"2024-02-07T14:32:41.911213Z","iopub.status.idle":"2024-02-07T14:32:42.258184Z","shell.execute_reply.started":"2024-02-07T14:32:41.911179Z","shell.execute_reply":"2024-02-07T14:32:42.257285Z"},"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-07T14:32:44.064938Z","iopub.execute_input":"2024-02-07T14:32:44.065370Z","iopub.status.idle":"2024-02-07T14:32:59.408986Z","shell.execute_reply.started":"2024-02-07T14:32:44.065342Z","shell.execute_reply":"2024-02-07T14:32:59.407973Z"},"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-07T14:32:59.410553Z","iopub.execute_input":"2024-02-07T14:32:59.410840Z","iopub.status.idle":"2024-02-07T14:33:00.710949Z","shell.execute_reply.started":"2024-02-07T14:32:59.410814Z","shell.execute_reply":"2024-02-07T14:33:00.710046Z"},"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-07T14:33:00.712080Z","iopub.execute_input":"2024-02-07T14:33:00.712353Z","iopub.status.idle":"2024-02-07T14:33:01.828329Z","shell.execute_reply.started":"2024-02-07T14:33:00.712327Z","shell.execute_reply":"2024-02-07T14:33:01.827422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:33:01.830214Z","iopub.execute_input":"2024-02-07T14:33:01.830551Z","iopub.status.idle":"2024-02-07T14:33:01.836166Z","shell.execute_reply.started":"2024-02-07T14:33:01.830491Z","shell.execute_reply":"2024-02-07T14:33:01.835355Z"},"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-07T14:34:57.801349Z","iopub.execute_input":"2024-02-07T14:34:57.801865Z","iopub.status.idle":"2024-02-07T14:34:57.808747Z","shell.execute_reply.started":"2024-02-07T14:34:57.801826Z","shell.execute_reply":"2024-02-07T14:34:57.807874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install --upgrade numpy>=1.16.5,<1.23.0","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:40:30.539772Z","iopub.execute_input":"2024-02-07T14:40:30.540659Z","iopub.status.idle":"2024-02-07T14:40:31.642829Z","shell.execute_reply.started":"2024-02-07T14:40:30.540615Z","shell.execute_reply":"2024-02-07T14:40:31.641632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:35:04.713882Z","iopub.execute_input":"2024-02-07T14:35:04.714220Z","iopub.status.idle":"2024-02-07T14:35:05.920869Z","shell.execute_reply.started":"2024-02-07T14:35:04.714195Z","shell.execute_reply":"2024-02-07T14:35:05.919710Z"},"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-07T14:35:07.386956Z","iopub.execute_input":"2024-02-07T14:35:07.387916Z","iopub.status.idle":"2024-02-07T14:36:47.433176Z","shell.execute_reply.started":"2024-02-07T14:35:07.387878Z","shell.execute_reply":"2024-02-07T14:36:47.432331Z"},"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')","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:38:19.980127Z","iopub.execute_input":"2024-02-07T14:38:19.980534Z","iopub.status.idle":"2024-02-07T14:39:14.745278Z","shell.execute_reply.started":"2024-02-07T14:38:19.980484Z","shell.execute_reply":"2024-02-07T14:39:14.744282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(photos.shape, labels.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:39:14.746430Z","iopub.execute_input":"2024-02-07T14:39:14.746721Z","iopub.status.idle":"2024-02-07T14:39:14.751936Z","shell.execute_reply.started":"2024-02-07T14:39:14.746695Z","shell.execute_reply":"2024-02-07T14:39:14.751049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","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-13T04:07:54.758244Z","iopub.execute_input":"2024-01-13T04:07:54.758579Z"}}},{"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-07T14:39:14.755853Z","iopub.execute_input":"2024-02-07T14:39:14.756162Z","iopub.status.idle":"2024-02-07T14:39:14.772559Z","shell.execute_reply.started":"2024-02-07T14:39:14.756137Z","shell.execute_reply":"2024-02-07T14:39:14.771859Z"},"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-07T14:39:14.773639Z","iopub.execute_input":"2024-02-07T14:39:14.773907Z","iopub.status.idle":"2024-02-07T14:39:31.090817Z","shell.execute_reply.started":"2024-02-07T14:39:14.773884Z","shell.execute_reply":"2024-02-07T14:39:31.089948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l test1 | wc ","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:39:31.091947Z","iopub.execute_input":"2024-02-07T14:39:31.092278Z","iopub.status.idle":"2024-02-07T14:39:32.566106Z","shell.execute_reply.started":"2024-02-07T14:39:31.092250Z","shell.execute_reply":"2024-02-07T14:39:32.564975Z"},"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-07T14:39:32.567693Z","iopub.execute_input":"2024-02-07T14:39:32.568003Z","iopub.status.idle":"2024-02-07T14:39:33.686505Z","shell.execute_reply.started":"2024-02-07T14:39:32.567976Z","shell.execute_reply":"2024-02-07T14:39:33.685519Z"},"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-07T14:39:33.687904Z","iopub.execute_input":"2024-02-07T14:39:33.688172Z","iopub.status.idle":"2024-02-07T14:39:34.807217Z","shell.execute_reply.started":"2024-02-07T14:39:33.688146Z","shell.execute_reply":"2024-02-07T14:39:34.806216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"!ls test1\n","metadata":{"execution":{"iopub.status.busy":"2024-01-13T03:01:48.472037Z","iopub.execute_input":"2024-01-13T03:01:48.473336Z","iopub.status.idle":"2024-01-13T03:01:49.583287Z","shell.execute_reply.started":"2024-01-13T03:01:48.47329Z","shell.execute_reply":"2024-01-13T03:01:49.58225Z"}}},{"cell_type":"markdown","source":"# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=1)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:39:48.625031Z","iopub.execute_input":"2024-02-07T14:39:48.625644Z","iopub.status.idle":"2024-02-07T14:39:48.639696Z","shell.execute_reply.started":"2024-02-07T14:39:48.625596Z","shell.execute_reply":"2024-02-07T14:39:48.638831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:39:48.641157Z","iopub.execute_input":"2024-02-07T14:39:48.641430Z","iopub.status.idle":"2024-02-07T14:40:04.403556Z","shell.execute_reply.started":"2024-02-07T14:39:48.641400Z","shell.execute_reply":"2024-02-07T14:40:04.402272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:40:04.404954Z","iopub.execute_input":"2024-02-07T14:40:04.405241Z","iopub.status.idle":"2024-02-07T14:40:04.423167Z","shell.execute_reply.started":"2024-02-07T14:40:04.405212Z","shell.execute_reply":"2024-02-07T14:40:04.422450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG19","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg19 import VGG19\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\n    # load model\n    model = VGG19(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:17]:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.95)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n        # fit model\n    history = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=9, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics(history)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T16:28:36.860010Z","iopub.execute_input":"2024-02-07T16:28:36.860428Z","iopub.status.idle":"2024-02-07T16:28:36.877426Z","shell.execute_reply.started":"2024-02-07T16:28:36.860389Z","shell.execute_reply":"2024-02-07T16:28:36.876416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T16:28:39.975083Z","iopub.execute_input":"2024-02-07T16:28:39.975632Z","iopub.status.idle":"2024-02-07T16:28:40.449951Z","shell.execute_reply.started":"2024-02-07T16:28:39.975577Z","shell.execute_reply":"2024-02-07T16:28:40.448807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T16:28:41.605212Z","iopub.execute_input":"2024-02-07T16:28:41.605902Z","iopub.status.idle":"2024-02-07T16:28:42.052051Z","shell.execute_reply.started":"2024-02-07T16:28:41.605867Z","shell.execute_reply":"2024-02-07T16:28:42.051209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T16:28:44.446141Z","iopub.execute_input":"2024-02-07T16:28:44.446548Z","iopub.status.idle":"2024-02-07T16:28:44.503055Z","shell.execute_reply.started":"2024-02-07T16:28:44.446513Z","shell.execute_reply":"2024-02-07T16:28:44.502098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T16:28:54.886715Z","iopub.execute_input":"2024-02-07T16:28:54.887488Z","iopub.status.idle":"2024-02-07T17:28:05.277181Z","shell.execute_reply.started":"2024-02-07T16:28:54.887448Z","shell.execute_reply":"2024-02-07T17:28:05.276023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# DenseNet201","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.densenet import DenseNet201\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_model2():\n    # load model\n    model = DenseNet201(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.95)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness2():\n    # define model\n    model2 = define_model2()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n        # fit model\n    history2 = model2.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=7, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc2 = model2.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc2 * 100.0))\n    # learning curves\n    summarize_diagnostics(history2)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:43:30.680832Z","iopub.execute_input":"2024-02-07T14:43:30.681924Z","iopub.status.idle":"2024-02-07T14:43:30.698972Z","shell.execute_reply.started":"2024-02-07T14:43:30.681878Z","shell.execute_reply":"2024-02-07T14:43:30.697937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model2 = define_model2()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:43:34.619378Z","iopub.execute_input":"2024-02-07T14:43:34.620289Z","iopub.status.idle":"2024-02-07T14:43:40.268839Z","shell.execute_reply.started":"2024-02-07T14:43:34.620251Z","shell.execute_reply":"2024-02-07T14:43:40.267731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model2.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:43:41.438896Z","iopub.execute_input":"2024-02-07T14:43:41.439268Z","iopub.status.idle":"2024-02-07T14:43:43.223062Z","shell.execute_reply.started":"2024-02-07T14:43:41.439235Z","shell.execute_reply":"2024-02-07T14:43:43.221968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness2()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T14:44:13.545208Z","iopub.execute_input":"2024-02-07T14:44:13.545736Z","iopub.status.idle":"2024-02-07T15:31:07.220475Z","shell.execute_reply.started":"2024-02-07T14:44:13.545703Z","shell.execute_reply":"2024-02-07T15:31:07.219569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ResNet101V2","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.resnet_v2 import ResNet101V2\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_model3():\n    # load model\n    model = ResNet101V2(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.95)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness3():\n    # define model\n    model3 = define_model3()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n        # fit model\n    history3 = model3.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=8, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc3 = model3.evaluate(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc3 * 100.0))\n    # learning curves\n    summarize_diagnostics(history3)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T15:34:28.184731Z","iopub.execute_input":"2024-02-07T15:34:28.185432Z","iopub.status.idle":"2024-02-07T15:34:28.201742Z","shell.execute_reply.started":"2024-02-07T15:34:28.185393Z","shell.execute_reply":"2024-02-07T15:34:28.200715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3 = define_model3()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T15:34:33.680836Z","iopub.execute_input":"2024-02-07T15:34:33.681606Z","iopub.status.idle":"2024-02-07T15:34:38.620015Z","shell.execute_reply.started":"2024-02-07T15:34:33.681570Z","shell.execute_reply":"2024-02-07T15:34:38.619018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T15:34:39.400625Z","iopub.execute_input":"2024-02-07T15:34:39.401530Z","iopub.status.idle":"2024-02-07T15:34:40.434717Z","shell.execute_reply.started":"2024-02-07T15:34:39.401478Z","shell.execute_reply":"2024-02-07T15:34:40.433759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness3()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T15:34:50.970132Z","iopub.execute_input":"2024-02-07T15:34:50.971065Z","iopub.status.idle":"2024-02-07T16:27:32.622832Z","shell.execute_reply.started":"2024-02-07T15:34:50.971025Z","shell.execute_reply":"2024-02-07T16:27:32.621711Z"},"trusted":true},"execution_count":null,"outputs":[]}]}