{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-02-03T19:43:08.136611Z","iopub.execute_input":"2025-02-03T19:43:08.137376Z","iopub.status.idle":"2025-02-03T19:43:08.14538Z","shell.execute_reply.started":"2025-02-03T19:43:08.13734Z","shell.execute_reply":"2025-02-03T19:43:08.144418Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:39:56.556818Z","iopub.execute_input":"2025-02-03T19:39:56.557405Z","iopub.status.idle":"2025-02-03T19:40:07.455032Z","shell.execute_reply.started":"2025-02-03T19:39:56.557365Z","shell.execute_reply":"2025-02-03T19:40:07.454278Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# 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-03T19:40:07.456216Z","iopub.execute_input":"2025-02-03T19:40:07.456531Z","iopub.status.idle":"2025-02-03T19:40:08.546665Z","shell.execute_reply.started":"2025-02-03T19:40:07.456505Z","shell.execute_reply":"2025-02-03T19:40:08.545715Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"!ls train","metadata":{"execution":{"iopub.status.busy":"2024-01-08T06:57:18.293035Z","iopub.execute_input":"2024-01-08T06:57:18.293457Z","iopub.status.idle":"2024-01-08T06:57:19.311078Z","shell.execute_reply.started":"2024-01-08T06:57:18.293422Z","shell.execute_reply":"2024-01-08T06:57:19.309969Z"}}},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplotฅ\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:08.548567Z","iopub.execute_input":"2025-02-03T19:40:08.548872Z","iopub.status.idle":"2025-02-03T19:40:09.557Z","shell.execute_reply.started":"2025-02-03T19:40:08.548844Z","shell.execute_reply":"2025-02-03T19:40:09.556113Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:09.558444Z","iopub.execute_input":"2025-02-03T19:40:09.55883Z","iopub.status.idle":"2025-02-03T19:40:10.771107Z","shell.execute_reply.started":"2025-02-03T19:40:09.558794Z","shell.execute_reply":"2025-02-03T19:40:10.770129Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pip install numpy tensorflow\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-03T19:40:10.772401Z","iopub.execute_input":"2025-02-03T19:40:10.772682Z","iopub.status.idle":"2025-02-03T19:40:20.159162Z","shell.execute_reply.started":"2025-02-03T19:40:10.772657Z","shell.execute_reply":"2025-02-03T19:40:20.15817Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:20.160862Z","iopub.execute_input":"2025-02-03T19:40:20.161288Z","iopub.status.idle":"2025-02-03T19:40:23.328282Z","shell.execute_reply.started":"2025-02-03T19:40:20.161244Z","shell.execute_reply":"2025-02-03T19:40:23.326315Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"markdown","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\n# 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":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:28.251205Z","iopub.execute_input":"2025-02-03T19:40:28.251865Z","iopub.status.idle":"2025-02-03T19:40:28.256655Z","shell.execute_reply.started":"2025-02-03T19:40:28.251834Z","shell.execute_reply":"2025-02-03T19:40:28.255721Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\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":{"execution":{"iopub.status.busy":"2025-02-03T19:40:28.764371Z","iopub.execute_input":"2025-02-03T19:40:28.764735Z","iopub.status.idle":"2025-02-03T19:40:28.770307Z","shell.execute_reply.started":"2025-02-03T19:40:28.764704Z","shell.execute_reply":"2025-02-03T19:40:28.76929Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:31.172086Z","iopub.execute_input":"2025-02-03T19:40:31.172478Z","iopub.status.idle":"2025-02-03T19:40:34.864058Z","shell.execute_reply.started":"2025-02-03T19:40:31.172447Z","shell.execute_reply":"2025-02-03T19:40:34.863276Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:34.865624Z","iopub.execute_input":"2025-02-03T19:40:34.865921Z","iopub.status.idle":"2025-02-03T19:40:36.076035Z","shell.execute_reply.started":"2025-02-03T19:40:34.865895Z","shell.execute_reply":"2025-02-03T19:40:36.074786Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:36.077492Z","iopub.execute_input":"2025-02-03T19:40:36.077816Z","iopub.status.idle":"2025-02-03T19:40:37.281453Z","shell.execute_reply.started":"2025-02-03T19:40:36.077786Z","shell.execute_reply":"2025-02-03T19:40:37.280426Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:37.283675Z","iopub.execute_input":"2025-02-03T19:40:37.284002Z","iopub.status.idle":"2025-02-03T19:40:46.736031Z","shell.execute_reply.started":"2025-02-03T19:40:37.28397Z","shell.execute_reply":"2025-02-03T19:40:46.734874Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-03T19:40:46.737888Z","iopub.execute_input":"2025-02-03T19:40:46.738318Z","iopub.status.idle":"2025-02-03T19:40:46.750168Z","shell.execute_reply.started":"2025-02-03T19:40:46.738277Z","shell.execute_reply":"2025-02-03T19:40:46.749468Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-02-03T19:40:46.751832Z","iopub.execute_input":"2025-02-03T19:40:46.752108Z","iopub.status.idle":"2025-02-03T19:40:46.76308Z","shell.execute_reply.started":"2025-02-03T19:40:46.752085Z","shell.execute_reply":"2025-02-03T19:40:46.762286Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"xcep_model = Xception(include_top=False, input_shape=(299, 299, 3))\nxcep_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-27T04:11:23.494572Z","iopub.execute_input":"2024-01-27T04:11:23.495217Z","iopub.status.idle":"2024-01-27T04:11:26.579883Z","shell.execute_reply.started":"2024-01-27T04:11:23.495182Z","shell.execute_reply":"2024-01-27T04:11:26.578335Z"}}},{"cell_type":"code","source":"\n# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n \n# define cnn model\ndef define_model():\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 \n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n \n# 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=3, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n \n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-03T18:44:14.636808Z","iopub.execute_input":"2025-02-03T18:44:14.637185Z","iopub.status.idle":"2025-02-03T18:46:57.570381Z","shell.execute_reply.started":"2025-02-03T18:44:14.637153Z","shell.execute_reply":"2025-02-03T18:46:57.569294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Define Two Block VGG Model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n    # Compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# Plot training history\ndef summarize_diagnostics(history):\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    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    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# Run the training process\ndef run_test_harness():\n    model = define_model()\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\n    \n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n\n    # Train model (epochs = 5)\n    history = model.fit(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it), epochs=5, verbose=1)\n\n    # Evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n\n    # Save training plot\n    summarize_diagnostics(history)\n\n# Run training\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.329Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Define Three Block VGG Model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # Compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# Plot training history\ndef summarize_diagnostics(history):\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    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    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# Run the training process\ndef run_test_harness():\n    model = define_model()\n    datagen = ImageDataGenerator(rescale=1.0/255.0)\n    \n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n\n    # Train model (epochs = 5)\n    history = model.fit(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it), epochs=5, verbose=1)\n\n    # Evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n\n    # Save training plot\n    summarize_diagnostics(history)\n\n# Run training\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"\n**VGG 1: 72.331%VGG 2: 76.646%VGG 3: 80.184%**\n****","metadata":{}},{"cell_type":"markdown","source":"Develop Model Improvements\nDropout Regularization\n","metadata":{}},{"cell_type":"markdown","source":"ด้านล่างคือ define_model () ฟังก์ชั่นสําหรับรุ่นพื้นฐานที่อัปเดตด้วยการเพิ่ม Dropout ในกรณีนี้การออกกลางคัน 20% จะถูกนําไปใช้หลังจากแต่ละบล็อก VGG โดยมีอัตราการออกกลางคันที่ใหญ่กว่า 50% ที่ใช้หลังจากเลเยอร์ที่เชื่อมต่ออย่างสมบูรณ์ในส่วนตัวจําแนกของโมเดล","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n \n# define cnn model\ndef define_model():\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(Dropout(0.2))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dropout(0.5))\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 \n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n \n# 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 iterator\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=8, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n \n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ในกรณีนี้เราสามารถเห็นประสิทธิภาพของโมเดลเล็ก ๆ จากความแม่นยําประมาณ 80% สําหรับโมเดลพื้นฐานถึงประมาณ 81% ด้วยการเพิ่มการออกกลางคัน ถ้า Run ให้ได้ 50 รอบ","metadata":{}},{"cell_type":"markdown","source":"\n# การเพิ่มข้อมูลรูปภาพการเสริมข้อมูลรูปภาพ\nเป็นเทคนิคที่สามารถใช้เพื่อขยายขนาดของชุดข้อมูลการฝึกอบรมโดยการสร้างรูปภาพที่ดัดแปลงในชุดข้อมูลการฝึกอบรมแบบจําลองเครือข่ายประสาทเรียนรู้เชิงลึกเกี่ยวกับข้อมูลเพิ่มเติมอาจส่งผลให้มีรูปแบบที่มีทักษะมากขึ้นและเทคนิคการเสริมสามารถสร้างรูปแบบต่างๆของภาพที่สามารถปรับปรุงความสามารถของแบบจําลองที่เหมาะสมเพื่อสรุปสิ่งที่พวกเขาเรียนรู้กับภาพใหม่การเสริมข้อมูลยังสามารถทําหน้าที่เป็นเทคนิคการทําให้เป็นมาตรฐานเพิ่มเสียงรบกวนให้กับข้อมูลการฝึกอบรมและสนับสนุนให้แบบจําลองเรียนรู้คุณสมบัติเดียวกันคงที่กับตําแหน่งของพวกเขาในอินพุตการเปลี่ยนแปลงเล็กน้อยของภาพถ่ายอินพุตของสุนัขและแมวอาจเป็นประโยชน์สําหรับปัญหานี้เช่นกะเล็กและพลิกแนวนอน การเพิ่มเหล่านี้สามารถระบุเป็นอาร์กิวเมนต์ของ ImageDataGenerator ที่ใช้สําหรับชุดข้อมูลการฝึกอบรม ไม่ควรใช้การเพิ่มสําหรับชุดข้อมูลทดสอบเนื่องจากเราต้องการประเมินประสิทธิภาพของแบบจําลองในภาพถ่ายที่ไม่ได้แก้ไขสิ่งนี้ต้องการให้เรามีอินสแตนซ์ ImageDataGenerator แยกต่างหากสําหรับชุดข้อมูลรถไฟและชุดทดสอบจากนั้นตัววนซ้ําสําหรับชุดรถไฟและชุดทดสอบที่สร้างขึ้นจากเครื่องกําเนิดข้อมูลที่เกี่ยวข้อง ตัวอย่างเช่น:# create data generatorstrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)test_datagen = ImageDataGenerator(rescale=1.0/255.0)# prepare iteratorstrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\tclass_mode='binary', batch_size=64, target_size=(200, 200))test_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\tclass_mode='binary', batch_size=64, target_size=(200, 200))ในกรณีนี้ภาพถ่ายในชุดข้อมูลการฝึกอบรมจะถูกเพิ่มด้วยการเลื่อนแนวนอนและแนวตั้งขนาดเล็ก (10%) และการพลิกแนวนอนแบบสุ่มที่สร้างภาพสะท้อนของภาพถ่าย ภาพถ่ายทั้งในรถไฟและขั้นตอนการทดสอบจะมีการปรับค่าพิกเซลในลักษณะเดียวกันรายการรหัสแบบเต็มของโมเดลพื้นฐานที่มีการเพิ่มข้อมูลการฝึกอบรมสําหรับชุดข้อมูลสุนัขและแมวมีการระบุไว้ด้านล่างเพื่อความสมบูรณ์\n","metadata":{}},{"cell_type":"code","source":"import sys\nfrom matplotlib import pyplot\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Define Three Block VGG Model\ndef define_model():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n    model.add(MaxPooling2D((2, 2)))\n    \n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # Compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# Plot training history\ndef summarize_diagnostics(history):\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    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    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# Run the training process\ndef run_test_harness():\n    model = define_model()\n    \n    train_datagen = ImageDataGenerator(rescale=1.0/255.0,\n        width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\n    test_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n    train_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n    test_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n        class_mode='binary', batch_size=64, target_size=(200, 200))\n\n    # Train model (epochs = 8)\n    history = model.fit(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it), epochs=8, verbose=1)\n\n    # Evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n\n    # Save training plot\n    summarize_diagnostics(history)\n\n# Run training\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# ควรจะได้ ถ้า epoch = 50 \n# Baseline VGG3 + Dropout: 81.279%\n# Baseline VGG3 + Data Augmentation: 85.816\n","metadata":{}},{"cell_type":"markdown","source":"# Explore Transfer Learning\n","metadata":{}},{"cell_type":"code","source":"import sys\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras\n\n# Define CNN model\ndef define_model():\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    for layer in model.layers:\n        layer.trainable = False\n\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation=\"relu\", kernel_initializer=\"he_uniform\")(flat1)\n    output = Dense(1, activation=\"sigmoid\")(class1)\n\n    model = Model(inputs=model.inputs, outputs=output)\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss=\"binary_crossentropy\", metrics=[\"accuracy\"])\n    return model\n\n# Run training with livelossplot\ndef run_test_harness():\n    model = define_model()\n\n    datagen = ImageDataGenerator(featurewise_center=True)\n    datagen.mean = [123.68, 116.779, 103.939]\n\n    train_it = datagen.flow_from_directory(\"dataset_dogs_vs_cats/train/\",\n        class_mode=\"binary\", batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory(\"dataset_dogs_vs_cats/test/\",\n        class_mode=\"binary\", batch_size=64, target_size=(224, 224))\n\n    # ใช้ PlotLossesKeras สำหรับ Live Plot\n    live_plot = PlotLossesKeras()\n\n    history = model.fit(train_it, steps_per_epoch=len(train_it),\n        validation_data=test_it, validation_steps=len(test_it),\n        epochs=10, verbose=1, callbacks=[live_plot])\n\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n    print(\"> %.3f\" % (acc * 100.0))\n\n# Run training\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Once created, we can train the model as before on the training dataset.\n\nNot a lot of training will be required in this case, as only the new fully connected and output layer have trainable weights. As such, we will fix the number of training epochs at 10.\n\nThe VGG16 model was trained on a specific ImageNet challenge dataset. As such, it is configured to expected input images to have the shape 224×224 pixels. We will use this as the target size when loading photos from the dogs and cats dataset.\n\nThe model also expects images to be centered. That is, to have the mean pixel values from each channel (red, green, and blue) as calculated on the ImageNet training dataset subtracted from the input. Keras provides a function to perform this preparation for individual photos via the preprocess_input() function. Nevertheless, we can achieve the same effect with the ImageDataGenerator by setting the “featurewise_center” argument to “True” and manually specifying the mean pixel values to use when centering as the mean values from the ImageNet training dataset: [123.68, 116.779, 103.939].\n\nThe full code listing of the VGG model for transfer learning on the dogs vs. cats dataset is listed below.\n\n# vgg16 model used for transfer learning on the dogs and cats dataset\nimport 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\n \n# define cnn model\ndef define_model():\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\n \n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n \n# 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(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\thistory = model.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)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n \n# entry point, run the test harness\nrun_test_harness()\nRunning the example first fits the model, then reports the model performance on the hold out test dataset.\n\nNote: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.\n\nIn this case, we can see that the model achieved very impressive results with a classification accuracy of about 97% on the holdout test dataset.\n\nFound 18697 images belonging to 2 classes.\nFound 6303 images belonging to 2 classes.\n> 97.636","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"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, Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping\n\n# define cnn model\ndef define_model():\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    # unfreeze the last few layers for fine-tuning\n    for layer in model.layers[:-4]:  # freeze all layers except the last 4\n        layer.trainable = False\n    for layer in model.layers[-4:]:\n        layer.trainable = True\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    \n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    \n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# 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    \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    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    \n    # create data generator with augmentation\n    datagen = ImageDataGenerator(\n        featurewise_center=True,\n        rotation_range=30,\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    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\n    \n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n                                           class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(224, 224))\n    \n    # early stopping callback\n    early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n    \n    # fit model\n    history = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n                                  validation_data=test_it, validation_steps=len(test_it), \n                                  epochs=20, verbose=1, callbacks=[early_stopping])\n    \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"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, Flatten\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping\n\n# define cnn model\ndef define_model():\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    # unfreeze the last few layers for fine-tuning\n    for layer in model.layers[:-4]:  # freeze all layers except the last 4\n        layer.trainable = False\n    for layer in model.layers[-4:]:\n        layer.trainable = True\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    \n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    \n    # compile model using Adam optimizer with a lower learning rate\n    opt = Adam(learning_rate=0.0001)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# 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    \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    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    \n    # create data generator with augmentation\n    datagen = ImageDataGenerator(\n        featurewise_center=True,\n        rotation_range=30,\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    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\n    \n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n                                           class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(224, 224))\n    \n    # early stopping callback\n    early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n    \n    # fit model using the new fit method (instead of fit_generator)\n    history = model.fit(train_it, steps_per_epoch=len(train_it),\n                        validation_data=test_it, validation_steps=len(test_it), \n                        epochs=8, verbose=1, callbacks=[early_stopping])\n    \n    # evaluate model\n    _, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"## สร้างโมเดล\nmodel = define_model()\n\n# แสดงสรุปของโมเดล\nmodel.summary()","metadata":{"trusted":true,"execution":{"execution_failed":"2025-02-03T18:39:40.33Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" \nimport 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, Flatten\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping\nfrom livelossplot import PlotLossesKeras  # Import PlotLossesKeras\n\n# define cnn model\ndef define_model():\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    # unfreeze the last few layers for fine-tuning\n    for layer in model.layers[:-4]:  # freeze all layers except the last 4\n        layer.trainable = False\n    for layer in model.layers[-4:]:\n        layer.trainable = True\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    \n    # define new model\n    model_transfer = Model(inputs=model.inputs, outputs=output)\n    \n    # compile model using Adam optimizer with a lower learning rate\n    opt = Adam(learning_rate=0.0001)\n    model_transfer.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model_transfer\n\n# 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    \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    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model_transfer = define_model()\n    \n    # create data generator with augmentation\n    datagen = ImageDataGenerator(\n        featurewise_center=True,\n        rotation_range=30,\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    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\n    \n    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n                                           class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(224, 224))\n    \n    # early stopping callback\n    early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\n    \n    # PlotLossesKeras callback for live plotting\n    plot_losses = PlotLossesKeras()\n    \n    # fit model using the new fit method (instead of fit_generator)\n    history = model_transfer.fit(train_it, steps_per_epoch=len(train_it),\n                        validation_data=test_it, validation_steps=len(test_it), \n                        epochs=8, verbose=1, callbacks=[early_stopping, plot_losses])\n    \n    # evaluate model\n    _, acc = model_transfer.evaluate(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    \n    # learning curves\n    summarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-03T19:43:30.566508Z","iopub.execute_input":"2025-02-03T19:43:30.567325Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport random\nfrom keras.preprocessing.image import load_img, img_to_array\nfrom keras.models import load_model\n\n# ✅ โหลดโมเดลที่เทรนไว้แล้ว\ndef load_trained_model():\n    # ใช้โมเดลที่เทรนไว้แล้วจากฟังก์ชัน define_model\n    model_transfer = define_model()\n    # หากคุณมีไฟล์น้ำหนักที่บันทึกไว้ สามารถโหลดน้ำหนักได้ดังนี้:\n    # model_transfer.load_weights('your_model_weights.h5')\n    return model_transfer\n\n# ✅ ตั้งค่าพาธของชุดทดสอบ\ntest_dir = \"dataset_dogs_vs_cats/test/\"\ncategories = [\"cats\", \"dogs\"]\n\n# ✅ สุ่มเลือก 5 รูปจากแต่ละคลาส\nnum_samples = 5\nselected_images = {category: random.sample(os.listdir(os.path.join(test_dir, category)), num_samples) for category in categories}\n\n# ✅ เตรียมแสดงผล\nplt.figure(figsize=(12, 6))\n\n# ✅ โหลดโมเดล\nmodel_transfer = load_trained_model()\n\n# ✅ ทำการพยากรณ์แต่ละภาพ\nfor i, category in enumerate(categories):\n    for j, img_name in enumerate(selected_images[category]):\n        img_path = os.path.join(test_dir, category, img_name)\n        img = load_img(img_path, target_size=(224, 224))  # ✅ ปรับขนาดให้เข้ากับโมเดล\n        img_array = img_to_array(img) / 255.0  # ✅ Normalize\n        img_array = np.expand_dims(img_array, axis=0)\n\n        # ✅ ทำการพยากรณ์\n        prediction = model_transfer.predict(img_array)[0][0]\n        predicted_label = \"Cat\" if prediction < 0.5 else \"Dog\"  # ใช้ threshold 0.5\n        confidence = prediction if predicted_label == \"Dog\" else 1 - prediction  # ความมั่นใจของผลลัพธ์\n\n        # ✅ แสดงภาพ\n        plt.subplot(2, num_samples, i * num_samples + j + 1)\n        plt.imshow(img)\n        plt.axis(\"off\")\n        plt.title(f\"{predicted_label} ({confidence:.2f})\")\n\n# ✅ แสดงภาพทั้งหมด\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}