{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30635,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Dog & Cat classification 2024\n### ศุภฤกษ์ ชัยศิริเลิศ - '6610210508'","metadata":{}},{"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-06T01:56:45.259765Z","iopub.execute_input":"2024-02-06T01:56:45.260137Z","iopub.status.idle":"2024-02-06T01:56:45.695650Z","shell.execute_reply.started":"2024-02-06T01:56:45.260106Z","shell.execute_reply":"2024-02-06T01:56:45.694452Z"},"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-06T01:56:49.077160Z","iopub.execute_input":"2024-02-06T01:56:49.077691Z","iopub.status.idle":"2024-02-06T01:57:05.415851Z","shell.execute_reply.started":"2024-02-06T01:56:49.077660Z","shell.execute_reply":"2024-02-06T01:57:05.414510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\ntrain_folder = 'train/'\n\n# define location of dataset\nfolder = train_folder\n# plot first few images\nfor i in range(9):\n        # define subplot\n        pyplot.subplot(330 + 1 + i)\n        # define filename\n        filename = folder + 'dog.' + str(i) + '.jpg'\n        # load image pixels\n        image = imread(filename)\n        # plot raw pixel data\n        pyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T01:57:05.418274Z","iopub.execute_input":"2024-02-06T01:57:05.419511Z","iopub.status.idle":"2024-02-06T01:57:07.052428Z","shell.execute_reply.started":"2024-02-06T01:57:05.419464Z","shell.execute_reply":"2024-02-06T01:57:07.051342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\n#from matplotlib import pyplot\n#from matplotlib.image import imread\n# define location of dataset\n#folder = 'train/'\n# plot first few images\nfor i in range(9):\n        # define subplot\n        pyplot.subplot(330 + 1 + i)\n        # define filename\n        filename = folder + 'cat.' + str(i) + '.jpg'\n        # load image pixels\n        image = imread(filename)\n        # plot raw pixel data\n        pyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T01:57:07.053827Z","iopub.execute_input":"2024-02-06T01:57:07.054221Z","iopub.status.idle":"2024-02-06T01:57:08.476406Z","shell.execute_reply.started":"2024-02-06T01:57:07.054185Z","shell.execute_reply":"2024-02-06T01:57:08.475334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_folder","metadata":{"execution":{"iopub.status.busy":"2024-02-06T01:57:08.478744Z","iopub.execute_input":"2024-02-06T01:57:08.479643Z","iopub.status.idle":"2024-02-06T01:57:08.486567Z","shell.execute_reply.started":"2024-02-06T01:57:08.479590Z","shell.execute_reply":"2024-02-06T01:57:08.485452Z"},"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":{"scrolled":true,"_kg_hide-input":false,"execution":{"iopub.status.busy":"2024-02-06T01:57:19.528899Z","iopub.execute_input":"2024-02-06T01:57:19.529300Z","iopub.status.idle":"2024-02-06T01:57:39.062614Z","shell.execute_reply.started":"2024-02-06T01:57:19.529268Z","shell.execute_reply":"2024-02-06T01:57:39.061590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Define location of dataset","metadata":{}},{"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        # determine class\n        output = 0.0\n        if file.startswith('dog'):\n            output = 1.0\n        # load image\n        photo = load_img(folder + file, target_size=(200, 200))\n        # convert to numpy array\n        photo = img_to_array(photo)\n        # store\n        photos.append(photo)\n        labels.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-06T01:57:46.618226Z","iopub.execute_input":"2024-02-06T01:57:46.618936Z","iopub.status.idle":"2024-02-06T01:59:18.639584Z","shell.execute_reply.started":"2024-02-06T01:57:46.618902Z","shell.execute_reply":"2024-02-06T01:59:18.638423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-02-06T01:59:18.641989Z","iopub.execute_input":"2024-02-06T01:59:18.642995Z","iopub.status.idle":"2024-02-06T01:59:20.322557Z","shell.execute_reply.started":"2024-02-06T01:59:18.642949Z","shell.execute_reply":"2024-02-06T01:59:20.320932Z"},"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        # create label subdirectories\n        labeldirs = ['dogs/', 'cats/']\n        for labldir in labeldirs:\n            newdir = dataset_home + subdir + labldir\n            os.makedirs(newdir, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T01:59:20.324441Z","iopub.execute_input":"2024-02-06T01:59:20.324927Z","iopub.status.idle":"2024-02-06T01:59:20.333040Z","shell.execute_reply.started":"2024-02-06T01:59:20.324883Z","shell.execute_reply":"2024-02-06T01:59:20.331792Z"},"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        # 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-02-06T01:59:20.335678Z","iopub.execute_input":"2024-02-06T01:59:20.336046Z","iopub.status.idle":"2024-02-06T01:59:38.160555Z","shell.execute_reply.started":"2024-02-06T01:59:20.336015Z","shell.execute_reply":"2024-02-06T01:59:38.159238Z"},"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-06T01:59:38.162354Z","iopub.execute_input":"2024-02-06T01:59:38.163807Z","iopub.status.idle":"2024-02-06T01:59:39.904644Z","shell.execute_reply.started":"2024-02-06T01:59:38.163760Z","shell.execute_reply":"2024-02-06T01:59:39.903375Z"},"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-06T01:59:39.906393Z","iopub.execute_input":"2024-02-06T01:59:39.906773Z","iopub.status.idle":"2024-02-06T01:59:41.391032Z","shell.execute_reply.started":"2024-02-06T01:59:39.906736Z","shell.execute_reply":"2024-02-06T01:59:41.389714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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        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        # compile model\n        opt = SGD(lr=0.001, 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(rescale=1.0/255.0)\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        # 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=1)\n        # evaluate model\n        _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n        print('> %.3f' % (acc * 100.0))\n        # learning curves\n        summarize_diagnostics(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:02.357473Z","iopub.execute_input":"2024-02-06T02:00:02.357935Z","iopub.status.idle":"2024-02-06T02:00:02.376645Z","shell.execute_reply.started":"2024-02-06T02:00:02.357896Z","shell.execute_reply":"2024-02-06T02:00:02.375607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot -q","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:07.772666Z","iopub.execute_input":"2024-02-06T02:00:07.773056Z","iopub.status.idle":"2024-02-06T02:00:27.923122Z","shell.execute_reply.started":"2024-02-06T02:00:07.773028Z","shell.execute_reply":"2024-02-06T02:00:27.921538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:40.692924Z","iopub.execute_input":"2024-02-06T02:00:40.693399Z","iopub.status.idle":"2024-02-06T02:00:40.714029Z","shell.execute_reply.started":"2024-02-06T02:00:40.693361Z","shell.execute_reply":"2024-02-06T02:00:40.712475Z"},"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    # load model\n    model = VGG16(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=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(224, 224))\n    # fit model\n    history = model.fit(train_it, \n                        steps_per_epoch=len(train_it),\n                        validation_data=test_it, \n                        validation_steps=len(test_it), \n                        epochs=11, verbose=1,\n                        callbacks=[PlotLossesKeras()])\n    # evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=1)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics(history)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:42.322120Z","iopub.execute_input":"2024-02-06T02:00:42.323105Z","iopub.status.idle":"2024-02-06T02:00:42.344742Z","shell.execute_reply.started":"2024-02-06T02:00:42.323062Z","shell.execute_reply":"2024-02-06T02:00:42.342366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:48.518888Z","iopub.execute_input":"2024-02-06T02:00:48.519322Z","iopub.status.idle":"2024-02-06T02:00:51.927755Z","shell.execute_reply.started":"2024-02-06T02:00:48.519287Z","shell.execute_reply":"2024-02-06T02:00:51.926732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:54.837793Z","iopub.execute_input":"2024-02-06T02:00:54.838202Z","iopub.status.idle":"2024-02-06T02:00:54.897329Z","shell.execute_reply.started":"2024-02-06T02:00:54.838151Z","shell.execute_reply":"2024-02-06T02:00:54.896228Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"run_test_harness()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T02:00:58.706320Z","iopub.execute_input":"2024-02-06T02:00:58.707206Z","iopub.status.idle":"2024-02-06T03:11:36.277063Z","shell.execute_reply.started":"2024-02-06T02:00:58.707142Z","shell.execute_reply":"2024-02-06T03:11:36.276032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## How to Finalize the Model and Make Predictions\n### Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.xception 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","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:12:18.703413Z","iopub.execute_input":"2024-02-06T03:12:18.703827Z","iopub.status.idle":"2024-02-06T03:12:18.710351Z","shell.execute_reply.started":"2024-02-06T03:12:18.703795Z","shell.execute_reply":"2024-02-06T03:12:18.709234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xcep_model = Xception(include_top=False, input_shape=(299, 299, 3))\nxcep_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:12:22.895197Z","iopub.execute_input":"2024-02-06T03:12:22.895625Z","iopub.status.idle":"2024-02-06T03:12:25.767629Z","shell.execute_reply.started":"2024-02-06T03:12:22.895591Z","shell.execute_reply":"2024-02-06T03:12:25.766336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create data generator\ndatagen = 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\n# Prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(299, 299))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(299, 299))","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:12:35.576990Z","iopub.execute_input":"2024-02-06T03:12:35.577429Z","iopub.status.idle":"2024-02-06T03:12:36.865740Z","shell.execute_reply.started":"2024-02-06T03:12:35.577395Z","shell.execute_reply":"2024-02-06T03:12:36.864537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load model\nmodel = Xception(include_top=False, input_shape=(299, 299, 3))\n# mark loaded layers as not trainable\nfor layer in model.layers[:15]:\n    layer.trainable = False\n# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmodel = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:12:49.615664Z","iopub.execute_input":"2024-02-06T03:12:49.616505Z","iopub.status.idle":"2024-02-06T03:12:51.481441Z","shell.execute_reply.started":"2024-02-06T03:12:49.616468Z","shell.execute_reply":"2024-02-06T03:12:51.480246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nhistory = 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# evaluate model\n_, acc = model.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\nsummarize_diagnostics(history)\n\nmodel.save('xception_model.keras')","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:12:56.917028Z","iopub.execute_input":"2024-02-06T03:12:56.917465Z","iopub.status.idle":"2024-02-06T03:37:29.744129Z","shell.execute_reply.started":"2024-02-06T03:12:56.917432Z","shell.execute_reply":"2024-02-06T03:37:29.742863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import load_model\nfrom tensorflow.keras.models import load_model","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:37:37.721990Z","iopub.execute_input":"2024-02-06T03:37:37.723057Z","iopub.status.idle":"2024-02-06T03:37:37.974406Z","shell.execute_reply.started":"2024-02-06T03:37:37.723018Z","shell.execute_reply":"2024-02-06T03:37:37.973475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = load_model('xception_model.keras')\nbest_model.evaluate(test_it, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:37:41.898235Z","iopub.execute_input":"2024-02-06T03:37:41.898734Z","iopub.status.idle":"2024-02-06T03:40:31.183535Z","shell.execute_reply.started":"2024-02-06T03:37:41.898695Z","shell.execute_reply":"2024-02-06T03:40:31.182401Z"},"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\nimport os\n\nprint(os.path.exists('/kaggle/working/xception_model.keras'))  # This should return True if the file exists","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:40:42.763435Z","iopub.execute_input":"2024-02-06T03:40:42.764429Z","iopub.status.idle":"2024-02-06T03:40:42.771101Z","shell.execute_reply.started":"2024-02-06T03:40:42.764390Z","shell.execute_reply":"2024-02-06T03:40:42.770054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load and prepare the image\ndef load_image(filename):\n    # load the image\n    img = load_img(filename, target_size=(299, 299))  # Adjusted to 299x299\n    # convert to array\n    img = img_to_array(img)\n    # reshape into a single sample with 3 channels\n    img = img.reshape(1, 299, 299, 3)  # Adjusted to 299x299\n    # center pixel data\n    img = img.astype('float32')\n    img = img - [123.68, 116.779, 103.939]\n    return img\n\n# load an image and predict the class\ndef run_example():\n    # load the image\n    img = load_image('/kaggle/working/train/cat.4644.jpg')\n    # load model\n    model = load_model('xception_model.keras')\n    # predict the class\n    result = model.predict(img)\n    print(result[0])","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:40:53.298851Z","iopub.execute_input":"2024-02-06T03:40:53.299541Z","iopub.status.idle":"2024-02-06T03:40:53.307874Z","shell.execute_reply.started":"2024-02-06T03:40:53.299504Z","shell.execute_reply":"2024-02-06T03:40:53.306664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-06T03:40:59.394687Z","iopub.execute_input":"2024-02-06T03:40:59.395774Z","iopub.status.idle":"2024-02-06T03:41:14.732624Z","shell.execute_reply.started":"2024-02-06T03:40:59.395733Z","shell.execute_reply":"2024-02-06T03:41:14.731326Z"},"trusted":true},"execution_count":null,"outputs":[]}]}