{"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-02-10T14:39:04.013105Z","iopub.execute_input":"2024-02-10T14:39:04.013997Z","iopub.status.idle":"2024-02-10T14:39:04.022689Z","shell.execute_reply.started":"2024-02-10T14:39:04.013953Z","shell.execute_reply":"2024-02-10T14:39:04.021631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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-10T14:39:04.057467Z","iopub.execute_input":"2024-02-10T14:39:04.057721Z","iopub.status.idle":"2024-02-10T14:39:15.171085Z","shell.execute_reply.started":"2024-02-10T14:39:04.057699Z","shell.execute_reply":"2024-02-10T14:39:15.170198Z"},"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\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 + '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-10T14:39:15.173098Z","iopub.execute_input":"2024-02-10T14:39:15.173801Z","iopub.status.idle":"2024-02-10T14:39:16.614445Z","shell.execute_reply.started":"2024-02-10T14:39:15.173752Z","shell.execute_reply":"2024-02-10T14:39:16.613443Z"},"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-02-10T14:39:16.61571Z","iopub.execute_input":"2024-02-10T14:39:16.616099Z","iopub.status.idle":"2024-02-10T14:39:17.77073Z","shell.execute_reply.started":"2024-02-10T14:39:16.616063Z","shell.execute_reply":"2024-02-10T14:39:17.769791Z"},"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-10T14:39:17.772888Z","iopub.execute_input":"2024-02-10T14:39:17.773199Z","iopub.status.idle":"2024-02-10T14:39:17.778301Z","shell.execute_reply.started":"2024-02-10T14:39:17.773172Z","shell.execute_reply":"2024-02-10T14:39:17.777226Z"},"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\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-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"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-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"code","source":"\n# 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","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:17.779579Z","iopub.execute_input":"2024-02-10T14:39:17.779905Z","iopub.status.idle":"2024-02-10T14:39:17.791073Z","shell.execute_reply.started":"2024-02-10T14:39:17.779873Z","shell.execute_reply":"2024-02-10T14:39:17.790153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:17.79246Z","iopub.execute_input":"2024-02-10T14:39:17.792767Z","iopub.status.idle":"2024-02-10T14:39:17.803343Z","shell.execute_reply.started":"2024-02-10T14:39:17.792734Z","shell.execute_reply":"2024-02-10T14:39:17.802489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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-10T14:39:17.804641Z","iopub.execute_input":"2024-02-10T14:39:17.804925Z","iopub.status.idle":"2024-02-10T14:39:21.362013Z","shell.execute_reply.started":"2024-02-10T14:39:17.804902Z","shell.execute_reply":"2024-02-10T14:39:21.360983Z"},"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-10T14:39:21.363271Z","iopub.execute_input":"2024-02-10T14:39:21.363643Z","iopub.status.idle":"2024-02-10T14:39:22.436264Z","shell.execute_reply.started":"2024-02-10T14:39:21.363602Z","shell.execute_reply":"2024-02-10T14:39:22.4353Z"},"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-10T14:39:22.438031Z","iopub.execute_input":"2024-02-10T14:39:22.438432Z","iopub.status.idle":"2024-02-10T14:39:23.506048Z","shell.execute_reply.started":"2024-02-10T14:39:22.438394Z","shell.execute_reply":"2024-02-10T14:39:23.504955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:23.510816Z","iopub.execute_input":"2024-02-10T14:39:23.511447Z","iopub.status.idle":"2024-02-10T14:39:35.2761Z","shell.execute_reply.started":"2024-02-10T14:39:23.511415Z","shell.execute_reply":"2024-02-10T14:39:35.274887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:35.277775Z","iopub.execute_input":"2024-02-10T14:39:35.278189Z","iopub.status.idle":"2024-02-10T14:39:35.283026Z","shell.execute_reply.started":"2024-02-10T14:39:35.27815Z","shell.execute_reply":"2024-02-10T14:39:35.282264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"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-10T14:39:35.284272Z","iopub.execute_input":"2024-02-10T14:39:35.284536Z","iopub.status.idle":"2024-02-10T14:39:35.295955Z","shell.execute_reply.started":"2024-02-10T14:39:35.284513Z","shell.execute_reply":"2024-02-10T14:39:35.294972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"xcep_model = Xception(include_top=False, input_shape=(299, 299, 3))\nxcep_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-27T04:11:23.494572Z","iopub.execute_input":"2024-01-27T04:11:23.495217Z","iopub.status.idle":"2024-01-27T04:11:26.579883Z","shell.execute_reply.started":"2024-01-27T04:11:23.495182Z","shell.execute_reply":"2024-01-27T04:11:26.578335Z"}}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n# 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# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:35.29728Z","iopub.execute_input":"2024-02-10T14:39:35.297831Z","iopub.status.idle":"2024-02-10T14:39:36.377057Z","shell.execute_reply.started":"2024-02-10T14:39:35.297798Z","shell.execute_reply":"2024-02-10T14:39:36.376285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load model\nmodel = VGG16(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:36.378337Z","iopub.execute_input":"2024-02-10T14:39:36.378635Z","iopub.status.idle":"2024-02-10T14:39:36.774064Z","shell.execute_reply.started":"2024-02-10T14:39:36.378609Z","shell.execute_reply":"2024-02-10T14:39:36.773149Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# mark loaded layers as not trainable\nfor index, layer in enumerate(model.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:36.775402Z","iopub.execute_input":"2024-02-10T14:39:36.775734Z","iopub.status.idle":"2024-02-10T14:39:36.784038Z","shell.execute_reply.started":"2024-02-10T14:39:36.775705Z","shell.execute_reply":"2024-02-10T14:39:36.783012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:36.785665Z","iopub.execute_input":"2024-02-10T14:39:36.786071Z","iopub.status.idle":"2024-02-10T14:39:36.803112Z","shell.execute_reply.started":"2024-02-10T14:39:36.786027Z","shell.execute_reply":"2024-02-10T14:39:36.802282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\nmy_model = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:36.804196Z","iopub.execute_input":"2024-02-10T14:39:36.804472Z","iopub.status.idle":"2024-02-10T14:39:36.898381Z","shell.execute_reply.started":"2024-02-10T14:39:36.804447Z","shell.execute_reply":"2024-02-10T14:39:36.897445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" # fit model\nmy_model.reset_states()\nhistory = my_model.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=15, 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\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:39:36.899516Z","iopub.execute_input":"2024-02-10T14:39:36.89978Z","iopub.status.idle":"2024-02-10T16:12:07.719813Z","shell.execute_reply.started":"2024-02-10T14:39:36.899756Z","shell.execute_reply":"2024-02-10T16:12:07.717961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.720798Z","iopub.status.idle":"2024-02-10T16:12:07.721183Z","shell.execute_reply.started":"2024-02-10T16:12:07.720997Z","shell.execute_reply":"2024-02-10T16:12:07.721022Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.722622Z","iopub.status.idle":"2024-02-10T16:12:07.722948Z","shell.execute_reply.started":"2024-02-10T16:12:07.72279Z","shell.execute_reply":"2024-02-10T16:12:07.722805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img\n\n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.724677Z","iopub.status.idle":"2024-02-10T16:12:07.72502Z","shell.execute_reply.started":"2024-02-10T16:12:07.724838Z","shell.execute_reply":"2024-02-10T16:12:07.724853Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications.mobilenet import MobileNet","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.726397Z","iopub.status.idle":"2024-02-10T16:12:07.726774Z","shell.execute_reply.started":"2024-02-10T16:12:07.72659Z","shell.execute_reply":"2024-02-10T16:12:07.726606Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = MobileNet(\n    input_shape=None,\n    alpha=1.0,\n    depth_multiplier=1,\n    dropout=0.001,\n    include_top=True,\n    weights=\"imagenet\",\n    input_tensor=None,\n    pooling=None,\n    classes=1000,\n    classifier_activation=\"softmax\",\n)\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.727899Z","iopub.status.idle":"2024-02-10T16:12:07.728256Z","shell.execute_reply.started":"2024-02-10T16:12:07.728091Z","shell.execute_reply":"2024-02-10T16:12:07.728107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\nmy_model = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.729296Z","iopub.status.idle":"2024-02-10T16:12:07.729629Z","shell.execute_reply.started":"2024-02-10T16:12:07.729465Z","shell.execute_reply":"2024-02-10T16:12:07.729481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model.reset_states()\nhistory = my_model.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=15, 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\nbest_model = 'mobilenet_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.731151Z","iopub.status.idle":"2024-02-10T16:12:07.731491Z","shell.execute_reply.started":"2024-02-10T16:12:07.731325Z","shell.execute_reply":"2024-02-10T16:12:07.731342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.733246Z","iopub.status.idle":"2024-02-10T16:12:07.733584Z","shell.execute_reply.started":"2024-02-10T16:12:07.73342Z","shell.execute_reply":"2024-02-10T16:12:07.733436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img\n\n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.734687Z","iopub.status.idle":"2024-02-10T16:12:07.735037Z","shell.execute_reply.started":"2024-02-10T16:12:07.734853Z","shell.execute_reply":"2024-02-10T16:12:07.734867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications.xception import Xception","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.736911Z","iopub.status.idle":"2024-02-10T16:12:07.737429Z","shell.execute_reply.started":"2024-02-10T16:12:07.73717Z","shell.execute_reply":"2024-02-10T16:12:07.737194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Xception(\n    include_top=True,\n    weights=\"imagenet\",\n    input_tensor=None,\n    input_shape=None,\n    pooling=None,\n    classes=1000,\n    classifier_activation=\"softmax\",\n)\nprint(model.summary())","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.73861Z","iopub.status.idle":"2024-02-10T16:12:07.739078Z","shell.execute_reply.started":"2024-02-10T16:12:07.73883Z","shell.execute_reply":"2024-02-10T16:12:07.738852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\nmy_model = Model(inputs=model.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.740498Z","iopub.status.idle":"2024-02-10T16:12:07.740951Z","shell.execute_reply.started":"2024-02-10T16:12:07.740713Z","shell.execute_reply":"2024-02-10T16:12:07.740734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model.reset_states()\nhistory = my_model.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=15, 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\nbest_model = 'x_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.742483Z","iopub.status.idle":"2024-02-10T16:12:07.742942Z","shell.execute_reply.started":"2024-02-10T16:12:07.742701Z","shell.execute_reply":"2024-02-10T16:12:07.742722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.746226Z","iopub.status.idle":"2024-02-10T16:12:07.74706Z","shell.execute_reply.started":"2024-02-10T16:12:07.746745Z","shell.execute_reply":"2024-02-10T16:12:07.74677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img\n\n# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])\n\n# entry point, run the example\nrun_example()","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:12:07.74841Z","iopub.status.idle":"2024-02-10T16:12:07.74887Z","shell.execute_reply.started":"2024-02-10T16:12:07.748623Z","shell.execute_reply":"2024-02-10T16:12:07.748645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}