{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:29:57.272507Z","iopub.execute_input":"2025-02-08T04:29:57.272894Z","iopub.status.idle":"2025-02-08T04:29:57.808933Z","shell.execute_reply.started":"2025-02-08T04:29:57.272864Z","shell.execute_reply":"2025-02-08T04:29:57.807709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:02.734077Z","iopub.execute_input":"2025-02-08T04:30:02.734456Z","iopub.status.idle":"2025-02-08T04:30:03.841583Z","shell.execute_reply.started":"2025-02-08T04:30:02.73443Z","shell.execute_reply":"2025-02-08T04:30:03.839899Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:11.426094Z","iopub.execute_input":"2025-02-08T04:30:11.426541Z","iopub.status.idle":"2025-02-08T04:30:25.976257Z","shell.execute_reply.started":"2025-02-08T04:30:11.426505Z","shell.execute_reply":"2025-02-08T04:30:25.975028Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:42.229998Z","iopub.execute_input":"2025-02-08T04:30:42.230394Z","iopub.status.idle":"2025-02-08T04:30:43.316042Z","shell.execute_reply.started":"2025-02-08T04:30:42.230362Z","shell.execute_reply":"2025-02-08T04:30:43.314833Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:45.221638Z","iopub.execute_input":"2025-02-08T04:30:45.222071Z","iopub.status.idle":"2025-02-08T04:30:46.322386Z","shell.execute_reply.started":"2025-02-08T04:30:45.222035Z","shell.execute_reply":"2025-02-08T04:30:46.321224Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:48.567001Z","iopub.execute_input":"2025-02-08T04:30:48.56744Z","iopub.status.idle":"2025-02-08T04:30:49.695322Z","shell.execute_reply.started":"2025-02-08T04:30:48.567404Z","shell.execute_reply":"2025-02-08T04:30:49.694063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:51.413993Z","iopub.execute_input":"2025-02-08T04:30:51.415248Z","iopub.status.idle":"2025-02-08T04:30:52.612161Z","shell.execute_reply.started":"2025-02-08T04:30:51.415202Z","shell.execute_reply":"2025-02-08T04:30:52.610626Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:30:54.134669Z","iopub.execute_input":"2025-02-08T04:30:54.135107Z","iopub.status.idle":"2025-02-08T04:30:55.408624Z","shell.execute_reply.started":"2025-02-08T04:30:54.135068Z","shell.execute_reply":"2025-02-08T04:30:55.407204Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:12.350827Z","iopub.execute_input":"2025-02-08T04:31:12.35127Z","iopub.status.idle":"2025-02-08T04:31:13.605461Z","shell.execute_reply.started":"2025-02-08T04:31:12.351232Z","shell.execute_reply":"2025-02-08T04:31:13.604254Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:17.622786Z","iopub.execute_input":"2025-02-08T04:31:17.623187Z","iopub.status.idle":"2025-02-08T04:31:18.706856Z","shell.execute_reply.started":"2025-02-08T04:31:17.623132Z","shell.execute_reply":"2025-02-08T04:31:18.705589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow\nprint(tensorflow.__version__)\n\nimport keras\nprint(keras.__version__)\n\nimport tensorflow.keras\nprint(tensorflow.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:21.957912Z","iopub.execute_input":"2025-02-08T04:31:21.958334Z","iopub.status.idle":"2025-02-08T04:31:35.943551Z","shell.execute_reply.started":"2025-02-08T04:31:21.958302Z","shell.execute_reply":"2025-02-08T04:31:35.94239Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:47.991522Z","iopub.execute_input":"2025-02-08T04:31:47.993234Z","iopub.status.idle":"2025-02-08T04:31:47.99853Z","shell.execute_reply.started":"2025-02-08T04:31:47.993188Z","shell.execute_reply":"2025-02-08T04:31:47.997397Z"}},"outputs":[],"execution_count":null},{"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":"# 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:53.461701Z","iopub.execute_input":"2025-02-08T04:31:53.462457Z","iopub.status.idle":"2025-02-08T04:31:53.467509Z","shell.execute_reply.started":"2025-02-08T04:31:53.46242Z","shell.execute_reply":"2025-02-08T04:31:53.466259Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:31:57.574216Z","iopub.execute_input":"2025-02-08T04:31:57.574588Z","iopub.status.idle":"2025-02-08T04:31:57.582191Z","shell.execute_reply.started":"2025-02-08T04:31:57.574561Z","shell.execute_reply":"2025-02-08T04:31:57.581061Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:05.836224Z","iopub.execute_input":"2025-02-08T04:32:05.836619Z","iopub.status.idle":"2025-02-08T04:32:06.936241Z","shell.execute_reply.started":"2025-02-08T04:32:05.836587Z","shell.execute_reply":"2025-02-08T04:32:06.934704Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:08.918365Z","iopub.execute_input":"2025-02-08T04:32:08.918775Z","iopub.status.idle":"2025-02-08T04:32:10.015333Z","shell.execute_reply.started":"2025-02-08T04:32:08.918742Z","shell.execute_reply":"2025-02-08T04:32:10.014025Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:12.629753Z","iopub.execute_input":"2025-02-08T04:32:12.630197Z","iopub.status.idle":"2025-02-08T04:32:13.729224Z","shell.execute_reply.started":"2025-02-08T04:32:12.630161Z","shell.execute_reply":"2025-02-08T04:32:13.727569Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:27.685785Z","iopub.execute_input":"2025-02-08T04:32:27.686212Z","iopub.status.idle":"2025-02-08T04:32:28.777628Z","shell.execute_reply.started":"2025-02-08T04:32:27.68618Z","shell.execute_reply":"2025-02-08T04:32:28.776174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:30.8542Z","iopub.execute_input":"2025-02-08T04:32:30.854617Z","iopub.status.idle":"2025-02-08T04:32:33.467949Z","shell.execute_reply.started":"2025-02-08T04:32:30.854584Z","shell.execute_reply":"2025-02-08T04:32:33.466657Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:36.701335Z","iopub.execute_input":"2025-02-08T04:32:36.701697Z","iopub.status.idle":"2025-02-08T04:32:36.707854Z","shell.execute_reply.started":"2025-02-08T04:32:36.701666Z","shell.execute_reply":"2025-02-08T04:32:36.706517Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:45.325709Z","iopub.execute_input":"2025-02-08T04:32:45.326089Z","iopub.status.idle":"2025-02-08T04:32:47.696202Z","shell.execute_reply.started":"2025-02-08T04:32:45.32606Z","shell.execute_reply":"2025-02-08T04:32:47.694989Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:50.542372Z","iopub.execute_input":"2025-02-08T04:32:50.542808Z","iopub.status.idle":"2025-02-08T04:32:52.778214Z","shell.execute_reply.started":"2025-02-08T04:32:50.542772Z","shell.execute_reply":"2025-02-08T04:32:52.776624Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:32:56.910276Z","iopub.execute_input":"2025-02-08T04:32:56.910734Z","iopub.status.idle":"2025-02-08T04:33:09.436995Z","shell.execute_reply.started":"2025-02-08T04:32:56.910661Z","shell.execute_reply":"2025-02-08T04:33:09.435006Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:12.79926Z","iopub.execute_input":"2025-02-08T04:33:12.799632Z","iopub.status.idle":"2025-02-08T04:33:12.816365Z","shell.execute_reply.started":"2025-02-08T04:33:12.799603Z","shell.execute_reply":"2025-02-08T04:33:12.815247Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:24.565803Z","iopub.execute_input":"2025-02-08T04:33:24.56627Z","iopub.status.idle":"2025-02-08T04:33:24.571378Z","shell.execute_reply.started":"2025-02-08T04:33:24.566238Z","shell.execute_reply":"2025-02-08T04:33:24.570229Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:32.760255Z","iopub.execute_input":"2025-02-08T04:33:32.760776Z","iopub.status.idle":"2025-02-08T04:33:32.769261Z","shell.execute_reply.started":"2025-02-08T04:33:32.760733Z","shell.execute_reply":"2025-02-08T04:33:32.767782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:37.67739Z","iopub.execute_input":"2025-02-08T04:33:37.677775Z","iopub.status.idle":"2025-02-08T04:33:37.684889Z","shell.execute_reply.started":"2025-02-08T04:33:37.677747Z","shell.execute_reply":"2025-02-08T04:33:37.683663Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:41.533892Z","iopub.execute_input":"2025-02-08T04:33:41.534299Z","iopub.status.idle":"2025-02-08T04:33:41.541315Z","shell.execute_reply.started":"2025-02-08T04:33:41.534268Z","shell.execute_reply":"2025-02-08T04:33:41.5401Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:43.838857Z","iopub.execute_input":"2025-02-08T04:33:43.839511Z","iopub.status.idle":"2025-02-08T04:33:43.849256Z","shell.execute_reply.started":"2025-02-08T04:33:43.839463Z","shell.execute_reply":"2025-02-08T04:33:43.847915Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:46.902091Z","iopub.execute_input":"2025-02-08T04:33:46.902513Z","iopub.status.idle":"2025-02-08T04:33:47.733857Z","shell.execute_reply.started":"2025-02-08T04:33:46.902484Z","shell.execute_reply":"2025-02-08T04:33:47.732638Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:51.342498Z","iopub.execute_input":"2025-02-08T04:33:51.342938Z","iopub.status.idle":"2025-02-08T04:33:52.186599Z","shell.execute_reply.started":"2025-02-08T04:33:51.342905Z","shell.execute_reply":"2025-02-08T04:33:52.185398Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_it), len(train_it.classes), train_it.classes[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:55.382638Z","iopub.execute_input":"2025-02-08T04:33:55.383045Z","iopub.status.idle":"2025-02-08T04:33:55.392972Z","shell.execute_reply.started":"2025-02-08T04:33:55.383016Z","shell.execute_reply":"2025-02-08T04:33:55.3916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(val_it), len(val_it.classes), val_it.classes[-10:]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:33:57.894112Z","iopub.execute_input":"2025-02-08T04:33:57.894539Z","iopub.status.idle":"2025-02-08T04:33:57.902324Z","shell.execute_reply.started":"2025-02-08T04:33:57.894506Z","shell.execute_reply":"2025-02-08T04:33:57.901112Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory_1 = model_1.fit_generator(\n    train_it, steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=20, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:35:15.680919Z","iopub.execute_input":"2025-02-08T04:35:15.681339Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-08T04:34:05.983182Z","iopub.execute_input":"2025-02-08T04:34:05.98358Z","iopub.status.idle":"2025-02-08T04:34:06.01677Z","shell.execute_reply.started":"2025-02-08T04:34:05.98355Z","shell.execute_reply":"2025-02-08T04:34:06.015212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate_generator(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning\n# 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":{"trusted":true},"outputs":[],"execution_count":null},{"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Image Augmentatioin\n\nfrom 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    fill_mode='reflect',\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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = train_it.__next__()\nprint(images.shape, labels.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model.layers):\n    print(index, layer.output.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null},{"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# evaluate model\n_, acc = model.evaluate_generator(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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null},{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}