{"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","trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:22:19.398887Z","iopub.execute_input":"2025-02-14T10:22:19.399192Z","iopub.status.idle":"2025-02-14T10:22:19.705804Z","shell.execute_reply.started":"2025-02-14T10:22:19.399162Z","shell.execute_reply":"2025-02-14T10:22:19.704973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:22:19.706839Z","iopub.execute_input":"2025-02-14T10:22:19.707145Z","iopub.status.idle":"2025-02-14T10:22:20.760802Z","shell.execute_reply.started":"2025-02-14T10:22:19.707124Z","shell.execute_reply":"2025-02-14T10:22:20.759648Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:22:20.763681Z","iopub.execute_input":"2025-02-14T10:22:20.763998Z","iopub.status.idle":"2025-02-14T10:22:21.819571Z","shell.execute_reply.started":"2025-02-14T10:22:20.763975Z","shell.execute_reply":"2025-02-14T10:22:21.818639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l test1/ | wc -1 ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:22:21.820724Z","iopub.execute_input":"2025-02-14T10:22:21.821061Z","iopub.status.idle":"2025-02-14T10:22:22.844798Z","shell.execute_reply.started":"2025-02-14T10:22:21.821036Z","shell.execute_reply":"2025-02-14T10:22:22.843976Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:23:11.682887Z","iopub.execute_input":"2025-02-14T10:23:11.683521Z","iopub.status.idle":"2025-02-14T10:23:12.822073Z","shell.execute_reply.started":"2025-02-14T10:23:11.683491Z","shell.execute_reply":"2025-02-14T10:23:12.820997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:23:28.459156Z","iopub.execute_input":"2025-02-14T10:23:28.460032Z","iopub.status.idle":"2025-02-14T10:23:29.468829Z","shell.execute_reply.started":"2025-02-14T10:23:28.45999Z","shell.execute_reply":"2025-02-14T10:23:29.4676Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:23:29.831742Z","iopub.execute_input":"2025-02-14T10:23:29.832616Z","iopub.status.idle":"2025-02-14T10:23:39.280312Z","shell.execute_reply.started":"2025-02-14T10:23:29.832582Z","shell.execute_reply":"2025-02-14T10:23:39.27934Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-02-14T10:23:40.306721Z","iopub.execute_input":"2025-02-14T10:23:40.307084Z","iopub.status.idle":"2025-02-14T10:23:41.229012Z","shell.execute_reply.started":"2025-02-14T10:23:40.307051Z","shell.execute_reply":"2025-02-14T10:23:41.228246Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:23:41.231097Z","iopub.execute_input":"2025-02-14T10:23:41.231825Z","iopub.status.idle":"2025-02-14T10:23:42.158788Z","shell.execute_reply.started":"2025-02-14T10:23:41.231791Z","shell.execute_reply":"2025-02-14T10:23:42.157981Z"},"trusted":true},"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-14T10:23:43.28853Z","iopub.execute_input":"2025-02-14T10:23:43.289337Z","iopub.status.idle":"2025-02-14T10:23:53.548327Z","shell.execute_reply.started":"2025-02-14T10:23:43.289307Z","shell.execute_reply":"2025-02-14T10:23:53.547504Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:23:53.54964Z","iopub.execute_input":"2025-02-14T10:23:53.550121Z","iopub.status.idle":"2025-02-14T10:23:53.554243Z","shell.execute_reply.started":"2025-02-14T10:23:53.550098Z","shell.execute_reply":"2025-02-14T10:23:53.553484Z"},"trusted":true},"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":"\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":"2025-02-14T10:23:53.555239Z","iopub.execute_input":"2025-02-14T10:23:53.55549Z","iopub.status.idle":"2025-02-14T10:23:53.56648Z","shell.execute_reply.started":"2025-02-14T10:23:53.555469Z","shell.execute_reply":"2025-02-14T10:23:53.565621Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\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":{"execution":{"iopub.status.busy":"2025-02-14T10:23:53.568119Z","iopub.execute_input":"2025-02-14T10:23:53.568357Z","iopub.status.idle":"2025-02-14T10:23:53.574789Z","shell.execute_reply.started":"2025-02-14T10:23:53.568338Z","shell.execute_reply":"2025-02-14T10:23:53.574156Z"},"trusted":true},"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-14T10:23:53.705476Z","iopub.execute_input":"2025-02-14T10:23:53.705901Z","iopub.status.idle":"2025-02-14T10:23:54.710466Z","shell.execute_reply.started":"2025-02-14T10:23:53.70588Z","shell.execute_reply":"2025-02-14T10:23:54.709391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:23:55.155885Z","iopub.execute_input":"2025-02-14T10:23:55.156323Z","iopub.status.idle":"2025-02-14T10:23:56.166396Z","shell.execute_reply.started":"2025-02-14T10:23:55.156295Z","shell.execute_reply":"2025-02-14T10:23:56.165158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:13:22.669877Z","iopub.execute_input":"2025-02-14T10:13:22.670259Z","iopub.status.idle":"2025-02-14T10:13:23.685856Z","shell.execute_reply.started":"2025-02-14T10:13:22.670231Z","shell.execute_reply":"2025-02-14T10:13:23.684898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:01.262518Z","iopub.execute_input":"2025-02-14T10:24:01.26287Z","iopub.status.idle":"2025-02-14T10:24:02.314227Z","shell.execute_reply.started":"2025-02-14T10:24:01.262843Z","shell.execute_reply":"2025-02-14T10:24:02.313128Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\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":"2025-02-14T10:24:14.492147Z","iopub.execute_input":"2025-02-14T10:24:14.492929Z","iopub.status.idle":"2025-02-14T10:24:16.787727Z","shell.execute_reply.started":"2025-02-14T10:24:14.492882Z","shell.execute_reply":"2025-02-14T10:24:16.787053Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:19.391207Z","iopub.execute_input":"2025-02-14T10:24:19.392049Z","iopub.status.idle":"2025-02-14T10:24:19.396158Z","shell.execute_reply.started":"2025-02-14T10:24:19.392021Z","shell.execute_reply":"2025-02-14T10:24:19.395266Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:24.196534Z","iopub.execute_input":"2025-02-14T10:24:24.197398Z","iopub.status.idle":"2025-02-14T10:24:25.367684Z","shell.execute_reply.started":"2025-02-14T10:24:24.197366Z","shell.execute_reply":"2025-02-14T10:24:25.366844Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:25.781007Z","iopub.execute_input":"2025-02-14T10:24:25.78129Z","iopub.status.idle":"2025-02-14T10:24:26.865584Z","shell.execute_reply.started":"2025-02-14T10:24:25.781267Z","shell.execute_reply":"2025-02-14T10:24:26.864546Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/test/dogs | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:27.246544Z","iopub.execute_input":"2025-02-14T10:24:27.246895Z","iopub.status.idle":"2025-02-14T10:24:28.284613Z","shell.execute_reply.started":"2025-02-14T10:24:27.246867Z","shell.execute_reply":"2025-02-14T10:24:28.283739Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:28.767114Z","iopub.execute_input":"2025-02-14T10:24:28.767774Z","iopub.status.idle":"2025-02-14T10:24:29.809172Z","shell.execute_reply.started":"2025-02-14T10:24:28.767743Z","shell.execute_reply":"2025-02-14T10:24:29.808293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-14T10:24:33.402164Z","iopub.execute_input":"2025-02-14T10:24:33.402483Z","iopub.status.idle":"2025-02-14T10:24:42.725644Z","shell.execute_reply.started":"2025-02-14T10:24:33.40246Z","shell.execute_reply":"2025-02-14T10:24:42.724618Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-14T10:24:42.727468Z","iopub.execute_input":"2025-02-14T10:24:42.727754Z","iopub.status.idle":"2025-02-14T10:24:42.741584Z","shell.execute_reply.started":"2025-02-14T10:24:42.72773Z","shell.execute_reply":"2025-02-14T10:24:42.740965Z"},"trusted":true},"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:23:31.512584Z","iopub.execute_input":"2025-02-08T04:23:31.513431Z","iopub.status.idle":"2025-02-08T04:23:31.517694Z","shell.execute_reply.started":"2025-02-08T04:23:31.513395Z","shell.execute_reply":"2025-02-08T04:23:31.516496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import 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\n ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:42.742506Z","iopub.execute_input":"2025-02-14T10:24:42.742756Z","iopub.status.idle":"2025-02-14T10:24:42.748059Z","shell.execute_reply.started":"2025-02-14T10:24:42.742736Z","shell.execute_reply":"2025-02-14T10:24:42.7472Z"}},"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\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:24:43.02494Z","iopub.execute_input":"2025-02-14T10:24:43.02518Z","iopub.status.idle":"2025-02-14T10:24:43.030214Z","shell.execute_reply.started":"2025-02-14T10:24:43.025161Z","shell.execute_reply":"2025-02-14T10:24:43.029407Z"}},"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-14T10:24:46.288358Z","iopub.execute_input":"2025-02-14T10:24:46.288918Z","iopub.status.idle":"2025-02-14T10:24:47.488335Z","shell.execute_reply.started":"2025-02-14T10:24:46.288887Z","shell.execute_reply":"2025-02-14T10:24:47.487515Z"}},"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-14T10:24:55.6972Z","iopub.execute_input":"2025-02-14T10:24:55.698005Z","iopub.status.idle":"2025-02-14T10:24:55.703242Z","shell.execute_reply.started":"2025-02-14T10:24:55.697975Z","shell.execute_reply":"2025-02-14T10:24:55.702479Z"}},"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-14T10:15:02.752206Z","iopub.execute_input":"2025-02-14T10:15:02.752522Z","iopub.status.idle":"2025-02-14T10:15:02.758766Z","shell.execute_reply.started":"2025-02-14T10:15:02.752496Z","shell.execute_reply":"2025-02-14T10:15:02.757723Z"}},"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-14T10:25:01.517752Z","iopub.execute_input":"2025-02-14T10:25:01.518548Z","iopub.status.idle":"2025-02-14T10:25:02.444445Z","shell.execute_reply.started":"2025-02-14T10:25:01.518507Z","shell.execute_reply":"2025-02-14T10:25:02.443594Z"}},"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-14T10:25:04.946548Z","iopub.execute_input":"2025-02-14T10:25:04.947137Z","iopub.status.idle":"2025-02-14T10:25:04.953303Z","shell.execute_reply.started":"2025-02-14T10:25:04.947107Z","shell.execute_reply":"2025-02-14T10:25:04.952494Z"}},"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-14T10:25:07.191683Z","iopub.execute_input":"2025-02-14T10:25:07.192263Z","iopub.status.idle":"2025-02-14T10:25:07.198188Z","shell.execute_reply.started":"2025-02-14T10:25:07.192234Z","shell.execute_reply":"2025-02-14T10:25:07.197398Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit_generator(\n    train_it, steps_per_epoch=len(train_it),\n    validation_data=test_it,\n    validation_steps=len(val_it),\n    epochs=20, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:25:09.345908Z","iopub.execute_input":"2025-02-14T10:25:09.346281Z","iopub.status.idle":"2025-02-14T10:25:09.830254Z","shell.execute_reply.started":"2025-02-14T10:25:09.346256Z","shell.execute_reply":"2025-02-14T10:25:09.829218Z"}},"outputs":[],"execution_count":null},{"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":"2025-02-14T10:25:15.287945Z","iopub.execute_input":"2025-02-14T10:25:15.288737Z","iopub.status.idle":"2025-02-14T10:25:15.293097Z","shell.execute_reply.started":"2025-02-14T10:25:15.288709Z","shell.execute_reply":"2025-02-14T10:25:15.292152Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","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":"test_images = test_it.__next__()\ntest_images.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:25:18.432363Z","iopub.execute_input":"2025-02-14T10:25:18.432682Z","iopub.status.idle":"2025-02-14T10:25:18.458617Z","shell.execute_reply.started":"2025-02-14T10:25:18.432658Z","shell.execute_reply":"2025-02-14T10:25:18.457478Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:25:20.670474Z","iopub.execute_input":"2025-02-14T10:25:20.67081Z","iopub.status.idle":"2025-02-14T10:25:21.640299Z","shell.execute_reply.started":"2025-02-14T10:25:20.670782Z","shell.execute_reply":"2025-02-14T10:25:21.639443Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = train_it.__next__()\nprint(images.shape, labels.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:25:23.930056Z","iopub.execute_input":"2025-02-14T10:25:23.930377Z","iopub.status.idle":"2025-02-14T10:25:24.600908Z","shell.execute_reply.started":"2025-02-14T10:25:23.930355Z","shell.execute_reply":"2025-02-14T10:25:24.599969Z"}},"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,"execution":{"iopub.status.busy":"2025-02-14T10:25:26.623464Z","iopub.execute_input":"2025-02-14T10:25:26.624048Z","iopub.status.idle":"2025-02-14T10:25:26.631023Z","shell.execute_reply.started":"2025-02-14T10:25:26.624019Z","shell.execute_reply":"2025-02-14T10:25:26.630173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:25:35.631516Z","iopub.execute_input":"2025-02-14T10:25:35.632498Z","iopub.status.idle":"2025-02-14T10:25:37.474577Z","shell.execute_reply.started":"2025-02-14T10:25:35.632464Z","shell.execute_reply":"2025-02-14T10:25:37.473687Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:25:42.503243Z","iopub.execute_input":"2025-02-14T10:25:42.504123Z","iopub.status.idle":"2025-02-14T10:25:43.309349Z","shell.execute_reply.started":"2025-02-14T10:25:42.504091Z","shell.execute_reply":"2025-02-14T10:25:43.308475Z"},"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,"execution":{"iopub.status.busy":"2025-02-14T10:25:47.371385Z","iopub.execute_input":"2025-02-14T10:25:47.372347Z","iopub.status.idle":"2025-02-14T10:25:47.377204Z","shell.execute_reply.started":"2025-02-14T10:25:47.372311Z","shell.execute_reply":"2025-02-14T10:25:47.376286Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:25:49.82281Z","iopub.execute_input":"2025-02-14T10:25:49.82347Z","iopub.status.idle":"2025-02-14T10:25:49.829958Z","shell.execute_reply.started":"2025-02-14T10:25:49.823437Z","shell.execute_reply":"2025-02-14T10:25:49.829062Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2025-02-14T10:25:55.09968Z","iopub.execute_input":"2025-02-14T10:25:55.100058Z","iopub.status.idle":"2025-02-14T10:25:55.105725Z","shell.execute_reply.started":"2025-02-14T10:25:55.100029Z","shell.execute_reply":"2025-02-14T10:25:55.104839Z"},"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":{"execution":{"iopub.status.busy":"2025-02-14T10:25:57.09316Z","iopub.execute_input":"2025-02-14T10:25:57.093504Z","iopub.status.idle":"2025-02-14T10:25:57.183826Z","shell.execute_reply.started":"2025-02-14T10:25:57.093468Z","shell.execute_reply":"2025-02-14T10:25:57.182732Z"},"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,"execution":{"iopub.status.busy":"2025-02-14T10:29:12.72245Z","iopub.execute_input":"2025-02-14T10:29:12.723363Z","iopub.status.idle":"2025-02-14T10:29:12.727895Z","shell.execute_reply.started":"2025-02-14T10:29:12.723322Z","shell.execute_reply":"2025-02-14T10:29:12.727034Z"}},"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,"execution":{"iopub.status.busy":"2025-02-14T10:29:15.494418Z","iopub.execute_input":"2025-02-14T10:29:15.495024Z","iopub.status.idle":"2025-02-14T10:29:15.579294Z","shell.execute_reply.started":"2025-02-14T10:29:15.494994Z","shell.execute_reply":"2025-02-14T10:29:15.578241Z"}},"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(5):\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-14T10:32:06.461057Z","iopub.execute_input":"2025-02-14T10:32:06.461384Z","iopub.status.idle":"2025-02-14T10:32:06.924904Z","shell.execute_reply.started":"2025-02-14T10:32:06.46136Z","shell.execute_reply":"2025-02-14T10:32:06.924069Z"}},"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(5):\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-14T10:32:32.614309Z","iopub.execute_input":"2025-02-14T10:32:32.614648Z","iopub.status.idle":"2025-02-14T10:32:33.193782Z","shell.execute_reply.started":"2025-02-14T10:32:32.614621Z","shell.execute_reply":"2025-02-14T10:32:33.192828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n\n\nfolder = 'train/'  \ncat_images = [f for f in os.listdir(folder) if f.startswith('cat') and f.endswith('.jpg')]\n\n# สุ่มเลือก 5 รูปจากไฟล์ที่มีอยู่\nrandom_cats = random.sample(cat_images, 5)\n\n# Plot รูปภาพที่สุ่มได้\nfor i, filename in enumerate(random_cats):\n    pyplot.subplot(330 + 1 + i)\n    image = imread(os.path.join(folder, filename))\n    pyplot.imshow(image)\n    pyplot.axis('off')  \n\n\npyplot.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:33:24.917696Z","iopub.execute_input":"2025-02-14T10:33:24.918516Z","iopub.status.idle":"2025-02-14T10:33:25.234762Z","shell.execute_reply.started":"2025-02-14T10:33:24.918486Z","shell.execute_reply":"2025-02-14T10:33:25.233945Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n\n\nfolder = 'train/'  \ndog_images = [f for f in os.listdir(folder) if f.startswith('dog') and f.endswith('.jpg')]\n\n\nrandom_dogs = random.sample(dog_images, 5)\n\n# Plot รูปภาพที่สุ่มได้\nfor i, filename in enumerate(random_dogs):\n    pyplot.subplot(330 + 1 + i)\n    image = imread(os.path.join(folder, filename))\n    pyplot.imshow(image)\n    pyplot.axis('off')  \n\npyplot.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:33:58.260853Z","iopub.execute_input":"2025-02-14T10:33:58.261232Z","iopub.status.idle":"2025-02-14T10:33:58.756627Z","shell.execute_reply.started":"2025-02-14T10:33:58.261204Z","shell.execute_reply":"2025-02-14T10:33:58.755708Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:36:53.634315Z","iopub.execute_input":"2025-02-14T10:36:53.634869Z","iopub.status.idle":"2025-02-14T10:36:53.639252Z","shell.execute_reply.started":"2025-02-14T10:36:53.634845Z","shell.execute_reply":"2025-02-14T10:36:53.63839Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1.0/255,\n    rotation_range=20,\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    validation_split=0.2  # แบ่ง 20% ของข้อมูลเป็น validation\n)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n    'train/',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='binary',\n    subset='training'\n)\n\nval_generator = train_datagen.flow_from_directory(\n    'train/',\n    target_size=(224, 224),\n    batch_size=32,\n    class_mode='binary',\n    subset='validation'\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:37:28.851637Z","iopub.execute_input":"2025-02-14T10:37:28.852449Z","iopub.status.idle":"2025-02-14T10:37:29.117068Z","shell.execute_reply.started":"2025-02-14T10:37:28.852421Z","shell.execute_reply":"2025-02-14T10:37:29.116404Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\n\n\nbase_model.trainable = False\n\n\nmodel = Sequential([\n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(256, activation='relu'),\n    Dropout(0.4),\n    Dense(1, activation='sigmoid')  # Binary Classification\n])\n\n\nmodel.compile(optimizer=Adam(learning_rate=0.0001),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])\n\n\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:37:40.906157Z","iopub.execute_input":"2025-02-14T10:37:40.90703Z","iopub.status.idle":"2025-02-14T10:37:43.853445Z","shell.execute_reply.started":"2025-02-14T10:37:40.906986Z","shell.execute_reply":"2025-02-14T10:37:43.852571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, min_lr=1e-6, verbose=1)\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:37:53.520507Z","iopub.execute_input":"2025-02-14T10:37:53.521208Z","iopub.status.idle":"2025-02-14T10:37:53.525172Z","shell.execute_reply.started":"2025-02-14T10:37:53.521178Z","shell.execute_reply":"2025-02-14T10:37:53.524353Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_directory(\n    'train/',\n    target_size=(224, 224),\n    batch_size=1,  # กำหนดให้โหลดทีละ 1 รูป\n    class_mode='binary',\n    subset='training'\n)\n\nfor img, label in train_generator:\n    print(img.shape, label)\n    break  #\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T10:39:12.758098Z","iopub.execute_input":"2025-02-14T10:39:12.758797Z","iopub.status.idle":"2025-02-14T10:39:12.895243Z","shell.execute_reply.started":"2025-02-14T10:39:12.758771Z","shell.execute_reply":"2025-02-14T10:39:12.89455Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}