{"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"},{"sourceId":10773418,"sourceType":"datasetVersion","datasetId":6683865}],"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-19T11:49:12.101620Z","iopub.execute_input":"2025-02-19T11:49:12.102644Z","iopub.status.idle":"2025-02-19T11:49:12.110625Z","shell.execute_reply.started":"2025-02-19T11:49:12.102604Z","shell.execute_reply":"2025-02-19T11:49:12.109829Z"}},"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-19T11:49:12.111966Z","iopub.execute_input":"2025-02-19T11:49:12.112177Z","iopub.status.idle":"2025-02-19T11:49:21.430464Z","shell.execute_reply.started":"2025-02-19T11:49:12.112158Z","shell.execute_reply":"2025-02-19T11:49:21.429468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:21.431696Z","iopub.execute_input":"2025-02-19T11:49:21.431967Z","iopub.status.idle":"2025-02-19T11:49:21.437233Z","shell.execute_reply.started":"2025-02-19T11:49:21.431945Z","shell.execute_reply":"2025-02-19T11:49:21.436353Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:21.438864Z","iopub.execute_input":"2025-02-19T11:49:21.439102Z","iopub.status.idle":"2025-02-19T11:49:22.350870Z","shell.execute_reply.started":"2025-02-19T11:49:21.439082Z","shell.execute_reply":"2025-02-19T11:49:22.349988Z"}},"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-19T11:49:22.352136Z","iopub.execute_input":"2025-02-19T11:49:22.352492Z","iopub.status.idle":"2025-02-19T11:49:23.211634Z","shell.execute_reply.started":"2025-02-19T11:49:22.352458Z","shell.execute_reply":"2025-02-19T11:49:23.210807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pip install --upgrade 'numpy<1.23.0'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:23.212998Z","iopub.execute_input":"2025-02-19T11:49:23.213368Z","iopub.status.idle":"2025-02-19T11:49:32.107875Z","shell.execute_reply.started":"2025-02-19T11:49:23.213334Z","shell.execute_reply":"2025-02-19T11:49:32.106710Z"}},"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-19T11:49:32.109358Z","iopub.execute_input":"2025-02-19T11:49:32.109686Z","iopub.status.idle":"2025-02-19T11:49:32.114744Z","shell.execute_reply.started":"2025-02-19T11:49:32.109658Z","shell.execute_reply":"2025-02-19T11:49:32.113823Z"}},"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 structurea\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-19T11:49:32.115843Z","iopub.execute_input":"2025-02-19T11:49:32.116077Z","iopub.status.idle":"2025-02-19T11:49:32.126636Z","shell.execute_reply.started":"2025-02-19T11:49:32.116056Z","shell.execute_reply":"2025-02-19T11:49:32.125977Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:32.129593Z","iopub.execute_input":"2025-02-19T11:49:32.129905Z","iopub.status.idle":"2025-02-19T11:49:32.137633Z","shell.execute_reply.started":"2025-02-19T11:49:32.129870Z","shell.execute_reply":"2025-02-19T11:49:32.136954Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:32.138584Z","iopub.execute_input":"2025-02-19T11:49:32.138883Z","iopub.status.idle":"2025-02-19T11:49:35.423996Z","shell.execute_reply.started":"2025-02-19T11:49:32.138856Z","shell.execute_reply":"2025-02-19T11:49:35.423239Z"}},"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-19T11:49:35.425329Z","iopub.execute_input":"2025-02-19T11:49:35.426009Z","iopub.status.idle":"2025-02-19T11:49:36.592446Z","shell.execute_reply.started":"2025-02-19T11:49:35.425970Z","shell.execute_reply":"2025-02-19T11:49:36.591364Z"}},"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-19T11:49:36.594106Z","iopub.execute_input":"2025-02-19T11:49:36.594410Z","iopub.status.idle":"2025-02-19T11:49:37.756925Z","shell.execute_reply.started":"2025-02-19T11:49:36.594383Z","shell.execute_reply":"2025-02-19T11:49:37.755894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:37.758567Z","iopub.execute_input":"2025-02-19T11:49:37.758864Z","iopub.status.idle":"2025-02-19T11:49:46.076831Z","shell.execute_reply.started":"2025-02-19T11:49:37.758837Z","shell.execute_reply":"2025-02-19T11:49:46.075878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:46.078453Z","iopub.execute_input":"2025-02-19T11:49:46.078804Z","iopub.status.idle":"2025-02-19T11:49:46.083387Z","shell.execute_reply.started":"2025-02-19T11:49:46.078775Z","shell.execute_reply":"2025-02-19T11:49:46.082589Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.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-19T11:49:46.084824Z","iopub.execute_input":"2025-02-19T11:49:46.085166Z","iopub.status.idle":"2025-02-19T11:49:46.096338Z","shell.execute_reply.started":"2025-02-19T11:49:46.085136Z","shell.execute_reply":"2025-02-19T11:49:46.095404Z"}},"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":"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:46.097396Z","iopub.execute_input":"2025-02-19T11:49:46.097684Z","iopub.status.idle":"2025-02-19T11:49:47.072789Z","shell.execute_reply.started":"2025-02-19T11:49:46.097650Z","shell.execute_reply":"2025-02-19T11:49:47.072080Z"}},"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":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:47.073795Z","iopub.execute_input":"2025-02-19T11:49:47.074061Z","iopub.status.idle":"2025-02-19T11:49:47.445868Z","shell.execute_reply.started":"2025-02-19T11:49:47.074038Z","shell.execute_reply":"2025-02-19T11:49:47.444984Z"}},"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-19T11:49:47.446938Z","iopub.execute_input":"2025-02-19T11:49:47.447203Z","iopub.status.idle":"2025-02-19T11:49:47.453785Z","shell.execute_reply.started":"2025-02-19T11:49:47.447180Z","shell.execute_reply":"2025-02-19T11:49:47.452945Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:47.454866Z","iopub.execute_input":"2025-02-19T11:49:47.455160Z","iopub.status.idle":"2025-02-19T11:49:47.465746Z","shell.execute_reply.started":"2025-02-19T11:49:47.455131Z","shell.execute_reply":"2025-02-19T11:49:47.464941Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:47.466710Z","iopub.execute_input":"2025-02-19T11:49:47.466990Z","iopub.status.idle":"2025-02-19T11:49:47.502130Z","shell.execute_reply.started":"2025-02-19T11:49:47.466964Z","shell.execute_reply":"2025-02-19T11:49:47.501565Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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,"scrolled":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:47.502930Z","iopub.execute_input":"2025-02-19T11:49:47.503130Z","iopub.status.idle":"2025-02-19T11:49:47.557791Z","shell.execute_reply.started":"2025-02-19T11:49:47.503112Z","shell.execute_reply":"2025-02-19T11:49:47.556980Z"}},"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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T11:49:47.558808Z","iopub.execute_input":"2025-02-19T11:49:47.559117Z","iopub.status.idle":"2025-02-19T12:57:48.623478Z","shell.execute_reply.started":"2025-02-19T11:49:47.559087Z","shell.execute_reply":"2025-02-19T12:57:48.622759Z"}},"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-19T12:57:48.624591Z","iopub.execute_input":"2025-02-19T12:57:48.624855Z","iopub.status.idle":"2025-02-19T12:59:55.369077Z","shell.execute_reply.started":"2025-02-19T12:57:48.624832Z","shell.execute_reply":"2025-02-19T12:59:55.368269Z"}},"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    pyplot.tight_layout()\n    pyplot.show()\n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.373979Z","iopub.execute_input":"2025-02-19T12:59:55.374541Z","iopub.status.idle":"2025-02-19T12:59:55.380188Z","shell.execute_reply.started":"2025-02-19T12:59:55.374501Z","shell.execute_reply":"2025-02-19T12:59:55.379270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.381156Z","iopub.execute_input":"2025-02-19T12:59:55.381425Z","iopub.status.idle":"2025-02-19T12:59:55.708957Z","shell.execute_reply.started":"2025-02-19T12:59:55.381405Z","shell.execute_reply":"2025-02-19T12:59:55.708084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# best_model = 'vgg16_model.hdf5'\n# my_model.save(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.709888Z","iopub.execute_input":"2025-02-19T12:59:55.710118Z","iopub.status.idle":"2025-02-19T12:59:55.713827Z","shell.execute_reply.started":"2025-02-19T12:59:55.710097Z","shell.execute_reply":"2025-02-19T12:59:55.712958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# best_model = load_model(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.714745Z","iopub.execute_input":"2025-02-19T12:59:55.715007Z","iopub.status.idle":"2025-02-19T12:59:55.724489Z","shell.execute_reply.started":"2025-02-19T12:59:55.714975Z","shell.execute_reply":"2025-02-19T12:59:55.723651Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# best_model.evaluate(test_it, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.725443Z","iopub.execute_input":"2025-02-19T12:59:55.725689Z","iopub.status.idle":"2025-02-19T12:59:55.734303Z","shell.execute_reply.started":"2025-02-19T12:59:55.725669Z","shell.execute_reply":"2025-02-19T12:59:55.733708Z"}},"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-19T12:59:55.735377Z","iopub.execute_input":"2025-02-19T12:59:55.735626Z","iopub.status.idle":"2025-02-19T12:59:55.745334Z","shell.execute_reply.started":"2025-02-19T12:59:55.735605Z","shell.execute_reply":"2025-02-19T12:59:55.744704Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.746224Z","iopub.execute_input":"2025-02-19T12:59:55.746436Z","iopub.status.idle":"2025-02-19T12:59:55.754788Z","shell.execute_reply.started":"2025-02-19T12:59:55.746405Z","shell.execute_reply":"2025-02-19T12:59:55.754008Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.755794Z","iopub.execute_input":"2025-02-19T12:59:55.756096Z","iopub.status.idle":"2025-02-19T12:59:55.766628Z","shell.execute_reply.started":"2025-02-19T12:59:55.756068Z","shell.execute_reply":"2025-02-19T12:59:55.765791Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"load_image(filename)","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.767604Z","iopub.execute_input":"2025-02-19T12:59:55.767810Z","iopub.status.idle":"2025-02-19T12:59:55.781988Z","shell.execute_reply.started":"2025-02-19T12:59:55.767791Z","shell.execute_reply":"2025-02-19T12:59:55.781139Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.preprocessing import image\nimport requests\nfrom io import BytesIO\n\nurl = 'https://machinelearningmastery.com/wp-content/uploads/2019/03/sample_image.jpg'\nresponse = requests.get(url)\nimg = image.load_img(BytesIO(response.content), target_size=(224, 224))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.782990Z","iopub.execute_input":"2025-02-19T12:59:55.783306Z","iopub.status.idle":"2025-02-19T12:59:55.951842Z","shell.execute_reply.started":"2025-02-19T12:59:55.783277Z","shell.execute_reply":"2025-02-19T12:59:55.951194Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.getcwd())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.952812Z","iopub.execute_input":"2025-02-19T12:59:55.953116Z","iopub.status.idle":"2025-02-19T12:59:55.958018Z","shell.execute_reply.started":"2025-02-19T12:59:55.953087Z","shell.execute_reply":"2025-02-19T12:59:55.957151Z"}},"outputs":[],"execution_count":null},{"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-19T12:59:55.959107Z","iopub.execute_input":"2025-02-19T12:59:55.959414Z","iopub.status.idle":"2025-02-19T12:59:55.967289Z","shell.execute_reply.started":"2025-02-19T12:59:55.959385Z","shell.execute_reply":"2025-02-19T12:59:55.966482Z"}},"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-19T12:59:55.968191Z","iopub.execute_input":"2025-02-19T12:59:55.968429Z","iopub.status.idle":"2025-02-19T12:59:55.978277Z","shell.execute_reply.started":"2025-02-19T12:59:55.968409Z","shell.execute_reply":"2025-02-19T12:59:55.977465Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:55.979120Z","iopub.execute_input":"2025-02-19T12:59:55.979361Z","iopub.status.idle":"2025-02-19T12:59:57.052014Z","shell.execute_reply.started":"2025-02-19T12:59:55.979339Z","shell.execute_reply":"2025-02-19T12:59:57.051087Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T12:59:57.053445Z","iopub.execute_input":"2025-02-19T12:59:57.053750Z","iopub.status.idle":"2025-02-19T12:59:58.126333Z","shell.execute_reply.started":"2025-02-19T12:59:57.053724Z","shell.execute_reply":"2025-02-19T12:59:58.125391Z"}},"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-19T12:59:58.128056Z","iopub.execute_input":"2025-02-19T12:59:58.128789Z","iopub.status.idle":"2025-02-19T13:00:01.138994Z","shell.execute_reply.started":"2025-02-19T12:59:58.128746Z","shell.execute_reply":"2025-02-19T13:00:01.137980Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.models import load_model\n\n# ฟังก์ชันสำหรับการสุ่มรูป\ndef random_image_from_folder(folder, num_images=5):\n    # สุ่มไฟล์จากโฟลเดอร์ที่ระบุ\n    image_files = random.sample(os.listdir(folder), num_images)\n    images = []\n    for file in image_files:\n        img_path = os.path.join(folder, file)\n        img = image.load_img(img_path, target_size=(224, 224))  # Resize ภาพให้ขนาดที่ต้องการ\n        img_array = image.img_to_array(img)\n        img_array = np.expand_dims(img_array, axis=0)  # เพิ่มมิติ\n        images.append((img_array, file, img))  # เก็บทั้งภาพและชื่อไฟล์\n    return images\n\n# ฟังก์ชันทำนายรูป\ndef predict_image(model, img_array):\n    prediction = model.predict(img_array)\n    return \"Dog\" if prediction[0] > 0.5 else \"Cat\"\n\n# ฟังก์ชันสำหรับแสดงรูปพร้อมผลการทำนายและเฉลย\ndef plot_images_with_predictions(model, folder_dog, folder_cat, num_images=5):\n    # สุ่มภาพหมาและแมว\n    dog_images = random_image_from_folder(folder_dog, num_images)\n    cat_images = random_image_from_folder(folder_cat, num_images)\n\n    # สร้างกราฟ\n    plt.figure(figsize=(12, 6))  # กำหนดขนาดของกราฟ\n\n    # แสดงผลการทำนายหมา (แถวแรก)\n    for i, (img_array, img_name, img) in enumerate(dog_images):\n        plt.subplot(2, 5, i + 1)  # การจัดรูปภาพในแถวแรก\n        plt.imshow(img)  # ใช้ภาพเดิมที่ไม่ผ่านการ preprocess\n        predicted_label = predict_image(model, img_array)\n        true_label = \"Dog\"  # เนื่องจากเป็นภาพหมา\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: {true_label}\")\n        plt.axis('off')\n\n    # แสดงผลการทำนายแมว (แถวที่สอง)\n    for i, (img_array, img_name, img) in enumerate(cat_images):\n        plt.subplot(2, 5, i + 6)  # การจัดรูปภาพในแถวที่สอง\n        plt.imshow(img)  # ใช้ภาพเดิมที่ไม่ผ่านการ preprocess\n        predicted_label = predict_image(model, img_array)\n        true_label = \"Cat\"  # เนื่องจากเป็นภาพแมว\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: {true_label}\")\n        plt.axis('off')\n\n    plt.tight_layout()  # ทำให้กราฟไม่เบียดกัน\n    plt.show()\n\n# ใช้โมเดลที่คุณฝึกไว้\n# สมมุติว่าโมเดลถูกฝึกและบันทึกแล้ว\n# เปลี่ยนให้โมเดลเป็นโมเดลที่คุณใช้\nmodel = my_model  # หรือโมเดลของคุณที่ฝึกมา\n\n# โฟลเดอร์สำหรับหมาและแมว\nfolder_dog = 'dataset_dogs_vs_cats/test/dogs'\nfolder_cat = 'dataset_dogs_vs_cats/test/cats'\n\n# เรียกใช้ฟังก์ชันในการแสดงผล\nplot_images_with_predictions(model, folder_dog, folder_cat)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:01.140651Z","iopub.execute_input":"2025-02-19T13:00:01.140921Z","iopub.status.idle":"2025-02-19T13:00:02.908949Z","shell.execute_reply.started":"2025-02-19T13:00:01.140898Z","shell.execute_reply":"2025-02-19T13:00:02.907915Z"}},"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'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:02.910194Z","iopub.execute_input":"2025-02-19T13:00:02.910850Z","iopub.status.idle":"2025-02-19T13:00:02.946697Z","shell.execute_reply.started":"2025-02-19T13:00:02.910817Z","shell.execute_reply":"2025-02-19T13:00:02.946094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (299, 299)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0,\n                            horizontal_flip=True,)\n\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen_test = ImageDataGenerator(rescale=1./255,\n                                 horizontal_flip=True)\n\n# Create the data generator using the DataFrame\ntest_it = datagen_test.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=IMAGE_SIZE,\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:02.947585Z","iopub.execute_input":"2025-02-19T13:00:02.947803Z","iopub.status.idle":"2025-02-19T13:00:04.007831Z","shell.execute_reply.started":"2025-02-19T13:00:02.947785Z","shell.execute_reply":"2025-02-19T13:00:04.007090Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## InceptionV3","metadata":{}},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\nfrom keras.layers import Flatten, Dense, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    drop1 = Dropout(0.5)(class1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(drop1)\n    drop2 = Dropout(0.5)(class2)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(drop2)\n    drop3 = Dropout(0.5)(class3)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(drop3)\n    drop4 = Dropout(0.5)(class4)\n    \n    output = Dense(1, activation='sigmoid')(drop4)  # ใช้ drop4 แทน class4\n\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)  # เปลี่ยน lr เป็น learning_rate\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:04.008877Z","iopub.execute_input":"2025-02-19T13:00:04.009132Z","iopub.status.idle":"2025-02-19T13:00:04.018262Z","shell.execute_reply.started":"2025-02-19T13:00:04.009109Z","shell.execute_reply":"2025-02-19T13:00:04.017418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_exmaple(images):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        if i < test_images.shape[0]:\n            ax.imshow(test_images[i])\n        ax.axis('off')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:04.019400Z","iopub.execute_input":"2025-02-19T13:00:04.019659Z","iopub.status.idle":"2025-02-19T13:00:04.037482Z","shell.execute_reply.started":"2025-02-19T13:00:04.019638Z","shell.execute_reply":"2025-02-19T13:00:04.036579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:04.038679Z","iopub.execute_input":"2025-02-19T13:00:04.039000Z","iopub.status.idle":"2025-02-19T13:00:06.293792Z","shell.execute_reply.started":"2025-02-19T13:00:04.038971Z","shell.execute_reply":"2025-02-19T13:00:06.293091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3.summary()","metadata":{"trusted":true,"_kg_hide-output":true,"scrolled":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:06.294738Z","iopub.execute_input":"2025-02-19T13:00:06.294967Z","iopub.status.idle":"2025-02-19T13:00:06.975269Z","shell.execute_reply.started":"2025-02-19T13:00:06.294947Z","shell.execute_reply":"2025-02-19T13:00:06.974389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:06.976300Z","iopub.execute_input":"2025-02-19T13:00:06.976581Z","iopub.status.idle":"2025-02-19T13:00:06.990544Z","shell.execute_reply.started":"2025-02-19T13:00:06.976554Z","shell.execute_reply":"2025-02-19T13:00:06.989442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_inceptionv3.reset_states()\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    callbacks = [PlotLossesKeras()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:00:06.991510Z","iopub.execute_input":"2025-02-19T13:00:06.991774Z","iopub.status.idle":"2025-02-19T13:28:57.784676Z","shell.execute_reply.started":"2025-02-19T13:00:06.991753Z","shell.execute_reply":"2025-02-19T13:28:57.783923Z"}},"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}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:28:57.785996Z","iopub.execute_input":"2025-02-19T13:28:57.786281Z","iopub.status.idle":"2025-02-19T13:28:57.793362Z","shell.execute_reply.started":"2025-02-19T13:28:57.786258Z","shell.execute_reply":"2025-02-19T13:28:57.792575Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:28:57.794498Z","iopub.execute_input":"2025-02-19T13:28:57.794780Z","iopub.status.idle":"2025-02-19T13:29:51.857678Z","shell.execute_reply.started":"2025-02-19T13:28:57.794759Z","shell.execute_reply":"2025-02-19T13:29:51.856867Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:51.858860Z","iopub.execute_input":"2025-02-19T13:29:51.859202Z","iopub.status.idle":"2025-02-19T13:29:51.865386Z","shell.execute_reply.started":"2025-02-19T13:29:51.859171Z","shell.execute_reply":"2025-02-19T13:29:51.864458Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"next(iter(test_it))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:51.866829Z","iopub.execute_input":"2025-02-19T13:29:51.867611Z","iopub.status.idle":"2025-02-19T13:29:52.048699Z","shell.execute_reply.started":"2025-02-19T13:29:51.867573Z","shell.execute_reply":"2025-02-19T13:29:52.047611Z"},"scrolled":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_inceptionv3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:52.049992Z","iopub.execute_input":"2025-02-19T13:29:52.050703Z","iopub.status.idle":"2025-02-19T13:29:52.478431Z","shell.execute_reply.started":"2025-02-19T13:29:52.050660Z","shell.execute_reply":"2025-02-19T13:29:52.477403Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom keras.applications.inception_v3 import preprocess_input  # ใช้ preprocess ของ InceptionV3\nfrom keras.models import load_model\n\n# ฟังก์ชันสำหรับการสุ่มรูป\ndef random_image_from_folder(folder, num_images=5):\n    image_files = random.sample(os.listdir(folder), num_images)\n    images = []\n    for file in image_files:\n        img_path = os.path.join(folder, file)\n        img = image.load_img(img_path, target_size=(299, 299))  # ใช้ 299x299\n        img_array = image.img_to_array(img)\n        img_array = np.expand_dims(img_array, axis=0)  # เพิ่มมิติ\n        img_array = preprocess_input(img_array)  # 🔹 ใช้ preprocess_input\n        images.append((img_array, file, img))\n    return images\n\n# ฟังก์ชันทำนายรูป\ndef predict_image(model, img_array):\n    prediction = model.predict(img_array, batch_size=1)[0][0]  # 🔹 กำหนด batch_size=1\n    print(f\"Confidence Score: {prediction:.4f}\")  # 🔹 เพิ่มการพิมพ์ค่า Score\n    return \"Dog\" if prediction > 0.5 else \"Cat\"  # 🔹 ปรับ Threshold กลับไป 0.5\n\n# ฟังก์ชันสำหรับแสดงรูปพร้อมผลการทำนายและเฉลย\ndef plot_images_with_predictions(model, folder_dog, folder_cat, num_images=5):\n    dog_images = random_image_from_folder(folder_dog, num_images)\n    cat_images = random_image_from_folder(folder_cat, num_images)\n\n    plt.figure(figsize=(12, 6))\n\n    for i, (img_array, img_name, img) in enumerate(dog_images):\n        plt.subplot(2, 5, i + 1)\n        plt.imshow(img)\n        predicted_label = predict_image(model, img_array)\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: Dog\")\n        plt.axis('off')\n\n    for i, (img_array, img_name, img) in enumerate(cat_images):\n        plt.subplot(2, 5, i + 6)\n        plt.imshow(img)\n        predicted_label = predict_image(model, img_array)\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: Cat\")\n        plt.axis('off')\n\n    plt.tight_layout()\n    plt.show()\n\n# โหลดโมเดลที่ฝึกไว้\nmodel = model_inceptionv3  # แทนด้วยโมเดลที่คุณฝึก\n\n# โฟลเดอร์สำหรับหมาและแมว\nfolder_dog = 'dataset_dogs_vs_cats/test/dogs'\nfolder_cat = 'dataset_dogs_vs_cats/test/cats'\n\n# เรียกใช้ฟังก์ชันในการแสดงผล\nplot_images_with_predictions(model, folder_dog, folder_cat)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:52.479816Z","iopub.execute_input":"2025-02-19T13:29:52.480499Z","iopub.status.idle":"2025-02-19T13:29:56.190412Z","shell.execute_reply.started":"2025-02-19T13:29:52.480462Z","shell.execute_reply":"2025-02-19T13:29:56.189547Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Training set:\")\nprint(train_it.class_indices)\nprint(train_it.samples)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:56.191647Z","iopub.execute_input":"2025-02-19T13:29:56.191917Z","iopub.status.idle":"2025-02-19T13:29:56.196477Z","shell.execute_reply.started":"2025-02-19T13:29:56.191894Z","shell.execute_reply":"2025-02-19T13:29:56.195643Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.utils.class_weight import compute_class_weight\nimport numpy as np\n\nclass_weights = compute_class_weight('balanced', classes=np.array([0, 1]), y=train_it.classes)\nclass_weight_dict = {i: class_weights[i] for i in range(len(class_weights))}\n\nmodel_inceptionv3.fit(train_it, epochs=10, class_weight=class_weight_dict)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T13:29:56.197702Z","iopub.execute_input":"2025-02-19T13:29:56.197977Z","iopub.status.idle":"2025-02-19T13:49:49.588611Z","shell.execute_reply.started":"2025-02-19T13:29:56.197955Z","shell.execute_reply":"2025-02-19T13:49:49.587801Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## resnet_model","metadata":{}},{"cell_type":"code","source":"from keras.layers import GlobalAveragePooling2D\n\ndef create_model(base_model, input_shape=(224, 224, 3), num_classes=1):\n    base_model = base_model(include_top=False, input_shape=input_shape, weights='imagenet')\n\n    for layer in base_model.layers:\n        layer.trainable = False\n\n    # x = GlobalAveragePooling2D()(base_model.output)\n    # x = Dense(512, activation='relu')(x)\n    # x = Dropout(0.5)(x)\n    # x = Dense(256, activation='relu')(x)\n    # x = Dropout(0.5)(x)\n\n    flat1 = GlobalAveragePooling2D()(base_model.output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    drop1 = Dropout(0.5)(class1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(drop1)\n    drop2 = Dropout(0.5)(class2)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(drop2)\n    drop3 = Dropout(0.5)(class3)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(drop3)\n    drop4 = Dropout(0.5)(class4)\n    output = Dense(num_classes, activation='sigmoid' if num_classes == 1 else 'softmax')(drop4)\n\n    return model\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:02:41.458598Z","iopub.execute_input":"2025-02-19T14:02:41.458994Z","iopub.status.idle":"2025-02-19T14:02:41.466570Z","shell.execute_reply.started":"2025-02-19T14:02:41.458965Z","shell.execute_reply":"2025-02-19T14:02:41.465495Z"},"scrolled":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nresnet_model = create_model(ResNet50, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:02:45.193631Z","iopub.execute_input":"2025-02-19T14:02:45.193971Z","iopub.status.idle":"2025-02-19T14:02:46.795283Z","shell.execute_reply.started":"2025-02-19T14:02:45.193945Z","shell.execute_reply":"2025-02-19T14:02:46.794588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:02:49.793897Z","iopub.execute_input":"2025-02-19T14:02:49.794210Z","iopub.status.idle":"2025-02-19T14:02:49.809645Z","shell.execute_reply.started":"2025-02-19T14:02:49.794187Z","shell.execute_reply":"2025-02-19T14:02:49.808862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nresnet_model.reset_states()\nhistory_resnet_model = resnet_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    callbacks = [PlotLossesKeras()])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:02:49.966972Z","iopub.execute_input":"2025-02-19T14:02:49.967736Z","iopub.status.idle":"2025-02-19T14:32:10.057057Z","shell.execute_reply.started":"2025-02-19T14:02:49.967710Z","shell.execute_reply":"2025-02-19T14:32:10.056285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = resnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:32:10.061302Z","iopub.execute_input":"2025-02-19T14:32:10.061631Z","iopub.status.idle":"2025-02-19T14:33:04.193691Z","shell.execute_reply.started":"2025-02-19T14:32:10.061605Z","shell.execute_reply":"2025-02-19T14:33:04.192811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_inceptionv3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:04.194724Z","iopub.execute_input":"2025-02-19T14:33:04.195000Z","iopub.status.idle":"2025-02-19T14:33:04.525701Z","shell.execute_reply.started":"2025-02-19T14:33:04.194975Z","shell.execute_reply":"2025-02-19T14:33:04.524764Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(resnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:04.527662Z","iopub.execute_input":"2025-02-19T14:33:04.527949Z","iopub.status.idle":"2025-02-19T14:33:07.326835Z","shell.execute_reply.started":"2025-02-19T14:33:04.527924Z","shell.execute_reply":"2025-02-19T14:33:07.325920Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## MobileNetV2","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\nmobilenet_model = create_model(MobileNetV2, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:07.327958Z","iopub.execute_input":"2025-02-19T14:33:07.328199Z","iopub.status.idle":"2025-02-19T14:33:08.571900Z","shell.execute_reply.started":"2025-02-19T14:33:07.328179Z","shell.execute_reply":"2025-02-19T14:33:08.571148Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:08.572960Z","iopub.execute_input":"2025-02-19T14:33:08.573243Z","iopub.status.idle":"2025-02-19T14:33:08.590055Z","shell.execute_reply.started":"2025-02-19T14:33:08.573219Z","shell.execute_reply":"2025-02-19T14:33:08.589142Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"mobilenet_model.summary()","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:08.591180Z","iopub.execute_input":"2025-02-19T14:33:08.591431Z","iopub.status.idle":"2025-02-19T14:33:09.294079Z","shell.execute_reply.started":"2025-02-19T14:33:08.591398Z","shell.execute_reply":"2025-02-19T14:33:09.293189Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nresnet_model.reset_states()\nhistory_mobilenet_model = mobilenet_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    callbacks = [PlotLossesKeras()])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T14:33:09.295174Z","iopub.execute_input":"2025-02-19T14:33:09.295438Z","iopub.status.idle":"2025-02-19T15:02:25.455656Z","shell.execute_reply.started":"2025-02-19T14:33:09.295415Z","shell.execute_reply":"2025-02-19T15:02:25.454933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = mobilenet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:02:25.456826Z","iopub.execute_input":"2025-02-19T15:02:25.457076Z","iopub.status.idle":"2025-02-19T15:03:19.248030Z","shell.execute_reply.started":"2025-02-19T15:02:25.457054Z","shell.execute_reply":"2025-02-19T15:03:19.247305Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_mobilenet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:03:19.251554Z","iopub.execute_input":"2025-02-19T15:03:19.251803Z","iopub.status.idle":"2025-02-19T15:03:19.669172Z","shell.execute_reply.started":"2025-02-19T15:03:19.251782Z","shell.execute_reply":"2025-02-19T15:03:19.668212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(mobilenet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:03:19.670064Z","iopub.execute_input":"2025-02-19T15:03:19.670296Z","iopub.status.idle":"2025-02-19T15:03:22.605158Z","shell.execute_reply.started":"2025-02-19T15:03:19.670275Z","shell.execute_reply":"2025-02-19T15:03:22.604227Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## EfficientNetB0","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import EfficientNetB0\nefficientnet_model = create_model(EfficientNetB0, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:03:22.606493Z","iopub.execute_input":"2025-02-19T15:03:22.606861Z","iopub.status.idle":"2025-02-19T15:03:24.473744Z","shell.execute_reply.started":"2025-02-19T15:03:22.606830Z","shell.execute_reply":"2025-02-19T15:03:24.472787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:03:24.474958Z","iopub.execute_input":"2025-02-19T15:03:24.475466Z","iopub.status.idle":"2025-02-19T15:03:24.491805Z","shell.execute_reply.started":"2025-02-19T15:03:24.475431Z","shell.execute_reply":"2025-02-19T15:03:24.491134Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nefficientnet_model.reset_states()\nhistory_efficientnet_model = efficientnet_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    callbacks = [PlotLossesKeras()])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:03:24.493076Z","iopub.execute_input":"2025-02-19T15:03:24.493423Z","iopub.status.idle":"2025-02-19T15:32:38.132275Z","shell.execute_reply.started":"2025-02-19T15:03:24.493392Z","shell.execute_reply":"2025-02-19T15:32:38.131573Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = efficientnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:32:38.133417Z","iopub.execute_input":"2025-02-19T15:32:38.133682Z","iopub.status.idle":"2025-02-19T15:33:31.966703Z","shell.execute_reply.started":"2025-02-19T15:32:38.133660Z","shell.execute_reply":"2025-02-19T15:33:31.965868Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_efficientnet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:33:31.967770Z","iopub.execute_input":"2025-02-19T15:33:31.968035Z","iopub.status.idle":"2025-02-19T15:33:32.405142Z","shell.execute_reply.started":"2025-02-19T15:33:31.968013Z","shell.execute_reply":"2025-02-19T15:33:32.404280Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(efficientnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:33:32.406125Z","iopub.execute_input":"2025-02-19T15:33:32.406379Z","iopub.status.idle":"2025-02-19T15:33:35.391724Z","shell.execute_reply.started":"2025-02-19T15:33:32.406356Z","shell.execute_reply":"2025-02-19T15:33:35.390688Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## NASNetMobile","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import NASNetMobile\nnasnet_model = create_model(NASNetMobile, input_shape=(224, 224, 3))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:33:35.393069Z","iopub.execute_input":"2025-02-19T15:33:35.393735Z","iopub.status.idle":"2025-02-19T15:33:41.004598Z","shell.execute_reply.started":"2025-02-19T15:33:35.393702Z","shell.execute_reply":"2025-02-19T15:33:41.003724Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:33:41.005748Z","iopub.execute_input":"2025-02-19T15:33:41.006038Z","iopub.status.idle":"2025-02-19T15:33:41.022225Z","shell.execute_reply.started":"2025-02-19T15:33:41.006012Z","shell.execute_reply":"2025-02-19T15:33:41.021452Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nnasnet_model.reset_states()\nhistory_nasnet_model = nasnet_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    callbacks = [PlotLossesKeras()])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T15:33:41.023326Z","iopub.execute_input":"2025-02-19T15:33:41.023617Z","iopub.status.idle":"2025-02-19T16:02:57.200282Z","shell.execute_reply.started":"2025-02-19T15:33:41.023594Z","shell.execute_reply":"2025-02-19T16:02:57.199578Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = nasnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:02:57.201433Z","iopub.execute_input":"2025-02-19T16:02:57.202011Z","iopub.status.idle":"2025-02-19T16:03:51.566825Z","shell.execute_reply.started":"2025-02-19T16:02:57.201984Z","shell.execute_reply":"2025-02-19T16:03:51.565977Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_nasnet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:03:51.568480Z","iopub.execute_input":"2025-02-19T16:03:51.568918Z","iopub.status.idle":"2025-02-19T16:03:51.931885Z","shell.execute_reply.started":"2025-02-19T16:03:51.568879Z","shell.execute_reply":"2025-02-19T16:03:51.930991Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(nasnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:03:51.932921Z","iopub.execute_input":"2025-02-19T16:03:51.933185Z","iopub.status.idle":"2025-02-19T16:03:55.853291Z","shell.execute_reply.started":"2025-02-19T16:03:51.933162Z","shell.execute_reply":"2025-02-19T16:03:55.852343Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" ","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}