{"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"},{"sourceId":7601396,"sourceType":"datasetVersion","datasetId":4425140}],"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:31:31.968606Z","iopub.execute_input":"2024-02-10T14:31:31.968986Z","iopub.status.idle":"2024-02-10T14:31:32.312167Z","shell.execute_reply.started":"2024-02-10T14:31:31.968952Z","shell.execute_reply":"2024-02-10T14:31:32.311214Z"},"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-10T14:31:34.356874Z","iopub.execute_input":"2024-02-10T14:31:34.357797Z","iopub.status.idle":"2024-02-10T14:31:50.817029Z","shell.execute_reply.started":"2024-02-10T14:31:34.357762Z","shell.execute_reply":"2024-02-10T14:31:50.816051Z"},"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:31:50.818956Z","iopub.execute_input":"2024-02-10T14:31:50.819328Z","iopub.status.idle":"2024-02-10T14:31:52.129272Z","shell.execute_reply.started":"2024-02-10T14:31:50.819297Z","shell.execute_reply":"2024-02-10T14:31:52.128322Z"},"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:31:52.130406Z","iopub.execute_input":"2024-02-10T14:31:52.130719Z","iopub.status.idle":"2024-02-10T14:31:53.307453Z","shell.execute_reply.started":"2024-02-10T14:31:52.130693Z","shell.execute_reply":"2024-02-10T14:31:53.306556Z"},"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 makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\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:33:47.138929Z","iopub.execute_input":"2024-02-10T14:33:47.13968Z","iopub.status.idle":"2024-02-10T14:34:03.924337Z","shell.execute_reply.started":"2024-02-10T14:33:47.139652Z","shell.execute_reply":"2024-02-10T14:34:03.923396Z"},"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:34:03.925824Z","iopub.execute_input":"2024-02-10T14:34:03.926361Z","iopub.status.idle":"2024-02-10T14:34:03.931921Z","shell.execute_reply.started":"2024-02-10T14:34:03.926332Z","shell.execute_reply":"2024-02-10T14:34:03.931018Z"},"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:34:21.379088Z","iopub.execute_input":"2024-02-10T14:34:21.379758Z","iopub.status.idle":"2024-02-10T14:34:23.884504Z","shell.execute_reply.started":"2024-02-10T14:34:21.379724Z","shell.execute_reply":"2024-02-10T14:34:23.883514Z"},"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:34:25.146636Z","iopub.execute_input":"2024-02-10T14:34:25.147494Z","iopub.status.idle":"2024-02-10T14:34:26.199403Z","shell.execute_reply.started":"2024-02-10T14:34:25.147461Z","shell.execute_reply":"2024-02-10T14:34:26.198341Z"},"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:34:26.871388Z","iopub.execute_input":"2024-02-10T14:34:26.871841Z","iopub.status.idle":"2024-02-10T14:34:27.920289Z","shell.execute_reply.started":"2024-02-10T14:34:26.871802Z","shell.execute_reply":"2024-02-10T14:34:27.919197Z"},"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:34:28.608347Z","iopub.execute_input":"2024-02-10T14:34:28.608717Z","iopub.status.idle":"2024-02-10T14:34:43.823017Z","shell.execute_reply.started":"2024-02-10T14:34:28.608688Z","shell.execute_reply":"2024-02-10T14:34:43.821911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:34:43.825046Z","iopub.execute_input":"2024-02-10T14:34:43.825357Z","iopub.status.idle":"2024-02-10T14:34:43.842307Z","shell.execute_reply.started":"2024-02-10T14:34:43.82533Z","shell.execute_reply":"2024-02-10T14:34:43.841575Z"},"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.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:34:43.843713Z","iopub.execute_input":"2024-02-10T14:34:43.844061Z","iopub.status.idle":"2024-02-10T14:34:43.851185Z","shell.execute_reply.started":"2024-02-10T14:34:43.844028Z","shell.execute_reply":"2024-02-10T14:34:43.850503Z"},"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":"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:34:43.853219Z","iopub.execute_input":"2024-02-10T14:34:43.853559Z","iopub.status.idle":"2024-02-10T14:34:44.909797Z","shell.execute_reply.started":"2024-02-10T14:34:43.853528Z","shell.execute_reply":"2024-02-10T14:34:44.908875Z"},"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    )","metadata":{"execution":{"iopub.status.busy":"2024-02-10T15:59:03.857148Z","iopub.execute_input":"2024-02-10T15:59:03.85767Z","iopub.status.idle":"2024-02-10T15:59:04.180165Z","shell.execute_reply.started":"2024-02-10T15:59:03.857618Z","shell.execute_reply":"2024-02-10T15:59:04.179336Z"},"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-10T15:59:07.356217Z","iopub.execute_input":"2024-02-10T15:59:07.356551Z","iopub.status.idle":"2024-02-10T15:59:07.364454Z","shell.execute_reply.started":"2024-02-10T15:59:07.356524Z","shell.execute_reply":"2024-02-10T15:59:07.363621Z"},"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-10T15:59:09.606488Z","iopub.execute_input":"2024-02-10T15:59:09.607205Z","iopub.status.idle":"2024-02-10T15:59:09.691445Z","shell.execute_reply.started":"2024-02-10T15:59:09.607171Z","shell.execute_reply":"2024-02-10T15:59:09.69059Z"},"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=10, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:51:50.350501Z","iopub.execute_input":"2024-02-10T14:51:50.351243Z","iopub.status.idle":"2024-02-10T14:57:04.822255Z","shell.execute_reply.started":"2024-02-10T14:51:50.351205Z","shell.execute_reply":"2024-02-10T14:57:04.821201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2024-02-10T14:57:44.427921Z","iopub.execute_input":"2024-02-10T14:57:44.42831Z","iopub.status.idle":"2024-02-10T14:57:44.433248Z","shell.execute_reply.started":"2024-02-10T14:57:44.428277Z","shell.execute_reply":"2024-02-10T14:57:44.432303Z"},"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-10T14:57:46.010082Z","iopub.execute_input":"2024-02-10T14:57:46.010784Z","iopub.status.idle":"2024-02-10T14:59:05.246453Z","shell.execute_reply.started":"2024-02-10T14:57:46.01075Z","shell.execute_reply":"2024-02-10T14:59:05.245599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"# 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('/kaggle/input/simple/sample_image.jpg')\n\t# load model\n\tmodel = load_model('vgg16_model.hdf5')\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-10T15:22:22.792684Z","iopub.execute_input":"2024-02-10T15:22:22.793568Z","iopub.status.idle":"2024-02-10T15:22:23.403537Z","shell.execute_reply.started":"2024-02-10T15:22:22.793532Z","shell.execute_reply":"2024-02-10T15:22:23.402577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications.mobilenet import MobileNet","metadata":{"execution":{"iopub.status.busy":"2024-02-10T15:24:56.929841Z","iopub.execute_input":"2024-02-10T15:24:56.930227Z","iopub.status.idle":"2024-02-10T15:24:56.934604Z","shell.execute_reply.started":"2024-02-10T15:24:56.930195Z","shell.execute_reply":"2024-02-10T15:24:56.933714Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T15:24:58.830448Z","iopub.execute_input":"2024-02-10T15:24:58.831156Z","iopub.status.idle":"2024-02-10T15:24:59.987761Z","shell.execute_reply.started":"2024-02-10T15:24:58.831121Z","shell.execute_reply":"2024-02-10T15:24:59.986783Z"},"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_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-10T15:25:05.318011Z","iopub.execute_input":"2024-02-10T15:25:05.318401Z","iopub.status.idle":"2024-02-10T15:25:05.560042Z","shell.execute_reply.started":"2024-02-10T15:25:05.318366Z","shell.execute_reply":"2024-02-10T15:25:05.559176Z"},"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=10, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\nbest_model = 'mobilenet_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T15:25:22.008509Z","iopub.execute_input":"2024-02-10T15:25:22.009399Z","iopub.status.idle":"2024-02-10T15:30:34.530375Z","shell.execute_reply.started":"2024-02-10T15:25:22.009363Z","shell.execute_reply":"2024-02-10T15:30:34.529502Z"},"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-10T15:30:34.532065Z","iopub.execute_input":"2024-02-10T15:30:34.532359Z","iopub.status.idle":"2024-02-10T15:31:52.508978Z","shell.execute_reply.started":"2024-02-10T15:30:34.532334Z","shell.execute_reply":"2024-02-10T15:31:52.508086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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('/kaggle/input/simple/sample_image.jpg')\n\t# load model\n\tmodel = load_model('mobilenet_model.hdf5')\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-10T15:31:52.510019Z","iopub.execute_input":"2024-02-10T15:31:52.510279Z","iopub.status.idle":"2024-02-10T15:31:54.327076Z","shell.execute_reply.started":"2024-02-10T15:31:52.510256Z","shell.execute_reply":"2024-02-10T15:31:54.32614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications.xception import Xception","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:00:30.712599Z","iopub.execute_input":"2024-02-10T16:00:30.713554Z","iopub.status.idle":"2024-02-10T16:00:30.71767Z","shell.execute_reply.started":"2024-02-10T16:00:30.713518Z","shell.execute_reply":"2024-02-10T16:00:30.716859Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:00:32.152863Z","iopub.execute_input":"2024-02-10T16:00:32.153249Z","iopub.status.idle":"2024-02-10T16:00:33.62808Z","shell.execute_reply.started":"2024-02-10T16:00:32.153217Z","shell.execute_reply":"2024-02-10T16:00:33.627086Z"},"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-10T16:00:34.327232Z","iopub.execute_input":"2024-02-10T16:00:34.32806Z","iopub.status.idle":"2024-02-10T16:00:34.345396Z","shell.execute_reply.started":"2024-02-10T16:00:34.328023Z","shell.execute_reply":"2024-02-10T16:00:34.344459Z"},"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:00:38.72249Z","iopub.execute_input":"2024-02-10T16:00:38.723212Z","iopub.status.idle":"2024-02-10T16:00:39.126809Z","shell.execute_reply.started":"2024-02-10T16:00:38.723175Z","shell.execute_reply":"2024-02-10T16:00:39.125919Z"},"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=10, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\nbest_model = 'x_model.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T16:00:47.5634Z","iopub.execute_input":"2024-02-10T16:00:47.563884Z","iopub.status.idle":"2024-02-10T16:06:12.926683Z","shell.execute_reply.started":"2024-02-10T16:00:47.56385Z","shell.execute_reply":"2024-02-10T16:06:12.92558Z"},"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:06:12.928917Z","iopub.execute_input":"2024-02-10T16:06:12.92922Z","iopub.status.idle":"2024-02-10T16:07:32.700419Z","shell.execute_reply.started":"2024-02-10T16:06:12.929195Z","shell.execute_reply":"2024-02-10T16:07:32.699409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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('/kaggle/input/simple/sample_image.jpg')\n\t# load model\n\tmodel = load_model('x_model.hdf5')\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_count":null,"outputs":[]}]}