{"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-05T12:54:40.877216Z","iopub.execute_input":"2024-02-05T12:54:40.877923Z","iopub.status.idle":"2024-02-05T12:54:41.226147Z","shell.execute_reply.started":"2024-02-05T12:54:40.877893Z","shell.execute_reply":"2024-02-05T12:54:41.225266Z"},"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-05T12:54:41.227751Z","iopub.execute_input":"2024-02-05T12:54:41.228118Z","iopub.status.idle":"2024-02-05T12:54:55.730003Z","shell.execute_reply.started":"2024-02-05T12:54:41.228093Z","shell.execute_reply":"2024-02-05T12:54:55.729220Z"},"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-05T12:54:55.731324Z","iopub.execute_input":"2024-02-05T12:54:55.731619Z","iopub.status.idle":"2024-02-05T12:54:57.009676Z","shell.execute_reply.started":"2024-02-05T12:54:55.731593Z","shell.execute_reply":"2024-02-05T12:54:57.008778Z"},"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-05T12:54:57.010816Z","iopub.execute_input":"2024-02-05T12:54:57.011099Z","iopub.status.idle":"2024-02-05T12:54:58.193068Z","shell.execute_reply.started":"2024-02-05T12:54:57.011074Z","shell.execute_reply":"2024-02-05T12:54:58.191732Z"},"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-05T12:54:58.196500Z","iopub.execute_input":"2024-02-05T12:54:58.196855Z","iopub.status.idle":"2024-02-05T12:55:11.139685Z","shell.execute_reply.started":"2024-02-05T12:54:58.196802Z","shell.execute_reply":"2024-02-05T12:55:11.138672Z"},"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-05T12:55:11.140882Z","iopub.execute_input":"2024-02-05T12:55:11.141427Z","iopub.status.idle":"2024-02-05T12:55:11.145931Z","shell.execute_reply.started":"2024-02-05T12:55:11.141400Z","shell.execute_reply":"2024-02-05T12:55:11.144869Z"},"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-05T12:55:11.147433Z","iopub.execute_input":"2024-02-05T12:55:11.147796Z","iopub.status.idle":"2024-02-05T12:55:11.180456Z","shell.execute_reply.started":"2024-02-05T12:55:11.147762Z","shell.execute_reply":"2024-02-05T12:55:11.179618Z"},"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-05T12:55:11.181567Z","iopub.execute_input":"2024-02-05T12:55:11.181829Z","iopub.status.idle":"2024-02-05T12:55:13.693659Z","shell.execute_reply.started":"2024-02-05T12:55:11.181806Z","shell.execute_reply":"2024-02-05T12:55:13.692679Z"},"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-05T12:55:13.694744Z","iopub.execute_input":"2024-02-05T12:55:13.695028Z","iopub.status.idle":"2024-02-05T12:55:14.742871Z","shell.execute_reply.started":"2024-02-05T12:55:13.695003Z","shell.execute_reply":"2024-02-05T12:55:14.741493Z"},"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-05T12:55:14.745420Z","iopub.execute_input":"2024-02-05T12:55:14.745818Z","iopub.status.idle":"2024-02-05T12:55:15.775617Z","shell.execute_reply.started":"2024-02-05T12:55:14.745777Z","shell.execute_reply":"2024-02-05T12:55:15.774570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2024-02-05T12:55:15.777091Z","iopub.execute_input":"2024-02-05T12:55:15.777403Z","iopub.status.idle":"2024-02-05T12:55:30.116177Z","shell.execute_reply.started":"2024-02-05T12:55:15.777375Z","shell.execute_reply":"2024-02-05T12:55:30.115072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-05T12:55:30.117863Z","iopub.execute_input":"2024-02-05T12:55:30.118225Z","iopub.status.idle":"2024-02-05T12:55:30.133181Z","shell.execute_reply.started":"2024-02-05T12:55:30.118188Z","shell.execute_reply":"2024-02-05T12:55:30.132342Z"},"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-05T12:55:30.134383Z","iopub.execute_input":"2024-02-05T12:55:30.134721Z","iopub.status.idle":"2024-02-05T12:55:30.140608Z","shell.execute_reply.started":"2024-02-05T12:55:30.134689Z","shell.execute_reply":"2024-02-05T12:55:30.139604Z"},"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-05T12:55:30.144007Z","iopub.execute_input":"2024-02-05T12:55:30.144288Z","iopub.status.idle":"2024-02-05T12:55:31.148414Z","shell.execute_reply.started":"2024-02-05T12:55:30.144256Z","shell.execute_reply":"2024-02-05T12:55:31.147624Z"},"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# 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\n\nmodel.layers[-1].output\n\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\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-05T12:55:34.012208Z","iopub.execute_input":"2024-02-05T12:55:34.012624Z","iopub.status.idle":"2024-02-05T12:55:36.032092Z","shell.execute_reply.started":"2024-02-05T12:55:34.012581Z","shell.execute_reply":"2024-02-05T12:55:36.031217Z"},"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=5, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\n# evaluate model\n_, acc = my_model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))\n\nimport matplotlib.pyplot as plt\n\ndef summarize_diagnostics(history):\n    # Plot loss\n    plt.subplot(211)\n    plt.title('Cross Entropy Loss')\n    plt.plot(history.history['loss'], color='blue', label='train')\n    plt.plot(history.history['val_loss'], color='orange', label='test')\n    \n    # Plot accuracy\n    plt.subplot(212)\n    plt.title('Classification Accuracy')\n    plt.plot(history.history['accuracy'], color='blue', label='train')\n    plt.plot(history.history['val_accuracy'], color='orange', label='test')\n    \n    # Show the plot\n    plt.show()\n# learning curves\nsummarize_diagnostics(history)\n\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)\n\nfrom keras.models import load_model\n\nbest_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-05T12:55:49.178342Z","iopub.execute_input":"2024-02-05T12:55:49.179299Z","iopub.status.idle":"2024-02-05T13:29:52.964990Z","shell.execute_reply.started":"2024-02-05T12:55:49.179253Z","shell.execute_reply":"2024-02-05T13:29:52.964062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications import VGG19\n\n# load model\nmodel2 = VGG19(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model2.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n\n# mark loaded layers as not trainable\nfor index, layer in enumerate(model2.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model2.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True\n\nmodel2.layers[-1].output\n\n# add new classifier layers\nflat1 = Flatten()(model2.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model2 = Model(inputs=model2.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model2.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model2.summary()\n\n# evaluate model\n_, acc = my_model2.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))","metadata":{"execution":{"iopub.status.busy":"2024-02-05T13:29:52.966790Z","iopub.execute_input":"2024-02-05T13:29:52.967080Z","iopub.status.idle":"2024-02-05T13:31:27.679263Z","shell.execute_reply.started":"2024-02-05T13:29:52.967056Z","shell.execute_reply":"2024-02-05T13:31:27.678361Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model2.reset_states()\nhistory2 = my_model2.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=5, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\n# evaluate model\n_, acc = my_model2.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))\n\nimport matplotlib.pyplot as plt\n\ndef summarize_diagnostics(history2):\n    # Plot loss\n    plt.subplot(211)\n    plt.title('Cross Entropy Loss')\n    plt.plot(history2.history['loss'], color='blue', label='train')\n    plt.plot(history2.history['val_loss'], color='orange', label='test')\n    \n    # Plot accuracy\n    plt.subplot(212)\n    plt.title('Classification Accuracy')\n    plt.plot(history2.history['accuracy'], color='blue', label='train')\n    plt.plot(history2.history['val_accuracy'], color='orange', label='test')\n    \n    # Show the plot\n    plt.show()\n# learning curves\nsummarize_diagnostics(history2)\n\nbest_model2 = 'vgg19_model.hdf5'\nmy_model2.save(best_model2)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-05T13:31:27.680452Z","iopub.execute_input":"2024-02-05T13:31:27.680747Z","iopub.status.idle":"2024-02-05T14:03:57.949625Z","shell.execute_reply.started":"2024-02-05T13:31:27.680721Z","shell.execute_reply":"2024-02-05T14:03:57.948552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras\nkeras.applications.MobileNet(\n    input_shape=(224, 224, 3),\n    alpha=1.0,\n    depth_multiplier=1,\n    dropout=0.001,\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    pooling=None,\n    classes=2,\n    classifier_activation=\"softmax\",\n)\n\nfrom keras.applications import MobileNet\n\n# load model\nmodel3 = MobileNet(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model3.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n# mark loaded layers as not trainable\nfor index, layer in enumerate(model3.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model3.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True\n\nmodel3.layers[-1].output\n\n# add new classifier layers\nflat1 = Flatten()(model3.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model3 = Model(inputs=model3.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model3.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model3.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-05T14:03:57.952365Z","iopub.execute_input":"2024-02-05T14:03:57.952763Z","iopub.status.idle":"2024-02-05T14:04:00.062045Z","shell.execute_reply.started":"2024-02-05T14:03:57.952729Z","shell.execute_reply":"2024-02-05T14:04:00.061322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model3.reset_states()\nhistory3 = my_model3.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=5, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\n          # evaluate model\n_, acc = my_model3.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))\n\nimport matplotlib.pyplot as plt\n\ndef summarize_diagnostics(history3):\n    # Plot loss\n    plt.subplot(211)\n    plt.title('Cross Entropy Loss')\n    plt.plot(history3.history['loss'], color='blue', label='train')\n    plt.plot(history3.history['val_loss'], color='orange', label='test')\n    \n    # Plot accuracy\n    plt.subplot(212)\n    plt.title('Classification Accuracy')\n    plt.plot(history3.history['accuracy'], color='blue', label='train')\n    plt.plot(history3.history['val_accuracy'], color='orange', label='test')\n    \n    # Show the plot\n    plt.show()\n# learning curves\nsummarize_diagnostics(history3)\n\nbest_model3 = 'mobilenet_model.hdf5'\nmy_model3.save(best_model3)","metadata":{"execution":{"iopub.status.busy":"2024-02-05T14:04:00.063130Z","iopub.execute_input":"2024-02-05T14:04:00.063424Z","iopub.status.idle":"2024-02-05T14:35:37.240554Z","shell.execute_reply.started":"2024-02-05T14:04:00.063399Z","shell.execute_reply":"2024-02-05T14:35:37.239710Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\nfrom keras.applications.mobilenet_v2 import preprocess_input, decode_predictions\n\nkeras.applications.MobileNetV2(\n    input_shape=(224, 224, 3),\n    alpha=1.0,\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    pooling=None,\n    classes=2,\n    classifier_activation=\"softmax\",\n)\n\nfrom keras.applications import MobileNetV2\n# load model\nmodel4 = MobileNetV2(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model4.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n\n# mark loaded layers as not trainable\nfor index, layer in enumerate(model4.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model4.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True\n\nmodel4.layers[-1].output\n\n# add new classifier layers\nflat1 = Flatten()(model4.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model4 = Model(inputs=model4.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model4.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model4.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-05T14:35:37.241971Z","iopub.execute_input":"2024-02-05T14:35:37.242358Z","iopub.status.idle":"2024-02-05T14:35:41.152717Z","shell.execute_reply.started":"2024-02-05T14:35:37.242323Z","shell.execute_reply":"2024-02-05T14:35:41.151960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model4.reset_states()\nhistory4 = my_model4.fit(train_it, \n                    #steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    #validation_steps=len(test_it), \n                    epochs=5, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n\n      # evaluate model\n_, acc = my_model4.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))\n\nimport matplotlib.pyplot as plt\n\ndef summarize_diagnostics(history4):\n    # Plot loss\n    plt.subplot(211)\n    plt.title('Cross Entropy Loss')\n    plt.plot(history4.history['loss'], color='blue', label='train')\n    plt.plot(history4.history['val_loss'], color='orange', label='test')\n    \n    # Plot accuracy\n    plt.subplot(212)\n    plt.title('Classification Accuracy')\n    plt.plot(history4.history['accuracy'], color='blue', label='train')\n    plt.plot(history4.history['val_accuracy'], color='orange', label='test')\n    \n    # Show the plot\n    plt.show()\n# learning curves\nsummarize_diagnostics(history4)\n\nbest_model4 = 'mobilenetv2_model.hdf5'\nmy_model4.save(best_model4)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-02-05T14:35:41.153800Z","iopub.execute_input":"2024-02-05T14:35:41.154056Z","iopub.status.idle":"2024-02-05T15:07:18.477597Z","shell.execute_reply.started":"2024-02-05T14:35:41.154033Z","shell.execute_reply":"2024-02-05T15:07:18.476255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.applications import MobileNetV3Small\nfrom keras.preprocessing import image\nfrom keras.applications.mobilenet_v3 import preprocess_input, decode_predictions\nkeras.applications.MobileNetV3Small(\n    input_shape=(224, 224, 3),\n    alpha=1.0,\n    minimalistic=False,\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=None,\n    pooling=None,\n    dropout_rate=0.2,\n    classes=2,\n    classifier_activation=\"softmax\",\n    include_preprocessing=True,\n)\n\n\n# load model\nmodel5 = MobileNetV3Small(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model5.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n# mark loaded layers as not trainable\nfor index, layer in enumerate(model5.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model5.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True\n\nmodel5.layers[-1].output\n# add new classifier layers\nflat1 = Flatten()(model5.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model5 = Model(inputs=model5.inputs, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model5.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model5.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-05T15:15:49.396445Z","iopub.execute_input":"2024-02-05T15:15:49.397180Z","iopub.status.idle":"2024-02-05T15:15:53.748401Z","shell.execute_reply.started":"2024-02-05T15:15:49.397149Z","shell.execute_reply":"2024-02-05T15:15:53.744282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit model\nmy_model5.reset_states()\nhistory5 = my_model5.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\n      # evaluate model\n_, acc = my_model5.evaluate_generator(test_it, steps=len(test_it), verbose=1)\n\nprint('> %.3f' % (acc * 100.0))\n\nimport matplotlib.pyplot as plt\n\ndef summarize_diagnostics(history5):\n    # Plot loss\n    plt.subplot(211)\n    plt.title('Cross Entropy Loss')\n    plt.plot(history5.history['loss'], color='blue', label='train')\n    plt.plot(history5.history['val_loss'], color='orange', label='test')\n    \n    # Plot accuracy\n    plt.subplot(212)\n    plt.title('Classification Accuracy')\n    plt.plot(history5.history['accuracy'], color='blue', label='train')\n    plt.plot(history5.history['val_accuracy'], color='orange', label='test')\n    \n    # Show the plot\n    plt.show()\n# learning curves\nsummarize_diagnostics(history5)\n\nbest_model5 = 'mobilenetv3small_model.hdf5'\nmy_model5.save(best_model5)","metadata":{"execution":{"iopub.status.busy":"2024-02-05T15:15:53.749884Z","iopub.execute_input":"2024-02-05T15:15:53.750175Z","iopub.status.idle":"2024-02-05T16:17:19.573892Z","shell.execute_reply.started":"2024-02-05T15:15:53.750150Z","shell.execute_reply":"2024-02-05T16:17:19.572830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}