{"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-15T02:41:42.94553Z","iopub.execute_input":"2025-02-15T02:41:42.946558Z","iopub.status.idle":"2025-02-15T02:41:42.954372Z","shell.execute_reply.started":"2025-02-15T02:41:42.946516Z","shell.execute_reply":"2025-02-15T02:41:42.953674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T12:08:38.572068Z","iopub.execute_input":"2025-02-14T12:08:38.572636Z","iopub.status.idle":"2025-02-14T12:08:39.709767Z","shell.execute_reply.started":"2025-02-14T12:08:38.572599Z","shell.execute_reply":"2025-02-14T12:08:39.708704Z"}},"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-15T02:41:49.37622Z","iopub.execute_input":"2025-02-15T02:41:49.376574Z","iopub.status.idle":"2025-02-15T02:41:58.768087Z","shell.execute_reply.started":"2025-02-15T02:41:49.376547Z","shell.execute_reply":"2025-02-15T02:41:58.76709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:41:58.769771Z","iopub.execute_input":"2025-02-15T02:41:58.770102Z","iopub.status.idle":"2025-02-15T02:41:59.817375Z","shell.execute_reply.started":"2025-02-15T02:41:58.77007Z","shell.execute_reply":"2025-02-15T02:41:59.81648Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:41:59.818825Z","iopub.execute_input":"2025-02-15T02:41:59.819194Z","iopub.status.idle":"2025-02-15T02:42:00.840007Z","shell.execute_reply.started":"2025-02-15T02:41:59.819149Z","shell.execute_reply":"2025-02-15T02:42:00.839121Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:42:00.841974Z","iopub.execute_input":"2025-02-15T02:42:00.842273Z","iopub.status.idle":"2025-02-15T02:42:01.901333Z","shell.execute_reply.started":"2025-02-15T02:42:00.84224Z","shell.execute_reply":"2025-02-15T02:42:01.900494Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:42:01.902657Z","iopub.execute_input":"2025-02-15T02:42:01.902914Z","iopub.status.idle":"2025-02-15T02:42:03.011146Z","shell.execute_reply.started":"2025-02-15T02:42:01.902891Z","shell.execute_reply":"2025-02-15T02:42:03.010284Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T12:08:59.077492Z","iopub.execute_input":"2025-02-14T12:08:59.077876Z","iopub.status.idle":"2025-02-14T12:09:00.374154Z","shell.execute_reply.started":"2025-02-14T12:08:59.07784Z","shell.execute_reply":"2025-02-14T12:09:00.37288Z"}},"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-15T02:51:37.187688Z","iopub.execute_input":"2025-02-15T02:51:37.188644Z","iopub.status.idle":"2025-02-15T02:51:38.154229Z","shell.execute_reply.started":"2025-02-15T02:51:37.188612Z","shell.execute_reply":"2025-02-15T02:51:38.153396Z"}},"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-15T02:51:38.484949Z","iopub.execute_input":"2025-02-15T02:51:38.485766Z","iopub.status.idle":"2025-02-15T02:51:39.461127Z","shell.execute_reply.started":"2025-02-15T02:51:38.485736Z","shell.execute_reply":"2025-02-15T02:51:39.460204Z"}},"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-15T02:51:41.268494Z","iopub.execute_input":"2025-02-15T02:51:41.269194Z","iopub.status.idle":"2025-02-15T02:51:41.274002Z","shell.execute_reply.started":"2025-02-15T02:51:41.269165Z","shell.execute_reply":"2025-02-15T02:51:41.273108Z"}},"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-15T02:51:42.272793Z","iopub.execute_input":"2025-02-15T02:51:42.273112Z","iopub.status.idle":"2025-02-15T02:51:42.277512Z","shell.execute_reply.started":"2025-02-15T02:51:42.273087Z","shell.execute_reply":"2025-02-15T02:51:42.276552Z"}},"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-15T02:51:43.920438Z","iopub.execute_input":"2025-02-15T02:51:43.920777Z","iopub.status.idle":"2025-02-15T02:51:43.925292Z","shell.execute_reply.started":"2025-02-15T02:51:43.92075Z","shell.execute_reply":"2025-02-15T02:51:43.924401Z"}},"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-15T02:51:44.611206Z","iopub.execute_input":"2025-02-15T02:51:44.612156Z","iopub.status.idle":"2025-02-15T02:51:44.61781Z","shell.execute_reply.started":"2025-02-15T02:51:44.612105Z","shell.execute_reply":"2025-02-15T02:51:44.616805Z"}},"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-15T02:51:46.195239Z","iopub.execute_input":"2025-02-15T02:51:46.195627Z","iopub.status.idle":"2025-02-15T02:51:47.230213Z","shell.execute_reply.started":"2025-02-15T02:51:46.195597Z","shell.execute_reply":"2025-02-15T02:51:47.229055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:51:50.035941Z","iopub.execute_input":"2025-02-15T02:51:50.036325Z","iopub.status.idle":"2025-02-15T02:51:51.082748Z","shell.execute_reply.started":"2025-02-15T02:51:50.036292Z","shell.execute_reply":"2025-02-15T02:51:51.081833Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:51:51.107454Z","iopub.execute_input":"2025-02-15T02:51:51.107758Z","iopub.status.idle":"2025-02-15T02:51:52.138563Z","shell.execute_reply.started":"2025-02-15T02:51:51.107733Z","shell.execute_reply":"2025-02-15T02:51:52.137413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:51:52.179275Z","iopub.execute_input":"2025-02-15T02:51:52.17968Z","iopub.status.idle":"2025-02-15T02:51:53.208311Z","shell.execute_reply.started":"2025-02-15T02:51:52.17965Z","shell.execute_reply":"2025-02-15T02:51:53.207119Z"}},"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-15T02:51:53.39591Z","iopub.execute_input":"2025-02-15T02:51:53.396281Z","iopub.status.idle":"2025-02-15T02:51:55.761259Z","shell.execute_reply.started":"2025-02-15T02:51:53.39625Z","shell.execute_reply":"2025-02-15T02:51:55.760552Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:51:55.762624Z","iopub.execute_input":"2025-02-15T02:51:55.762896Z","iopub.status.idle":"2025-02-15T02:51:55.767238Z","shell.execute_reply.started":"2025-02-15T02:51:55.762873Z","shell.execute_reply":"2025-02-15T02:51:55.766428Z"}},"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-15T02:51:56.788313Z","iopub.execute_input":"2025-02-15T02:51:56.788998Z","iopub.status.idle":"2025-02-15T02:51:59.043738Z","shell.execute_reply.started":"2025-02-15T02:51:56.788967Z","shell.execute_reply":"2025-02-15T02:51:59.042778Z"}},"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-15T02:51:59.04548Z","iopub.execute_input":"2025-02-15T02:51:59.045777Z","iopub.status.idle":"2025-02-15T02:52:01.141494Z","shell.execute_reply.started":"2025-02-15T02:51:59.045752Z","shell.execute_reply":"2025-02-15T02:52:01.140179Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:05.922092Z","iopub.execute_input":"2025-02-15T02:52:05.922596Z","iopub.status.idle":"2025-02-15T02:52:17.652929Z","shell.execute_reply.started":"2025-02-15T02:52:05.922564Z","shell.execute_reply":"2025-02-15T02:52:17.651673Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:17.65525Z","iopub.execute_input":"2025-02-15T02:52:17.655642Z","iopub.status.idle":"2025-02-15T02:52:17.672298Z","shell.execute_reply.started":"2025-02-15T02:52:17.655606Z","shell.execute_reply":"2025-02-15T02:52:17.671298Z"}},"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-14T12:09:38.097424Z","iopub.execute_input":"2025-02-14T12:09:38.097715Z","iopub.status.idle":"2025-02-14T12:09:38.101421Z","shell.execute_reply.started":"2025-02-14T12:09:38.097693Z","shell.execute_reply":"2025-02-14T12:09:38.100558Z"}},"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\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T12:09:38.102832Z","iopub.execute_input":"2025-02-14T12:09:38.103221Z","iopub.status.idle":"2025-02-14T12:09:38.113506Z","shell.execute_reply.started":"2025-02-14T12:09:38.103186Z","shell.execute_reply":"2025-02-14T12:09:38.112484Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\n# def 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\ndef define_model_1():\n    model = Sequential()\n    \n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.2))\n    \n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.3))\n    \n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(BatchNormalization())\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Dropout(0.4))\n\n    model.add(Flatten())\n    model.add(Dense(256, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dropout(0.5))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    opt = Adam(learning_rate=0.0001)  # ใช้ Adam optimizer แทน SGD\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T12:09:38.114954Z","iopub.execute_input":"2025-02-14T12:09:38.115346Z","iopub.status.idle":"2025-02-14T12:09:38.124809Z","shell.execute_reply.started":"2025-02-14T12:09:38.115311Z","shell.execute_reply":"2025-02-14T12:09:38.123823Z"}},"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-14T12:09:38.126063Z","iopub.execute_input":"2025-02-14T12:09:38.126391Z","iopub.status.idle":"2025-02-14T12:09:38.136543Z","shell.execute_reply.started":"2025-02-14T12:09:38.126364Z","shell.execute_reply":"2025-02-14T12:09:38.135546Z"}},"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-14T12:09:38.137685Z","iopub.execute_input":"2025-02-14T12:09:38.137942Z","iopub.status.idle":"2025-02-14T12:09:38.150037Z","shell.execute_reply.started":"2025-02-14T12:09:38.137919Z","shell.execute_reply":"2025-02-14T12:09:38.149006Z"}},"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-14T12:09:38.151401Z","iopub.execute_input":"2025-02-14T12:09:38.151661Z","iopub.status.idle":"2025-02-14T12:09:39.821168Z","shell.execute_reply.started":"2025-02-14T12:09:38.15164Z","shell.execute_reply":"2025-02-14T12:09:39.820245Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\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    fill_mode='nearest'\n)\n\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-14T12:09:39.822729Z","iopub.execute_input":"2025-02-14T12:09:39.823384Z","iopub.status.idle":"2025-02-14T12:09:40.681526Z","shell.execute_reply.started":"2025-02-14T12:09:39.823334Z","shell.execute_reply":"2025-02-14T12:09:40.680742Z"}},"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-14T12:09:40.682632Z","iopub.execute_input":"2025-02-14T12:09:40.682923Z","iopub.status.idle":"2025-02-14T12:09:40.690067Z","shell.execute_reply.started":"2025-02-14T12:09:40.682899Z","shell.execute_reply":"2025-02-14T12:09:40.689029Z"}},"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-14T12:09:40.691612Z","iopub.execute_input":"2025-02-14T12:09:40.691922Z","iopub.status.idle":"2025-02-14T12:09:40.706347Z","shell.execute_reply.started":"2025-02-14T12:09:40.691896Z","shell.execute_reply":"2025-02-14T12:09:40.705278Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit(\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    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T12:09:40.707558Z","iopub.execute_input":"2025-02-14T12:09:40.707826Z","iopub.status.idle":"2025-02-14T13:34:19.151612Z","shell.execute_reply.started":"2025-02-14T12:09:40.707802Z","shell.execute_reply":"2025-02-14T13:34:19.150529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T13:34:19.152926Z","iopub.execute_input":"2025-02-14T13:34:19.153259Z","iopub.status.idle":"2025-02-14T13:34:19.636374Z","shell.execute_reply.started":"2025-02-14T13:34:19.153234Z","shell.execute_reply":"2025-02-14T13:34:19.635202Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T14:43:01.299708Z","iopub.execute_input":"2025-02-14T14:43:01.300512Z","iopub.status.idle":"2025-02-14T14:44:04.353996Z","shell.execute_reply.started":"2025-02-14T14:43:01.300479Z","shell.execute_reply":"2025-02-14T14:44:04.353195Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\n\ndef predict_and_plot_images(model, test_generator, class_names, num_samples_per_class=5, save=False, output_dir=\"results\"):\n    \"\"\"\n    Randomly selects images from the test set, predicts labels, and plots results.\n\n    Args:\n    - model: Trained model for prediction.\n    - test_generator: Keras ImageDataGenerator for the test set.\n    - class_names (list): List of class names corresponding to label indices.\n    - num_samples_per_class (int): Number of images per class to display.\n    - save (bool): Whether to save the figure.\n    - output_dir (str): Directory to save the figure.\n\n    Returns:\n    - None: Displays the predicted images.\n    \"\"\"\n\n    # Get all filenames and labels from the test generator\n    filepaths = np.array(test_generator.filepaths)\n    labels = np.array(test_generator.classes)  # True class labels\n    \n    selected_images = []\n    selected_labels = []\n    \n    for class_idx in range(len(class_names)):  \n        # Get indices of images belonging to the current class\n        class_indices = np.where(labels == class_idx)[0]\n        if len(class_indices) == 0:\n            continue  # Skip if no images for this class\n\n        # Randomly select `num_samples_per_class` images from this class\n        selected_indices = np.random.choice(class_indices, min(num_samples_per_class, len(class_indices)), replace=False)\n        \n        for idx in selected_indices:\n            selected_images.append(filepaths[idx])\n            selected_labels.append(labels[idx])\n\n    # Load images, resize to 200x200, and preprocess them\n    selected_images_array = np.array([cv2.resize(plt.imread(img), (200, 200)) for img in selected_images])  \n    selected_images_array = selected_images_array / 255.0  # Normalize (as done during training)\n    \n    # Predict using the model\n    predictions = model.predict(selected_images_array)\n    predicted_labels = (predictions > 0.5).astype(\"int\").flatten()  # Convert probabilities to binary labels\n\n    # Plot results\n    fig, axes = plt.subplots(2, 5, figsize=(15, 6))\n    axes = axes.flatten()\n\n    for img, true_label, pred_label, ax in zip(selected_images_array, selected_labels, predicted_labels, axes):\n        ax.imshow(img)\n        ax.set_title(f\"True: {class_names[true_label]}\\nPred: {class_names[pred_label]}\",\n                     fontsize=12, color=\"green\" if true_label == pred_label else \"red\")\n        ax.axis(\"off\")\n\n    plt.tight_layout()\n    plt.show()\n\n    # Save the figure\n    if save:\n        os.makedirs(output_dir, exist_ok=True)\n        plot_path = os.path.join(output_dir, \"test_predictions.png\")\n        fig.savefig(plot_path, dpi=120)\n        print(f\"Saved plot at {plot_path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T14:56:45.903917Z","iopub.execute_input":"2025-02-14T14:56:45.904643Z","iopub.status.idle":"2025-02-14T14:56:46.462028Z","shell.execute_reply.started":"2025-02-14T14:56:45.904608Z","shell.execute_reply":"2025-02-14T14:56:46.461287Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# รายชื่อคลาส (แมว = 0, สุนัข = 1)\nclass_names = [\"Cat\", \"Dog\"]\n\n# เรียกใช้งานฟังก์ชันเพื่อสุ่มทดสอบ\npredict_and_plot_images(model_1, val_it, class_names, num_samples_per_class=5, save=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:08:03.83902Z","iopub.execute_input":"2025-02-14T15:08:03.839428Z","iopub.status.idle":"2025-02-14T15:08:06.128214Z","shell.execute_reply.started":"2025-02-14T15:08:03.83939Z","shell.execute_reply":"2025-02-14T15:08:06.127205Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:27.60476Z","iopub.execute_input":"2025-02-15T02:52:27.605105Z","iopub.status.idle":"2025-02-15T02:52:28.635699Z","shell.execute_reply.started":"2025-02-15T02:52:27.605076Z","shell.execute_reply":"2025-02-15T02:52:28.634631Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:28.637827Z","iopub.execute_input":"2025-02-15T02:52:28.638113Z","iopub.status.idle":"2025-02-15T02:52:28.645764Z","shell.execute_reply.started":"2025-02-15T02:52:28.638088Z","shell.execute_reply":"2025-02-15T02:52:28.644891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:31.457611Z","iopub.execute_input":"2025-02-15T02:52:31.458356Z","iopub.status.idle":"2025-02-15T02:52:31.493924Z","shell.execute_reply.started":"2025-02-15T02:52:31.458307Z","shell.execute_reply":"2025-02-15T02:52:31.493213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:32.308124Z","iopub.execute_input":"2025-02-15T02:52:32.309046Z","iopub.status.idle":"2025-02-15T02:52:32.318376Z","shell.execute_reply.started":"2025-02-15T02:52:32.309014Z","shell.execute_reply":"2025-02-15T02:52:32.317317Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen = ImageDataGenerator(rescale=1./255)\n\n# Create the data generator using the DataFrame\ntest_it = datagen.flow_from_dataframe(\n    dataframe=df,\n    x_col='filename',\n    y_col=None,            # No labels for testing, so set to None\n    target_size=(200, 200),\n    batch_size=64,\n    class_mode=None,       # Since there are no labels\n    shuffle=True       # Usually testing data should not be shuffled\n    # shuffle=false\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:55:53.638325Z","iopub.execute_input":"2025-02-15T02:55:53.639042Z","iopub.status.idle":"2025-02-15T02:55:53.742886Z","shell.execute_reply.started":"2025-02-15T02:55:53.639003Z","shell.execute_reply":"2025-02-15T02:55:53.742177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:55:55.027987Z","iopub.execute_input":"2025-02-15T02:55:55.028788Z","iopub.status.idle":"2025-02-15T02:55:55.138652Z","shell.execute_reply.started":"2025-02-15T02:55:55.028757Z","shell.execute_reply":"2025-02-15T02:55:55.137676Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:55:55.667195Z","iopub.execute_input":"2025-02-15T02:55:55.667858Z","iopub.status.idle":"2025-02-15T02:55:55.672173Z","shell.execute_reply.started":"2025-02-15T02:55:55.667827Z","shell.execute_reply":"2025-02-15T02:55:55.671331Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:55:56.674825Z","iopub.execute_input":"2025-02-15T02:55:56.675538Z","iopub.status.idle":"2025-02-15T02:55:56.679743Z","shell.execute_reply.started":"2025-02-15T02:55:56.675506Z","shell.execute_reply":"2025-02-15T02:55:56.678874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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,"execution":{"iopub.status.busy":"2025-02-15T02:56:01.187993Z","iopub.execute_input":"2025-02-15T02:56:01.188866Z","iopub.status.idle":"2025-02-15T02:56:02.116128Z","shell.execute_reply.started":"2025-02-15T02:56:01.188833Z","shell.execute_reply":"2025-02-15T02:56:02.115381Z"}},"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-15T02:56:02.915841Z","iopub.execute_input":"2025-02-15T02:56:02.916657Z","iopub.status.idle":"2025-02-15T02:56:03.594146Z","shell.execute_reply.started":"2025-02-15T02:56:02.916627Z","shell.execute_reply":"2025-02-15T02:56:03.593397Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:53:02.370746Z","iopub.execute_input":"2025-02-15T02:53:02.371029Z","iopub.status.idle":"2025-02-15T02:53:02.377596Z","shell.execute_reply.started":"2025-02-15T02:53:02.371004Z","shell.execute_reply":"2025-02-15T02:53:02.376718Z"}},"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-15T02:56:05.011176Z","iopub.execute_input":"2025-02-15T02:56:05.012019Z","iopub.status.idle":"2025-02-15T02:56:05.018851Z","shell.execute_reply.started":"2025-02-15T02:56:05.011986Z","shell.execute_reply":"2025-02-15T02:56:05.01797Z"}},"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-15T02:56:07.508777Z","iopub.execute_input":"2025-02-15T02:56:07.509119Z","iopub.status.idle":"2025-02-15T02:56:09.812813Z","shell.execute_reply.started":"2025-02-15T02:56:07.509091Z","shell.execute_reply":"2025-02-15T02:56:09.811596Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:56:51.940959Z","iopub.execute_input":"2025-02-15T02:56:51.941633Z","iopub.status.idle":"2025-02-15T02:56:52.299694Z","shell.execute_reply.started":"2025-02-15T02:56:51.9416Z","shell.execute_reply":"2025-02-15T02:56:52.298807Z"}},"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-15T02:56:54.869177Z","iopub.execute_input":"2025-02-15T02:56:54.870015Z","iopub.status.idle":"2025-02-15T02:56:54.874698Z","shell.execute_reply.started":"2025-02-15T02:56:54.869985Z","shell.execute_reply":"2025-02-15T02:56:54.873753Z"}},"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-15T02:56:56.068451Z","iopub.execute_input":"2025-02-15T02:56:56.069144Z","iopub.status.idle":"2025-02-15T02:56:56.075369Z","shell.execute_reply.started":"2025-02-15T02:56:56.069118Z","shell.execute_reply":"2025-02-15T02:56:56.074417Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:56:57.411868Z","iopub.execute_input":"2025-02-15T02:56:57.412726Z","iopub.status.idle":"2025-02-15T02:56:57.418112Z","shell.execute_reply.started":"2025-02-15T02:56:57.412695Z","shell.execute_reply":"2025-02-15T02:56:57.417269Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:56:58.436652Z","iopub.execute_input":"2025-02-15T02:56:58.437458Z","iopub.status.idle":"2025-02-15T02:56:58.513875Z","shell.execute_reply.started":"2025-02-15T02:56:58.43743Z","shell.execute_reply":"2025-02-15T02:56:58.51309Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:57:01.860699Z","iopub.execute_input":"2025-02-15T02:57:01.861357Z"}},"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-14T14:34:12.568654Z","iopub.status.idle":"2025-02-14T14:34:12.568985Z","shell.execute_reply.started":"2025-02-14T14:34:12.568819Z","shell.execute_reply":"2025-02-14T14:34:12.568834Z"}},"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-15T02:47:01.472389Z","iopub.execute_input":"2025-02-15T02:47:01.473058Z","iopub.status.idle":"2025-02-15T02:47:01.477125Z","shell.execute_reply.started":"2025-02-15T02:47:01.473029Z","shell.execute_reply":"2025-02-15T02:47:01.476359Z"}},"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-15T02:45:28.914281Z","iopub.execute_input":"2025-02-15T02:45:28.914655Z","iopub.status.idle":"2025-02-15T02:45:29.292056Z","shell.execute_reply.started":"2025-02-15T02:45:28.914627Z","shell.execute_reply":"2025-02-15T02:45:29.290846Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\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,"execution":{"iopub.status.busy":"2025-02-15T02:39:32.928772Z","iopub.execute_input":"2025-02-15T02:39:32.92914Z","iopub.status.idle":"2025-02-15T02:39:32.934018Z","shell.execute_reply.started":"2025-02-15T02:39:32.929113Z","shell.execute_reply":"2025-02-15T02:39:32.933151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_2():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\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-15T02:39:34.81485Z","iopub.execute_input":"2025-02-15T02:39:34.815659Z","iopub.status.idle":"2025-02-15T02:39:34.820853Z","shell.execute_reply.started":"2025-02-15T02:39:34.815628Z","shell.execute_reply":"2025-02-15T02:39:34.820152Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history2):\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-15T02:39:35.919825Z","iopub.execute_input":"2025-02-15T02:39:35.920114Z","iopub.status.idle":"2025-02-15T02:39:35.925582Z","shell.execute_reply.started":"2025-02-15T02:39:35.920091Z","shell.execute_reply":"2025-02-15T02:39:35.924736Z"}},"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_2()\n\t# create data generator\n\tdatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\t# fit model\n\thistory2 = model2.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1 ,callbacks = [PlotLossesKeras()])\n\t# evaluate model\n\t_, acc = model2.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-14T16:02:29.256886Z","iopub.status.idle":"2025-02-14T16:02:29.25727Z","shell.execute_reply.started":"2025-02-14T16:02:29.257038Z","shell.execute_reply":"2025-02-14T16:02:29.257059Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_2 = define_model_2()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:39:38.383811Z","iopub.execute_input":"2025-02-15T02:39:38.384478Z","iopub.status.idle":"2025-02-15T02:39:38.739531Z","shell.execute_reply.started":"2025-02-15T02:39:38.384449Z","shell.execute_reply":"2025-02-15T02:39:38.738814Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(featurewise_center=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:39:39.246707Z","iopub.execute_input":"2025-02-15T02:39:39.247239Z","iopub.status.idle":"2025-02-15T02:39:39.251024Z","shell.execute_reply.started":"2025-02-15T02:39:39.247213Z","shell.execute_reply":"2025-02-15T02:39:39.250166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen.mean = [123.68, 116.779, 103.939]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:39:39.98337Z","iopub.execute_input":"2025-02-15T02:39:39.984119Z","iopub.status.idle":"2025-02-15T02:39:39.988384Z","shell.execute_reply.started":"2025-02-15T02:39:39.984091Z","shell.execute_reply":"2025-02-15T02:39:39.987523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:47:09.203493Z","iopub.execute_input":"2025-02-15T02:47:09.204108Z","iopub.status.idle":"2025-02-15T02:47:09.249721Z","shell.execute_reply.started":"2025-02-15T02:47:09.204081Z","shell.execute_reply":"2025-02-15T02:47:09.248643Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\n\thistory2 = model2.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=10, verbose=1 ,callbacks = [PlotLossesKeras()])","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\t_, acc = model2.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}