{"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-10T00:54:01.504249Z","iopub.execute_input":"2024-02-10T00:54:01.504625Z","iopub.status.idle":"2024-02-10T00:54:01.511556Z","shell.execute_reply.started":"2024-02-10T00:54:01.504594Z","shell.execute_reply":"2024-02-10T00:54:01.510583Z"},"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-10T00:54:04.771690Z","iopub.execute_input":"2024-02-10T00:54:04.772055Z","iopub.status.idle":"2024-02-10T00:54:19.042423Z","shell.execute_reply.started":"2024-02-10T00:54:04.772029Z","shell.execute_reply":"2024-02-10T00:54:19.041359Z"},"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-10T00:54:23.348142Z","iopub.execute_input":"2024-02-10T00:54:23.348755Z","iopub.status.idle":"2024-02-10T00:54:24.505699Z","shell.execute_reply.started":"2024-02-10T00:54:23.348720Z","shell.execute_reply":"2024-02-10T00:54:24.504789Z"},"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-10T00:54:28.305313Z","iopub.execute_input":"2024-02-10T00:54:28.305656Z","iopub.status.idle":"2024-02-10T00:54:29.426337Z","shell.execute_reply.started":"2024-02-10T00:54:28.305631Z","shell.execute_reply":"2024-02-10T00:54:29.425390Z"},"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-10T00:54:31.462307Z","iopub.execute_input":"2024-02-10T00:54:31.463158Z","iopub.status.idle":"2024-02-10T00:54:31.467619Z","shell.execute_reply.started":"2024-02-10T00:54:31.463121Z","shell.execute_reply":"2024-02-10T00:54:31.466741Z"},"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-10T00:54:34.525126Z","iopub.execute_input":"2024-02-10T00:54:34.525642Z","iopub.status.idle":"2024-02-10T00:54:34.530407Z","shell.execute_reply.started":"2024-02-10T00:54:34.525608Z","shell.execute_reply":"2024-02-10T00:54:34.529385Z"},"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-10T00:54:36.209872Z","iopub.execute_input":"2024-02-10T00:54:36.210255Z","iopub.status.idle":"2024-02-10T00:54:36.216403Z","shell.execute_reply.started":"2024-02-10T00:54:36.210223Z","shell.execute_reply":"2024-02-10T00:54:36.215352Z"},"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-10T00:54:40.109869Z","iopub.execute_input":"2024-02-10T00:54:40.110252Z","iopub.status.idle":"2024-02-10T00:54:42.608389Z","shell.execute_reply.started":"2024-02-10T00:54:40.110220Z","shell.execute_reply":"2024-02-10T00:54:42.607383Z"},"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-10T00:54:42.610030Z","iopub.execute_input":"2024-02-10T00:54:42.610333Z","iopub.status.idle":"2024-02-10T00:54:43.678549Z","shell.execute_reply.started":"2024-02-10T00:54:42.610307Z","shell.execute_reply":"2024-02-10T00:54:43.677347Z"},"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-10T00:54:43.680417Z","iopub.execute_input":"2024-02-10T00:54:43.681350Z","iopub.status.idle":"2024-02-10T00:54:44.736666Z","shell.execute_reply.started":"2024-02-10T00:54:43.681309Z","shell.execute_reply":"2024-02-10T00:54:44.735487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:54:44.739380Z","iopub.execute_input":"2024-02-10T00:54:44.740067Z","iopub.status.idle":"2024-02-10T00:54:58.868228Z","shell.execute_reply.started":"2024-02-10T00:54:44.740027Z","shell.execute_reply":"2024-02-10T00:54:58.866963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:54:58.869907Z","iopub.execute_input":"2024-02-10T00:54:58.870353Z","iopub.status.idle":"2024-02-10T00:54:58.886982Z","shell.execute_reply.started":"2024-02-10T00:54:58.870297Z","shell.execute_reply":"2024-02-10T00:54:58.885982Z"},"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.inception_v3 import InceptionV3\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-09T16:29:06.251580Z","iopub.execute_input":"2024-02-09T16:29:06.251901Z","iopub.status.idle":"2024-02-09T16:29:06.257407Z","shell.execute_reply.started":"2024-02-09T16:29:06.251875Z","shell.execute_reply":"2024-02-09T16:29:06.256622Z"},"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":"IncepV3_model = InceptionV3(include_top=False, \n                            input_shape=(299, 299, 3))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:29:06.258566Z","iopub.execute_input":"2024-02-09T16:29:06.258928Z","iopub.status.idle":"2024-02-09T16:29:11.221269Z","shell.execute_reply.started":"2024-02-09T16:29:06.258886Z","shell.execute_reply":"2024-02-09T16:29:11.220398Z"},"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=(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-09T16:29:11.222437Z","iopub.execute_input":"2024-02-09T16:29:11.222734Z","iopub.status.idle":"2024-02-09T16:29:12.181104Z","shell.execute_reply.started":"2024-02-09T16:29:11.222707Z","shell.execute_reply":"2024-02-09T16:29:12.180279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# model 1\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T06:30:43.72305Z","iopub.execute_input":"2024-01-30T06:30:43.723387Z","iopub.status.idle":"2024-01-30T06:30:44.095413Z","shell.execute_reply.started":"2024-01-30T06:30:43.72336Z","shell.execute_reply":"2024-01-30T06:30:44.094579Z"}}},{"cell_type":"code","source":"model = InceptionV3(include_top=False,input_shape=(299,299,3))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:29:12.182254Z","iopub.execute_input":"2024-02-09T16:29:12.182618Z","iopub.status.idle":"2024-02-09T16:29:14.593165Z","shell.execute_reply.started":"2024-02-09T16:29:12.182581Z","shell.execute_reply":"2024-02-09T16:29:14.592332Z"},"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-09T16:29:14.594322Z","iopub.execute_input":"2024-02-09T16:29:14.594652Z","iopub.status.idle":"2024-02-09T16:29:14.627372Z","shell.execute_reply.started":"2024-02-09T16:29:14.594624Z","shell.execute_reply":"2024-02-09T16:29:14.626483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:29:14.628569Z","iopub.execute_input":"2024-02-09T16:29:14.628875Z","iopub.status.idle":"2024-02-09T16:29:15.090420Z","shell.execute_reply.started":"2024-02-09T16:29:14.628844Z","shell.execute_reply":"2024-02-09T16:29:15.089418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = InceptionV3(include_top=False, input_shape=(299, 299, 3))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:30:48.976848Z","iopub.execute_input":"2024-02-09T16:30:48.977255Z","iopub.status.idle":"2024-02-09T16:30:51.432253Z","shell.execute_reply.started":"2024-02-09T16:30:48.977220Z","shell.execute_reply":"2024-02-09T16:30:51.431227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# add new classifier layers\nflat1 = Flatten()(base_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=base_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'])","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:31:25.913546Z","iopub.execute_input":"2024-02-09T16:31:25.913942Z","iopub.status.idle":"2024-02-09T16:31:25.987471Z","shell.execute_reply.started":"2024-02-09T16:31:25.913908Z","shell.execute_reply":"2024-02-09T16:31:25.986736Z"},"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# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\nbest_model = 'iceptionv3.hdf5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:31:44.733871Z","iopub.execute_input":"2024-02-09T16:31:44.734839Z","iopub.status.idle":"2024-02-09T17:25:59.375357Z","shell.execute_reply.started":"2024-02-09T16:31:44.734782Z","shell.execute_reply":"2024-02-09T17:25:59.374500Z"},"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-10T00:51:44.729571Z","iopub.execute_input":"2024-02-10T00:51:44.730737Z","iopub.status.idle":"2024-02-10T00:51:45.105255Z","shell.execute_reply.started":"2024-02-10T00:51:44.730700Z","shell.execute_reply":"2024-02-10T00:51:45.103997Z"},"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-10T00:51:48.885173Z","iopub.execute_input":"2024-02-10T00:51:48.885549Z","iopub.status.idle":"2024-02-10T00:51:48.890404Z","shell.execute_reply.started":"2024-02-10T00:51:48.885518Z","shell.execute_reply":"2024-02-10T00:51:48.889430Z"},"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-10T00:51:50.924345Z","iopub.execute_input":"2024-02-10T00:51:50.925238Z","iopub.status.idle":"2024-02-10T00:51:51.064267Z","shell.execute_reply.started":"2024-02-10T00:51:50.925203Z","shell.execute_reply":"2024-02-10T00:51:51.062974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# model 2","metadata":{}},{"cell_type":"code","source":"from keras.applications.densenet import DenseNet121\nfrom keras.models import Model\nfrom keras.layers import Flatten, Dense\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:25:59.377740Z","iopub.execute_input":"2024-02-09T17:25:59.378433Z","iopub.status.idle":"2024-02-09T17:25:59.383359Z","shell.execute_reply.started":"2024-02-09T17:25:59.378394Z","shell.execute_reply":"2024-02-09T17:25:59.382470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dense_model = DenseNet121(include_top=False, input_shape=(224, 224, 3))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:25:59.384520Z","iopub.execute_input":"2024-02-09T17:25:59.384762Z","iopub.status.idle":"2024-02-09T17:26:02.838234Z","shell.execute_reply.started":"2024-02-09T17:25:59.384739Z","shell.execute_reply":"2024-02-09T17:26:02.837140Z"},"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))\n\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-09T17:26:02.841142Z","iopub.execute_input":"2024-02-09T17:26:02.841877Z","iopub.status.idle":"2024-02-09T17:26:03.830345Z","shell.execute_reply.started":"2024-02-09T17:26:02.841834Z","shell.execute_reply":"2024-02-09T17:26:03.829563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# mark loaded layers as not trainable\nfor index, layer in enumerate(dense_model.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(dense_model.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:26:03.831497Z","iopub.execute_input":"2024-02-09T17:26:03.831786Z","iopub.status.idle":"2024-02-09T17:26:03.874475Z","shell.execute_reply.started":"2024-02-09T17:26:03.831760Z","shell.execute_reply":"2024-02-09T17:26:03.873577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dense_model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:26:03.875452Z","iopub.execute_input":"2024-02-09T17:26:03.875717Z","iopub.status.idle":"2024-02-09T17:26:03.882253Z","shell.execute_reply.started":"2024-02-09T17:26:03.875693Z","shell.execute_reply":"2024-02-09T17:26:03.881278Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# add new classifier layers\nflat1 = Flatten()(dense_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=dense_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'])","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:26:03.883310Z","iopub.execute_input":"2024-02-09T17:26:03.883579Z","iopub.status.idle":"2024-02-09T17:26:03.971855Z","shell.execute_reply.started":"2024-02-09T17:26:03.883555Z","shell.execute_reply":"2024-02-09T17:26:03.971216Z"},"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# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\nbest_model = 'densenet121_cats_vs_dogs.h5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:26:03.972929Z","iopub.execute_input":"2024-02-09T17:26:03.973246Z","iopub.status.idle":"2024-02-09T17:58:33.015126Z","shell.execute_reply.started":"2024-02-09T17:26:03.973214Z","shell.execute_reply":"2024-02-09T17:58:33.014237Z"},"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-10T00:52:52.741214Z","iopub.execute_input":"2024-02-10T00:52:52.741667Z","iopub.status.idle":"2024-02-10T00:52:52.788807Z","shell.execute_reply.started":"2024-02-10T00:52:52.741631Z","shell.execute_reply":"2024-02-10T00:52:52.787463Z"},"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\n","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:52:49.625203Z","iopub.execute_input":"2024-02-10T00:52:49.626190Z","iopub.status.idle":"2024-02-10T00:52:49.630539Z","shell.execute_reply.started":"2024-02-10T00:52:49.626153Z","shell.execute_reply":"2024-02-10T00:52:49.629674Z"},"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-10T00:52:56.316190Z","iopub.execute_input":"2024-02-10T00:52:56.317027Z","iopub.status.idle":"2024-02-10T00:52:56.424186Z","shell.execute_reply.started":"2024-02-10T00:52:56.316986Z","shell.execute_reply":"2024-02-10T00:52:56.422809Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# model 3","metadata":{}},{"cell_type":"code","source":"from keras.applications import EfficientNetB2\nfrom keras.models import Model\nfrom keras.layers import Flatten, Dense\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:51:20.772148Z","iopub.execute_input":"2024-02-10T00:51:20.772527Z","iopub.status.idle":"2024-02-10T00:51:33.654864Z","shell.execute_reply.started":"2024-02-10T00:51:20.772496Z","shell.execute_reply":"2024-02-10T00:51:33.653828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"efficientnet_model = EfficientNetB2(include_top=False, input_shape=(224, 224, 3))","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:53:47.895951Z","iopub.execute_input":"2024-02-10T00:53:47.896664Z","iopub.status.idle":"2024-02-10T00:53:52.564271Z","shell.execute_reply.started":"2024-02-10T00:53:47.896630Z","shell.execute_reply":"2024-02-10T00:53:52.563482Z"},"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))\n\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-10T00:55:00.948050Z","iopub.execute_input":"2024-02-10T00:55:00.949075Z","iopub.status.idle":"2024-02-10T00:55:01.948397Z","shell.execute_reply.started":"2024-02-10T00:55:00.949038Z","shell.execute_reply":"2024-02-10T00:55:01.947614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# mark loaded layers as not trainable\nfor index, layer in enumerate(efficientnet_model.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(efficientnet_model.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:55:06.143760Z","iopub.execute_input":"2024-02-10T00:55:06.144796Z","iopub.status.idle":"2024-02-10T00:55:06.185453Z","shell.execute_reply.started":"2024-02-10T00:55:06.144758Z","shell.execute_reply":"2024-02-10T00:55:06.184454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"efficientnet_model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:55:11.491301Z","iopub.execute_input":"2024-02-10T00:55:11.492174Z","iopub.status.idle":"2024-02-10T00:55:11.499053Z","shell.execute_reply.started":"2024-02-10T00:55:11.492138Z","shell.execute_reply":"2024-02-10T00:55:11.498049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# add new classifier layers\nx = Flatten()(efficientnet_model.output)\nx = Dense(128, activation='relu', kernel_initializer='he_uniform')(x)\noutput = Dense(1, activation='sigmoid')(x)\n# define new model\nmy_model = Model(inputs=efficientnet_model.input, outputs=output)\n# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:55:13.746316Z","iopub.execute_input":"2024-02-10T00:55:13.746683Z","iopub.status.idle":"2024-02-10T00:55:13.843500Z","shell.execute_reply.started":"2024-02-10T00:55:13.746654Z","shell.execute_reply":"2024-02-10T00:55:13.842740Z"},"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# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\nbest_model = 'efficientnetb2_cats_vs_dogs.h5'\nmy_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2024-02-10T00:55:24.803964Z","iopub.execute_input":"2024-02-10T00:55:24.804336Z","iopub.status.idle":"2024-02-10T01:23:15.646937Z","shell.execute_reply.started":"2024-02-10T00:55:24.804305Z","shell.execute_reply":"2024-02-10T01:23:15.646075Z"},"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-10T01:23:37.130027Z","iopub.execute_input":"2024-02-10T01:23:37.130906Z","iopub.status.idle":"2024-02-10T01:25:00.983381Z","shell.execute_reply.started":"2024-02-10T01:23:37.130870Z","shell.execute_reply":"2024-02-10T01:25:00.982489Z"},"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\n","metadata":{"execution":{"iopub.status.busy":"2024-02-10T01:25:16.525215Z","iopub.execute_input":"2024-02-10T01:25:16.526034Z","iopub.status.idle":"2024-02-10T01:25:16.530262Z","shell.execute_reply.started":"2024-02-10T01:25:16.526000Z","shell.execute_reply":"2024-02-10T01:25:16.529344Z"},"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-10T01:25:33.269120Z","iopub.execute_input":"2024-02-10T01:25:33.269832Z","iopub.status.idle":"2024-02-10T01:25:33.366573Z","shell.execute_reply.started":"2024-02-10T01:25:33.269796Z","shell.execute_reply":"2024-02-10T01:25:33.365468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}