{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"6510210038 ขวัญกมล ดำแก้ว","metadata":{}},{"cell_type":"code","source":"# IMPORTANT: RUN THIS CELL IN ORDER TO IMPORT YOUR KAGGLE DATA SOURCES\n# TO THE CORRECT LOCATION (/kaggle/input) IN YOUR NOTEBOOK,\n# THEN FEEL FREE TO DELETE THIS CELL.\n# NOTE: THIS NOTEBOOK ENVIRONMENT DIFFERS FROM KAGGLE'S PYTHON\n# ENVIRONMENT SO THERE MAY BE MISSING LIBRARIES USED BY YOUR\n# NOTEBOOK.\n\nimport os\nimport sys\nfrom tempfile import NamedTemporaryFile\nfrom urllib.request import urlopen\nfrom urllib.parse import unquote, urlparse\nfrom urllib.error import HTTPError\nfrom zipfile import ZipFile\nimport tarfile\nimport shutil\n\nCHUNK_SIZE = 40960\nDATA_SOURCE_MAPPING = 'dogs-vs-cats:https%3A%2F%2Fstorage.googleapis.com%2Fkaggle-competitions-data%2Fkaggle-v2%2F3362%2F31148%2Fbundle%2Farchive.zip%3FX-Goog-Algorithm%3DGOOG4-RSA-SHA256%26X-Goog-Credential%3Dgcp-kaggle-com%2540kaggle-161607.iam.gserviceaccount.com%252F20240217%252Fauto%252Fstorage%252Fgoog4_request%26X-Goog-Date%3D20240217T072502Z%26X-Goog-Expires%3D259200%26X-Goog-SignedHeaders%3Dhost%26X-Goog-Signature%3D19d59836199c8a172e3251083eb1f0a04321c726c9154ab438700abc616afc8277b38b1c60d03db07c76cd2e3bd0d71855167ab138aa13c23292690e23d5f4d00e74cb955bebcd88d8385e040fe5052b9fd7700de7479b699ab5a6637fa1762805df934a8a145daf59f565bc881f36a342ff7290d40b58dcfc1822fd0fa313202e83f88e50d32ce3a27052b87982af81772ea76361076ad3fedbe341d1887279eef99da37424c260e00b86d9c689f89b4fd739d70ef90cf926fabefd65218c1b92855251e156bd3a1638abb8ac570647b2e00347e15dad76e0a37cdf8ceb662a1497eab6dc5989e4e41362a6a7e730cf5e03afd7e5edd791cb920abeb448887c'\n\nKAGGLE_INPUT_PATH='/kaggle/input'\nKAGGLE_WORKING_PATH='/kaggle/working'\nKAGGLE_SYMLINK='kaggle'\n\n!umount /kaggle/input/ 2> /dev/null\nshutil.rmtree('/kaggle/input', ignore_errors=True)\nos.makedirs(KAGGLE_INPUT_PATH, 0o777, exist_ok=True)\nos.makedirs(KAGGLE_WORKING_PATH, 0o777, exist_ok=True)\n\ntry:\n  os.symlink(KAGGLE_INPUT_PATH, os.path.join(\"..\", 'input'), target_is_directory=True)\nexcept FileExistsError:\n  pass\ntry:\n  os.symlink(KAGGLE_WORKING_PATH, os.path.join(\"..\", 'working'), target_is_directory=True)\nexcept FileExistsError:\n  pass\n\nfor data_source_mapping in DATA_SOURCE_MAPPING.split(','):\n    directory, download_url_encoded = data_source_mapping.split(':')\n    download_url = unquote(download_url_encoded)\n    filename = urlparse(download_url).path\n    destination_path = os.path.join(KAGGLE_INPUT_PATH, directory)\n    try:\n        with urlopen(download_url) as fileres, NamedTemporaryFile() as tfile:\n            total_length = fileres.headers['content-length']\n            print(f'Downloading {directory}, {total_length} bytes compressed')\n            dl = 0\n            data = fileres.read(CHUNK_SIZE)\n            while len(data) > 0:\n                dl += len(data)\n                tfile.write(data)\n                done = int(50 * dl / int(total_length))\n                sys.stdout.write(f\"\\r[{'=' * done}{' ' * (50-done)}] {dl} bytes downloaded\")\n                sys.stdout.flush()\n                data = fileres.read(CHUNK_SIZE)\n            if filename.endswith('.zip'):\n              with ZipFile(tfile) as zfile:\n                zfile.extractall(destination_path)\n            else:\n              with tarfile.open(tfile.name) as tarfile:\n                tarfile.extractall(destination_path)\n            print(f'\\nDownloaded and uncompressed: {directory}')\n    except HTTPError as e:\n        print(f'Failed to load (likely expired) {download_url} to path {destination_path}')\n        continue\n    except OSError as e:\n        print(f'Failed to load {download_url} to path {destination_path}')\n        continue\n\nprint('Data source import complete.')","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:14:49.324053Z","iopub.execute_input":"2024-02-24T18:14:49.324436Z","iopub.status.idle":"2024-02-24T18:14:50.365238Z","shell.execute_reply.started":"2024-02-24T18:14:49.324398Z","shell.execute_reply":"2024-02-24T18:14:50.364067Z"},"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-24T18:14:50.370285Z","iopub.execute_input":"2024-02-24T18:14:50.370551Z","iopub.status.idle":"2024-02-24T18:14:50.725783Z","shell.execute_reply.started":"2024-02-24T18:14:50.370525Z","shell.execute_reply":"2024-02-24T18:14:50.724713Z"},"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-24T18:14:50.727142Z","iopub.execute_input":"2024-02-24T18:14:50.727703Z","iopub.status.idle":"2024-02-24T18:15:01.774626Z","shell.execute_reply.started":"2024-02-24T18:14:50.727661Z","shell.execute_reply":"2024-02-24T18:15:01.773688Z"},"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-24T18:15:01.778267Z","iopub.execute_input":"2024-02-24T18:15:01.778688Z","iopub.status.idle":"2024-02-24T18:15:03.003973Z","shell.execute_reply.started":"2024-02-24T18:15:01.778651Z","shell.execute_reply":"2024-02-24T18:15:03.002899Z"},"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-24T18:15:03.005301Z","iopub.execute_input":"2024-02-24T18:15:03.005683Z","iopub.status.idle":"2024-02-24T18:15:04.234602Z","shell.execute_reply.started":"2024-02-24T18:15:03.005646Z","shell.execute_reply":"2024-02-24T18:15:04.233634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:04.235867Z","iopub.execute_input":"2024-02-24T18:15:04.236185Z","iopub.status.idle":"2024-02-24T18:15:04.242506Z","shell.execute_reply.started":"2024-02-24T18:15:04.236158Z","shell.execute_reply":"2024-02-24T18:15:04.241646Z"},"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-24T18:15:04.243795Z","iopub.execute_input":"2024-02-24T18:15:04.244127Z","iopub.status.idle":"2024-02-24T18:15:07.709395Z","shell.execute_reply.started":"2024-02-24T18:15:04.244101Z","shell.execute_reply":"2024-02-24T18:15:07.707805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","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-13T02:49:22.913849Z","iopub.execute_input":"2024-01-13T02:49:22.914548Z","iopub.status.idle":"2024-01-13T02:50:52.450602Z","shell.execute_reply.started":"2024-01-13T02:49:22.91451Z","shell.execute_reply":"2024-01-13T02:50:52.449246Z"}}},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:07.711661Z","iopub.execute_input":"2024-02-24T18:15:07.713137Z","iopub.status.idle":"2024-02-24T18:15:08.694810Z","shell.execute_reply.started":"2024-02-24T18:15:07.713072Z","shell.execute_reply":"2024-02-24T18:15:08.693544Z"},"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')","metadata":{"execution":{"iopub.status.busy":"2024-01-29T06:14:37.691547Z","iopub.execute_input":"2024-01-29T06:14:37.69247Z","iopub.status.idle":"2024-01-29T06:14:38.768512Z","shell.execute_reply.started":"2024-01-29T06:14:37.692428Z","shell.execute_reply":"2024-01-29T06:14:38.766475Z"}}},{"cell_type":"markdown","source":"* print(photos.shape, labels.shape)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T06:14:38.769462Z","iopub.status.idle":"2024-01-29T06:14:38.769902Z","shell.execute_reply.started":"2024-01-29T06:14:38.769701Z","shell.execute_reply":"2024-01-29T06:14:38.769736Z"}}},{"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-24T18:15:08.696640Z","iopub.execute_input":"2024-02-24T18:15:08.697018Z","iopub.status.idle":"2024-02-24T18:15:08.704016Z","shell.execute_reply.started":"2024-02-24T18:15:08.696984Z","shell.execute_reply":"2024-02-24T18:15:08.702851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-24T18:15:08.705560Z","iopub.execute_input":"2024-02-24T18:15:08.706291Z","iopub.status.idle":"2024-02-24T18:15:12.095888Z","shell.execute_reply.started":"2024-02-24T18:15:08.706254Z","shell.execute_reply":"2024-02-24T18:15:12.094945Z"},"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-24T18:15:12.097102Z","iopub.execute_input":"2024-02-24T18:15:12.097566Z","iopub.status.idle":"2024-02-24T18:15:13.182628Z","shell.execute_reply.started":"2024-02-24T18:15:12.097537Z","shell.execute_reply":"2024-02-24T18:15:13.181273Z"},"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-24T18:15:13.184412Z","iopub.execute_input":"2024-02-24T18:15:13.184801Z","iopub.status.idle":"2024-02-24T18:15:14.262267Z","shell.execute_reply.started":"2024-02-24T18:15:13.184767Z","shell.execute_reply":"2024-02-24T18:15:14.261072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l /kaggle/working/test1 | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:14.268261Z","iopub.execute_input":"2024-02-24T18:15:14.268673Z","iopub.status.idle":"2024-02-24T18:15:15.373970Z","shell.execute_reply.started":"2024-02-24T18:15:14.268640Z","shell.execute_reply":"2024-02-24T18:15:15.372838Z"},"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-24T18:15:15.375877Z","iopub.execute_input":"2024-02-24T18:15:15.376358Z","iopub.status.idle":"2024-02-24T18:15:16.331357Z","shell.execute_reply.started":"2024-02-24T18:15:15.376310Z","shell.execute_reply":"2024-02-24T18:15:16.330282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:16.332954Z","iopub.execute_input":"2024-02-24T18:15:16.333463Z","iopub.status.idle":"2024-02-24T18:15:29.248614Z","shell.execute_reply.started":"2024-02-24T18:15:16.333428Z","shell.execute_reply":"2024-02-24T18:15:29.247340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:29.250228Z","iopub.execute_input":"2024-02-24T18:15:29.250598Z","iopub.status.idle":"2024-02-24T18:15:29.262587Z","shell.execute_reply.started":"2024-02-24T18:15:29.250570Z","shell.execute_reply":"2024-02-24T18:15:29.261609Z"},"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(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-02-24T18:15:29.264265Z","iopub.execute_input":"2024-02-24T18:15:29.264649Z","iopub.status.idle":"2024-02-24T18:15:29.283458Z","shell.execute_reply.started":"2024-02-24T18:15:29.264615Z","shell.execute_reply":"2024-02-24T18:15:29.282267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:29.284940Z","iopub.execute_input":"2024-02-24T18:15:29.285347Z","iopub.status.idle":"2024-02-24T18:15:30.363249Z","shell.execute_reply.started":"2024-02-24T18:15:29.285308Z","shell.execute_reply":"2024-02-24T18:15:30.362234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:30.364797Z","iopub.execute_input":"2024-02-24T18:15:30.365129Z","iopub.status.idle":"2024-02-24T18:15:30.419689Z","shell.execute_reply.started":"2024-02-24T18:15:30.365102Z","shell.execute_reply":"2024-02-24T18:15:30.418738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T18:15:30.421048Z","iopub.execute_input":"2024-02-24T18:15:30.421410Z","iopub.status.idle":"2024-02-24T19:14:00.706929Z","shell.execute_reply.started":"2024-02-24T18:15:30.421381Z","shell.execute_reply":"2024-02-24T19:14:00.705724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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.vgg16 import VGG16\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:\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-02-24T19:14:00.708587Z","iopub.execute_input":"2024-02-24T19:14:00.708934Z","iopub.status.idle":"2024-02-24T19:14:00.726015Z","shell.execute_reply.started":"2024-02-24T19:14:00.708905Z","shell.execute_reply":"2024-02-24T19:14:00.724790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications 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\ntarget_size = 299\ndef define_model():\n\t# load model\n\tmodel = Xception(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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=2, 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-02-24T19:14:00.728291Z","iopub.execute_input":"2024-02-24T19:14:00.728719Z","iopub.status.idle":"2024-02-24T19:14:00.746856Z","shell.execute_reply.started":"2024-02-24T19:14:00.728675Z","shell.execute_reply":"2024-02-24T19:14:00.745706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:14:00.748575Z","iopub.execute_input":"2024-02-24T19:14:00.748971Z","iopub.status.idle":"2024-02-24T19:14:03.441286Z","shell.execute_reply.started":"2024-02-24T19:14:00.748934Z","shell.execute_reply":"2024-02-24T19:14:03.440221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:14:03.442802Z","iopub.execute_input":"2024-02-24T19:14:03.443147Z","iopub.status.idle":"2024-02-24T19:21:46.049513Z","shell.execute_reply.started":"2024-02-24T19:14:03.443118Z","shell.execute_reply":"2024-02-24T19:21:46.048628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ResNet152V2\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import ResNet152V2\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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = ResNet152V2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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                       )\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-02-24T19:21:46.051198Z","iopub.execute_input":"2024-02-24T19:21:46.051619Z","iopub.status.idle":"2024-02-24T19:21:46.069375Z","shell.execute_reply.started":"2024-02-24T19:21:46.051581Z","shell.execute_reply":"2024-02-24T19:21:46.068212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:21:46.070643Z","iopub.execute_input":"2024-02-24T19:21:46.070953Z","iopub.status.idle":"2024-02-24T19:21:53.307790Z","shell.execute_reply.started":"2024-02-24T19:21:46.070927Z","shell.execute_reply":"2024-02-24T19:21:53.306685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:21:53.309197Z","iopub.execute_input":"2024-02-24T19:21:53.309564Z","iopub.status.idle":"2024-02-24T19:34:44.486616Z","shell.execute_reply.started":"2024-02-24T19:21:53.309536Z","shell.execute_reply":"2024-02-24T19:34:44.485430Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# InceptionV3\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import InceptionV3\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\ntarget_size = 200\ndef define_model():\n\t# load model\n\tmodel = InceptionV3(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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=4, 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-02-24T19:34:44.488216Z","iopub.execute_input":"2024-02-24T19:34:44.488630Z","iopub.status.idle":"2024-02-24T19:34:44.506665Z","shell.execute_reply.started":"2024-02-24T19:34:44.488597Z","shell.execute_reply":"2024-02-24T19:34:44.505606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:34:44.508194Z","iopub.execute_input":"2024-02-24T19:34:44.509109Z","iopub.status.idle":"2024-02-24T19:34:48.163932Z","shell.execute_reply.started":"2024-02-24T19:34:44.509068Z","shell.execute_reply":"2024-02-24T19:34:48.162960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:34:48.165514Z","iopub.execute_input":"2024-02-24T19:34:48.165819Z","iopub.status.idle":"2024-02-24T19:41:05.696488Z","shell.execute_reply.started":"2024-02-24T19:34:48.165793Z","shell.execute_reply":"2024-02-24T19:41:05.695277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# InceptionResNetV2\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import InceptionResNetV2\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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = InceptionResNetV2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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=4, 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-02-24T19:41:05.698391Z","iopub.execute_input":"2024-02-24T19:41:05.699338Z","iopub.status.idle":"2024-02-24T19:41:05.717584Z","shell.execute_reply.started":"2024-02-24T19:41:05.699296Z","shell.execute_reply":"2024-02-24T19:41:05.716503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:41:05.719028Z","iopub.execute_input":"2024-02-24T19:41:05.719386Z","iopub.status.idle":"2024-02-24T19:41:14.718394Z","shell.execute_reply.started":"2024-02-24T19:41:05.719358Z","shell.execute_reply":"2024-02-24T19:41:14.717264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:41:14.719790Z","iopub.execute_input":"2024-02-24T19:41:14.720636Z","iopub.status.idle":"2024-02-24T19:51:15.965480Z","shell.execute_reply.started":"2024-02-24T19:41:14.720579Z","shell.execute_reply":"2024-02-24T19:51:15.964262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ResNet50\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications 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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = ResNet152V2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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                       )\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-02-24T19:51:15.966779Z","iopub.execute_input":"2024-02-24T19:51:15.967095Z","iopub.status.idle":"2024-02-24T19:51:15.985108Z","shell.execute_reply.started":"2024-02-24T19:51:15.967066Z","shell.execute_reply":"2024-02-24T19:51:15.983906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:51:15.986527Z","iopub.execute_input":"2024-02-24T19:51:15.986845Z","iopub.status.idle":"2024-02-24T19:51:23.144145Z","shell.execute_reply.started":"2024-02-24T19:51:15.986819Z","shell.execute_reply":"2024-02-24T19:51:23.143098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T19:51:23.145618Z","iopub.execute_input":"2024-02-24T19:51:23.145941Z","iopub.status.idle":"2024-02-24T20:03:55.103257Z","shell.execute_reply.started":"2024-02-24T19:51:23.145907Z","shell.execute_reply":"2024-02-24T20:03:55.102374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MobileNet\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import MobileNet\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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = ResNet152V2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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                       )\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-02-24T20:03:55.104770Z","iopub.execute_input":"2024-02-24T20:03:55.105190Z","iopub.status.idle":"2024-02-24T20:03:55.122613Z","shell.execute_reply.started":"2024-02-24T20:03:55.105148Z","shell.execute_reply":"2024-02-24T20:03:55.121649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:03:55.123749Z","iopub.execute_input":"2024-02-24T20:03:55.124037Z","iopub.status.idle":"2024-02-24T20:04:02.035596Z","shell.execute_reply.started":"2024-02-24T20:03:55.124013Z","shell.execute_reply":"2024-02-24T20:04:02.034629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:04:02.036855Z","iopub.execute_input":"2024-02-24T20:04:02.037179Z","iopub.status.idle":"2024-02-24T20:16:24.301919Z","shell.execute_reply.started":"2024-02-24T20:04:02.037153Z","shell.execute_reply":"2024-02-24T20:16:24.300813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MobileNetV2\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import MobileNetV2\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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = ResNet152V2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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                       )\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-02-24T20:16:24.308822Z","iopub.execute_input":"2024-02-24T20:16:24.309309Z","iopub.status.idle":"2024-02-24T20:16:24.327046Z","shell.execute_reply.started":"2024-02-24T20:16:24.309276Z","shell.execute_reply":"2024-02-24T20:16:24.325907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:16:24.328332Z","iopub.execute_input":"2024-02-24T20:16:24.328661Z","iopub.status.idle":"2024-02-24T20:16:31.308479Z","shell.execute_reply.started":"2024-02-24T20:16:24.328635Z","shell.execute_reply":"2024-02-24T20:16:31.307420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:16:31.309861Z","iopub.execute_input":"2024-02-24T20:16:31.310172Z","iopub.status.idle":"2024-02-24T20:29:12.085820Z","shell.execute_reply.started":"2024-02-24T20:16:31.310146Z","shell.execute_reply":"2024-02-24T20:29:12.084830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MobileNetV3Small\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.vgg19 import VGG19\nfrom keras.applications import MobileNetV3Small\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\ntarget_size = 250\ndef define_model():\n\t# load model\n\tmodel = ResNet152V2(include_top=False, input_shape=(target_size, target_size, 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=(target_size, target_size))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(target_size, target_size))\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                       )\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-02-24T20:29:12.087825Z","iopub.execute_input":"2024-02-24T20:29:12.088288Z","iopub.status.idle":"2024-02-24T20:29:12.106047Z","shell.execute_reply.started":"2024-02-24T20:29:12.088232Z","shell.execute_reply":"2024-02-24T20:29:12.104940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:29:12.107331Z","iopub.execute_input":"2024-02-24T20:29:12.107717Z","iopub.status.idle":"2024-02-24T20:29:19.041010Z","shell.execute_reply.started":"2024-02-24T20:29:12.107683Z","shell.execute_reply":"2024-02-24T20:29:19.039957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-24T20:29:19.042317Z","iopub.execute_input":"2024-02-24T20:29:19.042617Z","iopub.status.idle":"2024-02-24T20:41:52.544819Z","shell.execute_reply.started":"2024-02-24T20:29:19.042592Z","shell.execute_reply":"2024-02-24T20:41:52.543531Z"},"trusted":true},"execution_count":null,"outputs":[]}]}