{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-29T14:12:12.521044Z","iopub.execute_input":"2024-01-29T14:12:12.521307Z","iopub.status.idle":"2024-01-29T14:12:12.861353Z","shell.execute_reply.started":"2024-01-29T14:12:12.521283Z","shell.execute_reply":"2024-01-29T14:12:12.860382Z"},"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-29T14:15:34.544527Z","iopub.execute_input":"2024-01-29T14:15:34.545024Z","iopub.status.idle":"2024-01-29T14:15:47.999890Z","shell.execute_reply.started":"2024-01-29T14:15:34.544994Z","shell.execute_reply":"2024-01-29T14:15:47.999084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Plot Dog and Cat Photos**","metadata":{}},{"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-28T07:05:01.852524Z","iopub.execute_input":"2024-01-28T07:05:01.852895Z","iopub.status.idle":"2024-01-28T07:05:03.118548Z","shell.execute_reply.started":"2024-01-28T07:05:01.852865Z","shell.execute_reply":"2024-01-28T07:05:03.117584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:05:17.704683Z","iopub.execute_input":"2024-01-28T07:05:17.705035Z","iopub.status.idle":"2024-01-28T07:05:18.912769Z","shell.execute_reply.started":"2024-01-28T07:05:17.705002Z","shell.execute_reply":"2024-01-28T07:05:18.911828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Select Standardized Photo Size** /\nPre-Process Photo Sizes (ไม่บังคับ)","metadata":{}},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\n# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:05:04.150147Z","iopub.execute_input":"2024-01-28T12:05:04.150544Z","iopub.status.idle":"2024-01-28T12:06:47.030195Z","shell.execute_reply.started":"2024-01-28T12:05:04.150515Z","shell.execute_reply":"2024-01-28T12:06:47.029141Z"},"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-28T12:08:26.846752Z","iopub.execute_input":"2024-01-28T12:08:26.847496Z","iopub.status.idle":"2024-01-28T12:09:21.651165Z","shell.execute_reply.started":"2024-01-28T12:08:26.847437Z","shell.execute_reply":"2024-01-28T12:09:21.649988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Pre-Process Photos into Standard Directories**","metadata":{}},{"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    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir\n        makedirs(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    src = src_directory + '/' + file\n    dst_dir = 'train/'\n    if random() < val_ratio:\n        dst_dir = 'test/'\n    if file.startswith('cat'):\n        dst = dataset_home + dst_dir + 'cats/'  + file\n        copyfile(src, dst)\n    elif file.startswith('dog'):\n        dst = dataset_home + dst_dir + 'dogs/'  + file\n        copyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:09:27.795442Z","iopub.execute_input":"2024-01-28T12:09:27.795851Z","iopub.status.idle":"2024-01-28T12:09:43.207237Z","shell.execute_reply.started":"2024-01-28T12:09:27.795822Z","shell.execute_reply":"2024-01-28T12:09:43.206164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:10:34.240398Z","iopub.execute_input":"2024-01-28T07:10:34.240820Z","iopub.status.idle":"2024-01-28T07:10:48.907260Z","shell.execute_reply.started":"2024-01-28T07:10:34.240786Z","shell.execute_reply":"2024-01-28T07:10:48.905811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:10:55.438270Z","iopub.execute_input":"2024-01-28T07:10:55.438669Z","iopub.status.idle":"2024-01-28T07:10:55.454887Z","shell.execute_reply.started":"2024-01-28T07:10:55.438642Z","shell.execute_reply":"2024-01-28T07:10:55.453926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**One Block VGG Model**","metadata":{}},{"cell_type":"code","source":"import 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","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:10:23.620139Z","iopub.execute_input":"2024-01-28T12:10:23.621011Z","iopub.status.idle":"2024-01-28T12:10:33.862686Z","shell.execute_reply.started":"2024-01-28T12:10:23.620977Z","shell.execute_reply":"2024-01-28T12:10:33.861780Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:10:51.853519Z","iopub.execute_input":"2024-01-28T12:10:51.854552Z","iopub.status.idle":"2024-01-28T12:10:51.861733Z","shell.execute_reply.started":"2024-01-28T12:10:51.854516Z","shell.execute_reply":"2024-01-28T12:10:51.860496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\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\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\n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()\n    \n    pyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:10:55.815533Z","iopub.execute_input":"2024-01-28T12:10:55.816309Z","iopub.status.idle":"2024-01-28T12:10:55.822709Z","shell.execute_reply.started":"2024-01-28T12:10:55.816277Z","shell.execute_reply":"2024-01-28T12:10:55.821712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n    \n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\n    \n    # prepare iterators\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n    \n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n    \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n\n    # learning curves\n    summarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T12:10:58.792478Z","iopub.execute_input":"2024-01-28T12:10:58.793364Z","iopub.status.idle":"2024-01-28T12:26:33.549249Z","shell.execute_reply.started":"2024-01-28T12:10:58.793332Z","shell.execute_reply":"2024-01-28T12:26:33.548293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Two Block VGG Model**","metadata":{}},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:59:11.980144Z","iopub.execute_input":"2024-01-28T07:59:11.981039Z","iopub.status.idle":"2024-01-28T07:59:11.989165Z","shell.execute_reply.started":"2024-01-28T07:59:11.980990Z","shell.execute_reply":"2024-01-28T07:59:11.988187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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    \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    \n    # show plot (no need to save)\n    pyplot.show()\n    \n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:59:18.845833Z","iopub.execute_input":"2024-01-28T07:59:18.846576Z","iopub.status.idle":"2024-01-28T07:59:18.853407Z","shell.execute_reply.started":"2024-01-28T07:59:18.846541Z","shell.execute_reply":"2024-01-28T07:59:18.852320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run_test_harness():\n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\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=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(200, 200))\n    \n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n                                  validation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=0)\n    \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)  \n    \n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T07:59:24.323820Z","iopub.execute_input":"2024-01-28T07:59:24.324232Z","iopub.status.idle":"2024-01-28T08:07:42.686123Z","shell.execute_reply.started":"2024-01-28T07:59:24.324202Z","shell.execute_reply":"2024-01-28T08:07:42.685158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Three Block VGG Model**","metadata":{}},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:09:41.110153Z","iopub.execute_input":"2024-01-28T08:09:41.111059Z","iopub.status.idle":"2024-01-28T08:09:41.119383Z","shell.execute_reply.started":"2024-01-28T08:09:41.111024Z","shell.execute_reply":"2024-01-28T08:09:41.118374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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    \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    \n    # show plot (no need to save)\n    pyplot.show()\n    \n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:09:48.107216Z","iopub.execute_input":"2024-01-28T08:09:48.107991Z","iopub.status.idle":"2024-01-28T08:09:48.114802Z","shell.execute_reply.started":"2024-01-28T08:09:48.107940Z","shell.execute_reply":"2024-01-28T08:09:48.113803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run_test_harness():\n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\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=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(200, 200))\n    \n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n                                  validation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=0)\n    \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)  \n    \n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:09:51.896829Z","iopub.execute_input":"2024-01-28T08:09:51.897621Z","iopub.status.idle":"2024-01-28T08:17:44.475849Z","shell.execute_reply.started":"2024-01-28T08:09:51.897588Z","shell.execute_reply":"2024-01-28T08:17:44.474925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Dropout Regularization**","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:18:37.411849Z","iopub.execute_input":"2024-01-28T08:18:37.412903Z","iopub.status.idle":"2024-01-28T08:18:37.418686Z","shell.execute_reply.started":"2024-01-28T08:18:37.412867Z","shell.execute_reply":"2024-01-28T08:18:37.417678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.2))\n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.2))\n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.2))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dropout(0.5))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:18:45.870614Z","iopub.execute_input":"2024-01-28T08:18:45.871484Z","iopub.status.idle":"2024-01-28T08:18:45.881188Z","shell.execute_reply.started":"2024-01-28T08:18:45.871444Z","shell.execute_reply":"2024-01-28T08:18:45.880033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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    \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    \n    # show plot (no need to save)\n    pyplot.show()\n    \n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:18:48.849510Z","iopub.execute_input":"2024-01-28T08:18:48.850278Z","iopub.status.idle":"2024-01-28T08:18:48.857077Z","shell.execute_reply.started":"2024-01-28T08:18:48.850247Z","shell.execute_reply":"2024-01-28T08:18:48.855897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def run_test_harness():\n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\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=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(200, 200))\n    \n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n                                  validation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=0)\n    \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)  \n    \n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:18:51.800230Z","iopub.execute_input":"2024-01-28T08:18:51.800926Z","iopub.status.idle":"2024-01-28T08:26:52.748151Z","shell.execute_reply.started":"2024-01-28T08:18:51.800893Z","shell.execute_reply":"2024-01-28T08:26:52.746944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Image Data Augmentation**","metadata":{}},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:27:16.167716Z","iopub.execute_input":"2024-01-28T08:27:16.168620Z","iopub.status.idle":"2024-01-28T08:27:16.176857Z","shell.execute_reply.started":"2024-01-28T08:27:16.168584Z","shell.execute_reply":"2024-01-28T08:27:16.175921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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    \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    \n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()\n    \n    pyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:27:19.236728Z","iopub.execute_input":"2024-01-28T08:27:19.237605Z","iopub.status.idle":"2024-01-28T08:27:19.244566Z","shell.execute_reply.started":"2024-01-28T08:27:19.237572Z","shell.execute_reply":"2024-01-28T08:27:19.243310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n\n    # create data generators\n    train_datagen = ImageDataGenerator(rescale=1.0/255.0,\n    width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\n    test_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n    # prepare iterators\n    train_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n    test_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n\n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n    validation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=0)\n\n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)\n    \n # entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:27:25.417978Z","iopub.execute_input":"2024-01-28T08:27:25.418356Z","iopub.status.idle":"2024-01-28T08:57:38.899100Z","shell.execute_reply.started":"2024-01-28T08:27:25.418329Z","shell.execute_reply":"2024-01-28T08:57:38.898116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Explore Transfer Learning**","metadata":{}},{"cell_type":"code","source":"import 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","metadata":{"execution":{"iopub.status.busy":"2024-01-28T08:59:36.351247Z","iopub.execute_input":"2024-01-28T08:59:36.352202Z","iopub.status.idle":"2024-01-28T08:59:36.357644Z","shell.execute_reply.started":"2024-01-28T08:59:36.352164Z","shell.execute_reply":"2024-01-28T08:59:36.356595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\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\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-28T09:00:01.631793Z","iopub.execute_input":"2024-01-28T09:00:01.632574Z","iopub.status.idle":"2024-01-28T09:00:01.640386Z","shell.execute_reply.started":"2024-01-28T09:00:01.632538Z","shell.execute_reply":"2024-01-28T09:00:01.639229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\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 \n    # save plot to file\n    #filename = sys.argv[0].split('/')[-1]\n    #pyplot.savefig(filename + '_plot.png')\n    #pyplot.close()\n    \n    pyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T09:00:09.181594Z","iopub.execute_input":"2024-01-28T09:00:09.181988Z","iopub.status.idle":"2024-01-28T09:00:09.189263Z","shell.execute_reply.started":"2024-01-28T09:00:09.181941Z","shell.execute_reply":"2024-01-28T09:00:09.188346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n    \n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(featurewise_center=True)\n\n    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\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\n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n    validation_data=test_it, validation_steps=len(test_it), epochs=5, verbose=1)\n\n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n\n    # learning curves\n    summarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-28T09:58:55.081613Z","iopub.execute_input":"2024-01-28T09:58:55.082023Z","iopub.status.idle":"2024-01-28T10:08:31.620927Z","shell.execute_reply.started":"2024-01-28T09:58:55.081982Z","shell.execute_reply":"2024-01-28T10:08:31.619752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**How to Finalize the Model and Make Predictions**","metadata":{}},{"cell_type":"code","source":"from os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\n# create directories\ndataset_home = '/kaggle/working/finalize_dogs_vs_cats/'\n# create label subdirectories\nlabeldirs = ['dogs/', 'cats/']\nfor labldir in labeldirs:\n    newdir = dataset_home + labldir\n    makedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:16:51.571778Z","iopub.execute_input":"2024-01-29T14:16:51.572117Z","iopub.status.idle":"2024-01-29T14:16:51.578010Z","shell.execute_reply.started":"2024-01-29T14:16:51.572092Z","shell.execute_reply":"2024-01-29T14:16:51.577093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\n# create directories\ndataset_home = '/kaggle/working/finalize_dogs_vs_cats/'\n# create label subdirectories\nlabeldirs = ['dogs/', 'cats/']\nfor labldir in labeldirs:\n    newdir = dataset_home + labldir\n    makedirs(newdir, exist_ok=True)\n# copy training dataset images into subdirectories\nsrc_directory = '/kaggle/working/train'\nfor file in listdir(src_directory):\n    src = src_directory + '/' + file\n    if file.startswith('cat'):\n        dst = dataset_home + 'cats/'  + file\n        copyfile(src, dst)\n    elif file.startswith('dog'):\n        dst = dataset_home + 'dogs/'  + file\n        copyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:17:49.016132Z","iopub.execute_input":"2024-01-29T14:17:49.016939Z","iopub.status.idle":"2024-01-29T14:17:51.550672Z","shell.execute_reply.started":"2024-01-29T14:17:49.016903Z","shell.execute_reply":"2024-01-29T14:17:51.549697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Save Final Model**","metadata":{}},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:17:58.824754Z","iopub.execute_input":"2024-01-29T14:17:58.825482Z","iopub.status.idle":"2024-01-29T14:18:10.528757Z","shell.execute_reply.started":"2024-01-29T14:17:58.825445Z","shell.execute_reply":"2024-01-29T14:18:10.527950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\n\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\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\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:18:22.467879Z","iopub.execute_input":"2024-01-29T14:18:22.469025Z","iopub.status.idle":"2024-01-29T14:18:22.475730Z","shell.execute_reply.started":"2024-01-29T14:18:22.468990Z","shell.execute_reply":"2024-01-29T14:18:22.474762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n\n    # define model\n    model = define_model()\n\n    # create data generator\n    datagen = ImageDataGenerator(featurewise_center=True)\n\n    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\n\n    # prepare iterator\n    train_it = datagen.flow_from_directory('finalize_dogs_vs_cats/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))\n\n    # fit model\n    model.fit_generator(train_it, steps_per_epoch=len(train_it), epochs=10, verbose=0)\n\n    # save model\n    model.save('final_model.h5')\n     \n# entry point, run the test harness\nrun_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:18:27.565884Z","iopub.execute_input":"2024-01-29T14:18:27.566695Z","iopub.status.idle":"2024-01-29T14:36:28.784938Z","shell.execute_reply.started":"2024-01-29T14:18:27.566656Z","shell.execute_reply":"2024-01-29T14:36:28.783902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Make Prediction**","metadata":{}},{"cell_type":"code","source":"# make a prediction for a new image.\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model\n \n# load and prepare the image\ndef load_image(filename):\n\n    # load the image\n    img = load_img(filename, target_size=(224, 224))\n\n    # convert to array\n    img = img_to_array(img)\n\n    # reshape into a single sample with 3 channels\n    img = img.reshape(1, 224, 224, 3)\n\n    # center pixel data\n    img = img.astype('float32')\n    img = img - [123.68, 116.779, 103.939]\n\n    return img","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:37:46.878755Z","iopub.execute_input":"2024-01-29T14:37:46.879409Z","iopub.status.idle":"2024-01-29T14:37:46.885730Z","shell.execute_reply.started":"2024-01-29T14:37:46.879377Z","shell.execute_reply":"2024-01-29T14:37:46.884754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load an image and predict the class\ndef run_example():\n\n    # load the image\n    img = load_image('/kaggle/working/test1/166.jpg')\n\n    # load model\n    model = load_model('final_model.h5')\n\n    # predict the class\n    result = model.predict(img)\n    print(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-01-29T14:39:26.905721Z","iopub.execute_input":"2024-01-29T14:39:26.906476Z","iopub.status.idle":"2024-01-29T14:39:28.159391Z","shell.execute_reply.started":"2024-01-29T14:39:26.906434Z","shell.execute_reply":"2024-01-29T14:39:28.158410Z"},"trusted":true},"execution_count":null,"outputs":[]}]}