{"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":"2025-02-28T06:58:32.516777Z","iopub.execute_input":"2025-02-28T06:58:32.516996Z","iopub.status.idle":"2025-02-28T06:58:32.811755Z","shell.execute_reply.started":"2025-02-28T06:58:32.516974Z","shell.execute_reply":"2025-02-28T06:58:32.810906Z"},"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":{"execution":{"iopub.status.busy":"2025-02-28T06:58:34.174630Z","iopub.execute_input":"2025-02-28T06:58:34.174942Z","iopub.status.idle":"2025-02-28T06:58:47.931098Z","shell.execute_reply.started":"2025-02-28T06:58:34.174915Z","shell.execute_reply":"2025-02-28T06:58:47.930177Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:58:47.932470Z","iopub.execute_input":"2025-02-28T06:58:47.932729Z","iopub.status.idle":"2025-02-28T06:58:48.962161Z","shell.execute_reply.started":"2025-02-28T06:58:47.932706Z","shell.execute_reply":"2025-02-28T06:58:48.961176Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ |wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:58:48.963482Z","iopub.execute_input":"2025-02-28T06:58:48.963740Z","iopub.status.idle":"2025-02-28T06:58:49.995941Z","shell.execute_reply.started":"2025-02-28T06:58:48.963718Z","shell.execute_reply":"2025-02-28T06:58:49.994949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ |wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:58:49.998054Z","iopub.execute_input":"2025-02-28T06:58:49.998343Z","iopub.status.idle":"2025-02-28T06:58:51.069471Z","shell.execute_reply.started":"2025-02-28T06:58:49.998319Z","shell.execute_reply":"2025-02-28T06:58:51.068706Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:58:51.070660Z","iopub.execute_input":"2025-02-28T06:58:51.070931Z","iopub.status.idle":"2025-02-28T06:58:52.196639Z","shell.execute_reply.started":"2025-02-28T06:58:51.070908Z","shell.execute_reply":"2025-02-28T06:58:52.195642Z"}},"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":{"execution":{"iopub.status.busy":"2025-02-28T06:58:52.198107Z","iopub.execute_input":"2025-02-28T06:58:52.198482Z","iopub.status.idle":"2025-02-28T06:58:53.125592Z","shell.execute_reply.started":"2025-02-28T06:58:52.198449Z","shell.execute_reply":"2025-02-28T06:58:53.124820Z"},"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-28T06:58:53.126971Z","iopub.execute_input":"2025-02-28T06:58:53.127644Z","iopub.status.idle":"2025-02-28T06:58:54.050439Z","shell.execute_reply.started":"2025-02-28T06:58:53.127611Z","shell.execute_reply":"2025-02-28T06:58:54.049659Z"},"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-28T06:58:54.051822Z","iopub.execute_input":"2025-02-28T06:58:54.052459Z","iopub.status.idle":"2025-02-28T06:59:04.607679Z","shell.execute_reply.started":"2025-02-28T06:58:54.052423Z","shell.execute_reply":"2025-02-28T06:59:04.606813Z"}},"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-28T06:59:04.608870Z","iopub.execute_input":"2025-02-28T06:59:04.609367Z","iopub.status.idle":"2025-02-28T06:59:04.613574Z","shell.execute_reply.started":"2025-02-28T06:59:04.609344Z","shell.execute_reply":"2025-02-28T06:59:04.612819Z"},"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":"# 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-28T06:59:04.616861Z","iopub.execute_input":"2025-02-28T06:59:04.617155Z","iopub.status.idle":"2025-02-28T06:59:04.643523Z","shell.execute_reply.started":"2025-02-28T06:59:04.617130Z","shell.execute_reply":"2025-02-28T06:59:04.642601Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-02-28T06:59:04.644763Z","iopub.execute_input":"2025-02-28T06:59:04.645074Z","iopub.status.idle":"2025-02-28T06:59:04.654956Z","shell.execute_reply.started":"2025-02-28T06:59:04.645047Z","shell.execute_reply":"2025-02-28T06:59:04.654133Z"},"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-28T06:59:04.656286Z","iopub.execute_input":"2025-02-28T06:59:04.656565Z","iopub.status.idle":"2025-02-28T06:59:05.673165Z","shell.execute_reply.started":"2025-02-28T06:59:04.656541Z","shell.execute_reply":"2025-02-28T06:59:05.672344Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:59:05.674674Z","iopub.execute_input":"2025-02-28T06:59:05.675028Z","iopub.status.idle":"2025-02-28T06:59:06.681707Z","shell.execute_reply.started":"2025-02-28T06:59:05.674987Z","shell.execute_reply":"2025-02-28T06:59:06.680870Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:59:06.682940Z","iopub.execute_input":"2025-02-28T06:59:06.683215Z","iopub.status.idle":"2025-02-28T06:59:07.711380Z","shell.execute_reply.started":"2025-02-28T06:59:06.683174Z","shell.execute_reply":"2025-02-28T06:59:07.710215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:59:07.713045Z","iopub.execute_input":"2025-02-28T06:59:07.713442Z","iopub.status.idle":"2025-02-28T06:59:08.767845Z","shell.execute_reply.started":"2025-02-28T06:59:07.713408Z","shell.execute_reply":"2025-02-28T06:59:08.767001Z"}},"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\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-28T06:59:08.769230Z","iopub.execute_input":"2025-02-28T06:59:08.769507Z","iopub.status.idle":"2025-02-28T06:59:11.081793Z","shell.execute_reply.started":"2025-02-28T06:59:08.769484Z","shell.execute_reply":"2025-02-28T06:59:11.080848Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:11.082928Z","iopub.execute_input":"2025-02-28T06:59:11.083161Z","iopub.status.idle":"2025-02-28T06:59:12.206679Z","shell.execute_reply.started":"2025-02-28T06:59:11.083142Z","shell.execute_reply":"2025-02-28T06:59:12.205823Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:12.208005Z","iopub.execute_input":"2025-02-28T06:59:12.208291Z","iopub.status.idle":"2025-02-28T06:59:13.287970Z","shell.execute_reply.started":"2025-02-28T06:59:12.208268Z","shell.execute_reply":"2025-02-28T06:59:13.286907Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:13.289736Z","iopub.execute_input":"2025-02-28T06:59:13.290619Z","iopub.status.idle":"2025-02-28T06:59:22.804109Z","shell.execute_reply.started":"2025-02-28T06:59:13.290581Z","shell.execute_reply":"2025-02-28T06:59:22.803134Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:22.805386Z","iopub.execute_input":"2025-02-28T06:59:22.805634Z","iopub.status.idle":"2025-02-28T06:59:22.821310Z","shell.execute_reply.started":"2025-02-28T06:59:22.805613Z","shell.execute_reply":"2025-02-28T06:59:22.820525Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"#start tutorial\n#Develop a Baseline CNN Model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T14:55:02.731984Z","iopub.execute_input":"2025-02-26T14:55:02.732233Z","iopub.status.idle":"2025-02-26T14:55:02.737392Z","shell.execute_reply.started":"2025-02-26T14:55:02.732212Z","shell.execute_reply":"2025-02-26T14:55:02.736695Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"CNN Model","metadata":{}},{"cell_type":"code","source":"\n# 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-28T06:59:22.822279Z","iopub.execute_input":"2025-02-28T06:59:22.822479Z","iopub.status.idle":"2025-02-28T06:59:22.827568Z","shell.execute_reply.started":"2025-02-28T06:59:22.822461Z","shell.execute_reply":"2025-02-28T06:59:22.826720Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.show()\n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:59:22.828493Z","iopub.execute_input":"2025-02-28T06:59:22.828738Z","iopub.status.idle":"2025-02-28T06:59:22.837145Z","shell.execute_reply.started":"2025-02-28T06:59:22.828704Z","shell.execute_reply":"2025-02-28T06:59:22.836374Z"}},"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-25T08:51:46.984886Z","iopub.execute_input":"2025-02-25T08:51:46.985130Z","iopub.status.idle":"2025-02-25T08:51:46.996645Z","shell.execute_reply.started":"2025-02-25T08:51:46.985111Z","shell.execute_reply":"2025-02-25T08:51:46.995996Z"}},"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-25T08:51:46.997779Z","iopub.execute_input":"2025-02-25T08:51:46.998478Z","iopub.status.idle":"2025-02-25T08:51:48.255126Z","shell.execute_reply.started":"2025-02-25T08:51:46.998448Z","shell.execute_reply":"2025-02-25T08:51:48.254281Z"}},"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T07:05:31.906615Z","iopub.execute_input":"2025-02-26T07:05:31.906968Z","iopub.status.idle":"2025-02-26T07:05:31.913063Z","shell.execute_reply.started":"2025-02-26T07:05:31.906941Z","shell.execute_reply":"2025-02-26T07:05:31.912087Z"}},"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-26T07:05:32.547337Z","iopub.execute_input":"2025-02-26T07:05:32.548185Z","iopub.status.idle":"2025-02-26T07:05:33.205673Z","shell.execute_reply.started":"2025-02-26T07:05:32.548157Z","shell.execute_reply":"2025-02-26T07:05:33.205006Z"}},"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-26T07:05:35.839572Z","iopub.execute_input":"2025-02-26T07:05:35.839914Z","iopub.status.idle":"2025-02-26T07:05:35.846880Z","shell.execute_reply.started":"2025-02-26T07:05:35.839889Z","shell.execute_reply":"2025-02-26T07:05:35.845771Z"}},"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-26T07:05:36.750469Z","iopub.execute_input":"2025-02-26T07:05:36.750933Z","iopub.status.idle":"2025-02-26T07:05:36.757943Z","shell.execute_reply.started":"2025-02-26T07:05:36.750907Z","shell.execute_reply":"2025-02-26T07:05:36.756878Z"}},"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-25T08:52:09.277606Z","iopub.execute_input":"2025-02-25T08:52:09.277867Z","iopub.status.idle":"2025-02-25T08:52:10.016289Z","shell.execute_reply.started":"2025-02-25T08:52:09.277845Z","shell.execute_reply":"2025-02-25T08:52:10.014860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n\tsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T07:49:15.243158Z","iopub.execute_input":"2025-02-14T07:49:15.243941Z","iopub.status.idle":"2025-02-14T07:49:15.253279Z","shell.execute_reply.started":"2025-02-14T07:49:15.243888Z","shell.execute_reply":"2025-02-14T07:49:15.251336Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate_generator(test_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true},"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-28T06:59:22.840531Z","iopub.execute_input":"2025-02-28T06:59:22.840782Z","iopub.status.idle":"2025-02-28T06:59:22.845650Z","shell.execute_reply.started":"2025-02-28T06:59:22.840748Z","shell.execute_reply":"2025-02-28T06:59:22.844920Z"},"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":"markdown","source":"VGG16","metadata":{}},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n# create data generator\ndatagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:22.846719Z","iopub.execute_input":"2025-02-28T06:59:22.846945Z","iopub.status.idle":"2025-02-28T06:59:23.717131Z","shell.execute_reply.started":"2025-02-28T06:59:22.846926Z","shell.execute_reply":"2025-02-28T06:59:23.716323Z"},"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))","metadata":{"execution":{"iopub.status.busy":"2025-02-28T06:59:23.718160Z","iopub.execute_input":"2025-02-28T06:59:23.718433Z","iopub.status.idle":"2025-02-28T06:59:25.893211Z","shell.execute_reply.started":"2025-02-28T06:59:23.718411Z","shell.execute_reply":"2025-02-28T06:59:25.888890Z"},"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,"execution":{"iopub.status.busy":"2025-02-28T06:59:25.894157Z","iopub.execute_input":"2025-02-28T06:59:25.894417Z","iopub.status.idle":"2025-02-28T06:59:25.900986Z","shell.execute_reply.started":"2025-02-28T06:59:25.894395Z","shell.execute_reply":"2025-02-28T06:59:25.900184Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T06:59:25.901981Z","iopub.execute_input":"2025-02-28T06:59:25.902288Z","iopub.status.idle":"2025-02-28T06:59:25.910232Z","shell.execute_reply.started":"2025-02-28T06:59:25.902267Z","shell.execute_reply":"2025-02-28T06:59:25.909459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(512, activation='relu', kernel_initializer='he_uniform')(flat1)\nclass2 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class1)\nclass3 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class2)\noutput = Dense(1, activation='sigmoid')(class3)\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,"execution":{"iopub.status.busy":"2025-02-28T06:59:25.911249Z","iopub.execute_input":"2025-02-28T06:59:25.911540Z","iopub.status.idle":"2025-02-28T06:59:26.021582Z","shell.execute_reply.started":"2025-02-28T06:59:25.911513Z","shell.execute_reply":"2025-02-28T06:59:26.020754Z"}},"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=30, verbose=1,\n                    callbacks=[PlotLossesKeras()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T07:07:29.803749Z","iopub.execute_input":"2025-02-28T07:07:29.804133Z","iopub.status.idle":"2025-02-28T09:36:12.434400Z","shell.execute_reply.started":"2025-02-28T07:07:29.804105Z","shell.execute_reply":"2025-02-28T09:36:12.433743Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = my_model.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:53:12.528693Z","iopub.execute_input":"2025-02-28T10:53:12.529366Z","iopub.status.idle":"2025-02-28T10:54:28.175432Z","shell.execute_reply.started":"2025-02-28T10:53:12.529337Z","shell.execute_reply":"2025-02-28T10:54:28.174563Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:54:38.680756Z","iopub.execute_input":"2025-02-28T10:54:38.681394Z","iopub.status.idle":"2025-02-28T10:54:39.080009Z","shell.execute_reply.started":"2025-02-28T10:54:38.681363Z","shell.execute_reply":"2025-02-28T10:54:39.079265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:54:43.628257Z","iopub.execute_input":"2025-02-28T10:54:43.628914Z","iopub.status.idle":"2025-02-28T10:54:44.145020Z","shell.execute_reply.started":"2025-02-28T10:54:43.628886Z","shell.execute_reply":"2025-02-28T10:54:44.143987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:54:47.537089Z","iopub.execute_input":"2025-02-28T10:54:47.537436Z","iopub.status.idle":"2025-02-28T10:56:03.443571Z","shell.execute_reply.started":"2025-02-28T10:54:47.537409Z","shell.execute_reply":"2025-02-28T10:56:03.442861Z"}},"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-28T09:42:44.648230Z","iopub.execute_input":"2025-02-28T09:42:44.648587Z","iopub.status.idle":"2025-02-28T09:42:44.653095Z","shell.execute_reply.started":"2025-02-28T09:42:44.648561Z","shell.execute_reply":"2025-02-28T09:42:44.652144Z"}},"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":"import matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:56:24.734608Z","iopub.execute_input":"2025-02-28T10:56:24.735306Z","iopub.status.idle":"2025-02-28T10:56:24.738906Z","shell.execute_reply.started":"2025-02-28T10:56:24.735278Z","shell.execute_reply":"2025-02-28T10:56:24.737975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\ndef predict_random_images(test_dir, model, class_names):\n    img_size=(224, 224)\n    images = []  # เก็บ path รูปภาพ\n    labels = []  # เก็บ label จริง\n\n    # เลือก 5 รูปจากแต่ละ class\n    for label in class_names:\n        folder = os.path.join(test_dir, label)\n        files = random.sample(list(os.listdir(folder)), 5)\n        for f in files:\n            images.append(os.path.join(folder, f))\n            labels.append(label)\n\n    # Plot\n    fig, axes = plt.subplots(2, 5, figsize=(12, 6))\n    for i, (img_path, true_label) in enumerate(zip(images, labels)):\n        img = load_img(img_path, target_size=img_size)\n        img_array = img_to_array(img)\n        img_array = np.expand_dims(img_array, axis=0)\n\n        pred = model.predict(img_array)[0]  # ค่าระหว่าง 0-1\n        pred_label = class_names[1] if pred > 0.5 else class_names[0]\n\n        axes[i // 5, i % 5].imshow(img)\n        axes[i // 5, i % 5].set_title(f\"Pred: {pred_label}\\nTrue: {true_label}\", fontsize=10)\n        axes[i // 5, i % 5].axis(\"off\")\n\n    plt.tight_layout()\n    plt.show()\npredict_random_images(\"dataset_dogs_vs_cats/test/\", best_model, [\"cats\", \"dogs\"])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-28T10:56:24.939812Z","iopub.execute_input":"2025-02-28T10:56:24.940031Z","iopub.status.idle":"2025-02-28T10:56:26.654009Z","shell.execute_reply.started":"2025-02-28T10:56:24.940013Z","shell.execute_reply":"2025-02-28T10:56:26.653119Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}