{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{},"execution_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-07T06:21:56.609820Z","iopub.execute_input":"2024-02-07T06:21:56.610185Z","iopub.status.idle":"2024-02-07T06:21:56.949466Z","shell.execute_reply.started":"2024-02-07T06:21:56.610159Z","shell.execute_reply":"2024-02-07T06:21:56.948575Z"},"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-07T06:21:56.951038Z","iopub.execute_input":"2024-02-07T06:21:56.951405Z","iopub.status.idle":"2024-02-07T06:22:12.963707Z","shell.execute_reply.started":"2024-02-07T06:21:56.951378Z","shell.execute_reply":"2024-02-07T06:22:12.962706Z"},"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-07T06:22:12.964852Z","iopub.execute_input":"2024-02-07T06:22:12.965164Z","iopub.status.idle":"2024-02-07T06:22:14.163383Z","shell.execute_reply.started":"2024-02-07T06:22:12.965138Z","shell.execute_reply":"2024-02-07T06:22:14.162471Z"},"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-07T06:22:14.165298Z","iopub.execute_input":"2024-02-07T06:22:14.165586Z","iopub.status.idle":"2024-02-07T06:22:15.304670Z","shell.execute_reply.started":"2024-02-07T06:22:14.165561Z","shell.execute_reply":"2024-02-07T06:22:15.303909Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:22:15.305758Z","iopub.execute_input":"2024-02-07T06:22:15.306092Z","iopub.status.idle":"2024-02-07T06:22:15.312256Z","shell.execute_reply.started":"2024-02-07T06:22:15.306053Z","shell.execute_reply":"2024-02-07T06:22:15.311371Z"},"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-07T06:22:15.313571Z","iopub.execute_input":"2024-02-07T06:22:15.314104Z","iopub.status.idle":"2024-02-07T06:22:27.270999Z","shell.execute_reply.started":"2024-02-07T06:22:15.314071Z","shell.execute_reply":"2024-02-07T06:22:27.270025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n#for file in listdir(folder[:10_000]): # select 10_000 images\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:22:27.272201Z","iopub.execute_input":"2024-02-07T06:22:27.272891Z","iopub.status.idle":"2024-02-07T06:23:53.711442Z","shell.execute_reply.started":"2024-02-07T06:22:27.272828Z","shell.execute_reply":"2024-02-07T06:23:53.710591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:23:53.712760Z","iopub.execute_input":"2024-02-07T06:23:53.713083Z","iopub.status.idle":"2024-02-07T06:23:55.095119Z","shell.execute_reply.started":"2024-02-07T06:23:53.713053Z","shell.execute_reply":"2024-02-07T06:23:55.093920Z"},"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-02-07T06:23:55.096950Z","iopub.execute_input":"2024-02-07T06:23:55.097839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create directories\nimport os\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tos.makedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:25:17.486197Z","iopub.execute_input":"2024-02-07T06:25:17.487167Z","iopub.status.idle":"2024-02-07T06:25:17.530088Z","shell.execute_reply.started":"2024-02-07T06:25:17.487121Z","shell.execute_reply":"2024-02-07T06:25:17.529164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:25:18.452019Z","iopub.execute_input":"2024-02-07T06:25:18.453085Z","iopub.status.idle":"2024-02-07T06:25:34.059328Z","shell.execute_reply.started":"2024-02-07T06:25:18.453047Z","shell.execute_reply":"2024-02-07T06:25:34.058308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l test1 | wc","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:25:34.061377Z","iopub.execute_input":"2024-02-07T06:25:34.062081Z","iopub.status.idle":"2024-02-07T06:25:35.281804Z","shell.execute_reply.started":"2024-02-07T06:25:34.062039Z","shell.execute_reply":"2024-02-07T06:25:35.280621Z"},"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-07T06:25:35.283511Z","iopub.execute_input":"2024-02-07T06:25:35.283929Z","iopub.status.idle":"2024-02-07T06:25:36.346831Z","shell.execute_reply.started":"2024-02-07T06:25:35.283889Z","shell.execute_reply":"2024-02-07T06:25:36.345931Z"},"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-07T06:25:36.349966Z","iopub.execute_input":"2024-02-07T06:25:36.350345Z","iopub.status.idle":"2024-02-07T06:25:37.375907Z","shell.execute_reply.started":"2024-02-07T06:25:36.350310Z","shell.execute_reply":"2024-02-07T06:25:37.374588Z"},"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":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:25:37.377369Z","iopub.execute_input":"2024-02-07T06:25:37.377697Z","iopub.status.idle":"2024-02-07T06:25:50.915786Z","shell.execute_reply.started":"2024-02-07T06:25:37.377668Z","shell.execute_reply":"2024-02-07T06:25:50.914641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-07T06:25:50.917162Z","iopub.execute_input":"2024-02-07T06:25:50.917470Z","iopub.status.idle":"2024-02-07T06:25:50.933531Z","shell.execute_reply.started":"2024-02-07T06:25:50.917442Z","shell.execute_reply":"2024-02-07T06:25:50.932642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# VGG19","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg19 import VGG19\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n    # define cnn model\ndef define_model():\n        # load model\n    model = VGG19(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers[:15]:\n        layer.trainable = False\n        # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n        # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n        # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n    # plot diagnostic learning curves\ndef summarize_diagnostics(history):\n        # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n        # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n        # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n    # run the test harness for evaluating a model\ndef run_test_harness():\n        # define model\n    model = define_model()\n        # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n        # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n        # fit model\n    history = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=10, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n        # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n        # learning curves\n    summarize_diagnostics(history)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T07:01:08.897909Z","iopub.execute_input":"2024-02-07T07:01:08.898800Z","iopub.status.idle":"2024-02-07T07:01:08.915431Z","shell.execute_reply.started":"2024-02-07T07:01:08.898756Z","shell.execute_reply":"2024-02-07T07:01:08.914593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n    # remove Thai comment for execution\n    run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T07:01:10.589955Z","iopub.execute_input":"2024-02-07T07:01:10.590670Z","iopub.status.idle":"2024-02-07T07:54:43.414188Z","shell.execute_reply.started":"2024-02-07T07:01:10.590637Z","shell.execute_reply":"2024-02-07T07:54:43.413108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.applications import ResNet50\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten, Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model2():\n    # load model\n    model2 = ResNet50(include_top=False, input_shape=(224, 224, 3))\n    # mark loaded layers as not trainable\n    for layer in model2.layers:\n        layer.trainable = False\n    # add new classifier layers\n    flat1 = Flatten()(model2.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    dropout = Dropout(0.5)(class1)\n    output = Dense(1, activation='sigmoid')(dropout)\n    # define new model\n    model2 = Model(inputs=model2.inputs, outputs=output)\n    # compile model\n    opt = SGD(lr=0.0001, momentum=0.9)\n    model2.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model2\n\n# plot diagnostic learning curves\ndef summarize_diagnostics2(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = f\"plot_{int(time.time())}.png\"\n    pyplot.savefig(filename)\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness2():\n    # define model\n    model2 = define_model2()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n    )\n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=128, target_size=(224, 224))\n    # fit model\n    history = model2.fit(train_it, steps_per_epoch=len(train_it),\n                         validation_data=test_it, \n                         validation_steps=len(test_it), \n                         epochs=10, verbose=1,callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model2.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics2(history)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-02-07T09:29:31.286417Z","iopub.execute_input":"2024-02-07T09:29:31.286837Z","iopub.status.idle":"2024-02-07T09:29:31.301944Z","shell.execute_reply.started":"2024-02-07T09:29:31.286788Z","shell.execute_reply":"2024-02-07T09:29:31.300918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness2()","metadata":{"execution":{"iopub.status.busy":"2024-02-07T09:29:31.884720Z","iopub.execute_input":"2024-02-07T09:29:31.885638Z","iopub.status.idle":"2024-02-07T09:32:15.430717Z","shell.execute_reply.started":"2024-02-07T09:29:31.885605Z","shell.execute_reply":"2024-02-07T09:32:15.428890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\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[:15]:\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.0001, 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(\n        rescale=1./255,\n        rotation_range=40,\n        width_shift_range=0.2,\n        height_shift_range=0.2,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        fill_mode='nearest'\n\t)\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=128, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=128, 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=10, verbose=1,\n                        callbacks=[PlotLossesKeras()])\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# remove Thai comment for execution\nrun_test_harness()","metadata":{"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=50, 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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}