{"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-21T17:04:30.648676Z","iopub.execute_input":"2025-02-21T17:04:30.649041Z","iopub.status.idle":"2025-02-21T17:04:30.655477Z","shell.execute_reply.started":"2025-02-21T17:04:30.649012Z","shell.execute_reply":"2025-02-21T17:04:30.654569Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:30.6567Z","iopub.execute_input":"2025-02-21T17:04:30.656961Z","iopub.status.idle":"2025-02-21T17:04:31.729Z","shell.execute_reply.started":"2025-02-21T17:04:30.656939Z","shell.execute_reply":"2025-02-21T17:04:31.727916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2025-02-21T17:04:31.730937Z","iopub.execute_input":"2025-02-21T17:04:31.731225Z","iopub.status.idle":"2025-02-21T17:04:41.277973Z","shell.execute_reply.started":"2025-02-21T17:04:31.731199Z","shell.execute_reply":"2025-02-21T17:04:41.277241Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:41.279405Z","iopub.execute_input":"2025-02-21T17:04:41.280068Z","iopub.status.idle":"2025-02-21T17:04:42.355433Z","shell.execute_reply.started":"2025-02-21T17:04:41.280031Z","shell.execute_reply":"2025-02-21T17:04:42.35442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:42.357811Z","iopub.execute_input":"2025-02-21T17:04:42.358073Z","iopub.status.idle":"2025-02-21T17:04:43.423809Z","shell.execute_reply.started":"2025-02-21T17:04:42.358051Z","shell.execute_reply":"2025-02-21T17:04:43.422658Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:43.425176Z","iopub.execute_input":"2025-02-21T17:04:43.425449Z","iopub.status.idle":"2025-02-21T17:04:44.523044Z","shell.execute_reply.started":"2025-02-21T17:04:43.425425Z","shell.execute_reply":"2025-02-21T17:04:44.521901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:44.52487Z","iopub.execute_input":"2025-02-21T17:04:44.525728Z","iopub.status.idle":"2025-02-21T17:04:45.677228Z","shell.execute_reply.started":"2025-02-21T17:04:44.525689Z","shell.execute_reply":"2025-02-21T17:04:45.676204Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:45.678653Z","iopub.execute_input":"2025-02-21T17:04:45.678966Z","iopub.status.idle":"2025-02-21T17:04:46.850104Z","shell.execute_reply.started":"2025-02-21T17:04:45.678942Z","shell.execute_reply":"2025-02-21T17:04:46.84892Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2025-02-21T17:04:46.85164Z","iopub.execute_input":"2025-02-21T17:04:46.851967Z","iopub.status.idle":"2025-02-21T17:04:48.078463Z","shell.execute_reply.started":"2025-02-21T17:04:46.851943Z","shell.execute_reply":"2025-02-21T17:04:48.07764Z"},"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-21T17:04:48.079925Z","iopub.execute_input":"2025-02-21T17:04:48.08064Z","iopub.status.idle":"2025-02-21T17:04:49.098955Z","shell.execute_reply.started":"2025-02-21T17:04:48.080596Z","shell.execute_reply":"2025-02-21T17:04:49.098185Z"},"trusted":true},"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-21T17:04:49.102918Z","iopub.execute_input":"2025-02-21T17:04:49.103158Z","iopub.status.idle":"2025-02-21T17:04:49.107125Z","shell.execute_reply.started":"2025-02-21T17:04:49.103136Z","shell.execute_reply":"2025-02-21T17:04:49.10626Z"}},"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-21T17:04:49.108401Z","iopub.execute_input":"2025-02-21T17:04:49.109039Z","iopub.status.idle":"2025-02-21T17:04:49.117791Z","shell.execute_reply.started":"2025-02-21T17:04:49.109006Z","shell.execute_reply":"2025-02-21T17:04:49.117174Z"}},"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-21T17:04:49.119002Z","iopub.execute_input":"2025-02-21T17:04:49.11925Z","iopub.status.idle":"2025-02-21T17:04:49.129747Z","shell.execute_reply.started":"2025-02-21T17:04:49.119229Z","shell.execute_reply":"2025-02-21T17:04:49.12897Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:49.130738Z","iopub.execute_input":"2025-02-21T17:04:49.13154Z","iopub.status.idle":"2025-02-21T17:04:50.317635Z","shell.execute_reply.started":"2025-02-21T17:04:49.131509Z","shell.execute_reply":"2025-02-21T17:04:50.316751Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:50.319284Z","iopub.execute_input":"2025-02-21T17:04:50.319645Z","iopub.status.idle":"2025-02-21T17:04:51.359734Z","shell.execute_reply.started":"2025-02-21T17:04:50.31961Z","shell.execute_reply":"2025-02-21T17:04:51.358873Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:51.36103Z","iopub.execute_input":"2025-02-21T17:04:51.361286Z","iopub.status.idle":"2025-02-21T17:04:52.416623Z","shell.execute_reply.started":"2025-02-21T17:04:51.361263Z","shell.execute_reply":"2025-02-21T17:04:52.415713Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:52.418037Z","iopub.execute_input":"2025-02-21T17:04:52.418335Z","iopub.status.idle":"2025-02-21T17:04:53.392332Z","shell.execute_reply.started":"2025-02-21T17:04:52.41831Z","shell.execute_reply":"2025-02-21T17:04:53.39146Z"}},"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-21T17:04:53.393811Z","iopub.execute_input":"2025-02-21T17:04:53.394186Z","iopub.status.idle":"2025-02-21T17:04:54.323849Z","shell.execute_reply.started":"2025-02-21T17:04:53.394153Z","shell.execute_reply":"2025-02-21T17:04:54.323077Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:54.324988Z","iopub.execute_input":"2025-02-21T17:04:54.325244Z","iopub.status.idle":"2025-02-21T17:04:56.612147Z","shell.execute_reply.started":"2025-02-21T17:04:54.325221Z","shell.execute_reply":"2025-02-21T17:04:56.611091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:56.613662Z","iopub.execute_input":"2025-02-21T17:04:56.613931Z","iopub.status.idle":"2025-02-21T17:04:58.75496Z","shell.execute_reply.started":"2025-02-21T17:04:56.613908Z","shell.execute_reply":"2025-02-21T17:04:58.753685Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:04:58.756887Z","iopub.execute_input":"2025-02-21T17:04:58.757783Z","iopub.status.idle":"2025-02-21T17:05:07.108973Z","shell.execute_reply.started":"2025-02-21T17:04:58.757742Z","shell.execute_reply":"2025-02-21T17:05:07.107912Z"}},"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-21T17:05:07.110717Z","iopub.execute_input":"2025-02-21T17:05:07.111025Z","iopub.status.idle":"2025-02-21T17:05:07.116196Z","shell.execute_reply.started":"2025-02-21T17:05:07.111Z","shell.execute_reply":"2025-02-21T17:05:07.115291Z"}},"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-21T17:05:07.11713Z","iopub.execute_input":"2025-02-21T17:05:07.117353Z","iopub.status.idle":"2025-02-21T17:05:07.128527Z","shell.execute_reply.started":"2025-02-21T17:05:07.117333Z","shell.execute_reply":"2025-02-21T17:05:07.127876Z"}},"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-21T17:05:07.129499Z","iopub.execute_input":"2025-02-21T17:05:07.129747Z","iopub.status.idle":"2025-02-21T17:05:07.139878Z","shell.execute_reply.started":"2025-02-21T17:05:07.129726Z","shell.execute_reply":"2025-02-21T17:05:07.139255Z"}},"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-21T17:05:07.141038Z","iopub.execute_input":"2025-02-21T17:05:07.141324Z","iopub.status.idle":"2025-02-21T17:05:10.298373Z","shell.execute_reply.started":"2025-02-21T17:05:07.141295Z","shell.execute_reply":"2025-02-21T17:05:10.297298Z"}},"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-21T17:05:10.299529Z","iopub.execute_input":"2025-02-21T17:05:10.299809Z","iopub.status.idle":"2025-02-21T17:05:11.426449Z","shell.execute_reply.started":"2025-02-21T17:05:10.299786Z","shell.execute_reply":"2025-02-21T17:05:11.425435Z"}},"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-21T17:05:11.427981Z","iopub.execute_input":"2025-02-21T17:05:11.428295Z","iopub.status.idle":"2025-02-21T17:05:12.548663Z","shell.execute_reply.started":"2025-02-21T17:05:11.428269Z","shell.execute_reply":"2025-02-21T17:05:12.54749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:12.550343Z","iopub.execute_input":"2025-02-21T17:05:12.550678Z","iopub.status.idle":"2025-02-21T17:05:21.141019Z","shell.execute_reply.started":"2025-02-21T17:05:12.550649Z","shell.execute_reply":"2025-02-21T17:05:21.139949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:21.14743Z","iopub.execute_input":"2025-02-21T17:05:21.147773Z","iopub.status.idle":"2025-02-21T17:05:21.151944Z","shell.execute_reply.started":"2025-02-21T17:05:21.147747Z","shell.execute_reply":"2025-02-21T17:05:21.151068Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.xception import Xception\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:21.153006Z","iopub.execute_input":"2025-02-21T17:05:21.153236Z","iopub.status.idle":"2025-02-21T17:05:21.163388Z","shell.execute_reply.started":"2025-02-21T17:05:21.153216Z","shell.execute_reply":"2025-02-21T17:05:21.162569Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.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-21T17:05:21.164582Z","iopub.execute_input":"2025-02-21T17:05:21.164919Z","iopub.status.idle":"2025-02-21T17:05:21.865161Z","shell.execute_reply.started":"2025-02-21T17:05:21.164891Z","shell.execute_reply":"2025-02-21T17:05:21.864371Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.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-21T17:05:21.866389Z","iopub.execute_input":"2025-02-21T17:05:21.867039Z","iopub.status.idle":"2025-02-21T17:05:22.500951Z","shell.execute_reply.started":"2025-02-21T17:05:21.867005Z","shell.execute_reply":"2025-02-21T17:05:22.500053Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def summarize_diagnostics(history):\n    # ตัวอย่างการสร้างกราฟจากประวัติการฝึก\n    import matplotlib.pyplot as plt\n    \n    # Plot training & validation accuracy\n    plt.plot(history.history['accuracy'])\n    plt.plot(history.history['val_accuracy'])\n    plt.title('Model accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()\n\n    # Plot training & validation loss\n    plt.plot(history.history['loss'])\n    plt.plot(history.history['val_loss'])\n    plt.title('Model loss')\n    plt.xlabel('Epochs')\n    plt.ylabel('Loss')\n    plt.legend(['Train', 'Test'], loc='upper left')\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:22.502283Z","iopub.execute_input":"2025-02-21T17:05:22.503007Z","iopub.status.idle":"2025-02-21T17:05:22.508424Z","shell.execute_reply.started":"2025-02-21T17:05:22.502969Z","shell.execute_reply":"2025-02-21T17:05:22.507613Z"}},"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,"execution":{"iopub.status.busy":"2025-02-21T17:05:22.509804Z","iopub.execute_input":"2025-02-21T17:05:22.510169Z","iopub.status.idle":"2025-02-21T17:05:22.885686Z","shell.execute_reply.started":"2025-02-21T17:05:22.510139Z","shell.execute_reply":"2025-02-21T17:05:22.884802Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.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-21T17:05:22.886821Z","iopub.execute_input":"2025-02-21T17:05:22.887094Z","iopub.status.idle":"2025-02-21T17:05:23.603518Z","shell.execute_reply.started":"2025-02-21T17:05:22.88707Z","shell.execute_reply":"2025-02-21T17:05:23.602878Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:23.604693Z","iopub.execute_input":"2025-02-21T17:05:23.60506Z","iopub.status.idle":"2025-02-21T17:05:23.610874Z","shell.execute_reply.started":"2025-02-21T17:05:23.605029Z","shell.execute_reply":"2025-02-21T17:05:23.609953Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.models import Model\n\n# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)  # ใช้ output จากเลเยอร์สุดท้าย\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)  # ReLU และ He initializer\noutput = Dense(1, activation='sigmoid')(class1)  # Layer สุดท้ายสำหรับ binary classification\n\n# define new model\nmy_model = Model(inputs=model.inputs, outputs=output)\n\n# compile model\nopt = SGD(learning_rate=0.0001, momentum=0.9)  # ใช้ learning_rate แทน lr\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# display model summary\nmy_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:23.611976Z","iopub.execute_input":"2025-02-21T17:05:23.612225Z","iopub.status.idle":"2025-02-21T17:05:23.70643Z","shell.execute_reply.started":"2025-02-21T17:05:23.612203Z","shell.execute_reply":"2025-02-21T17:05:23.705777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory = my_model.fit(\n    train_it, \n    validation_data=test_it, \n    epochs=3,  # ปรับเป็นจำนวน epochs ที่ต้องการ\n    verbose=1,\n    callbacks=[PlotLossesKeras()]  # สามารถตัดออกหากไม่ต้องการการแสดงผลกราฟ\n)\n\n# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)  # ใช้ evaluate แทน evaluate_generator\nprint('> %.3f' % (acc * 100.0))\n\n# learning curves\nsummarize_diagnostics(history)\n\n# save model\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)\nprint(f'Model saved to {best_model}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:05:23.707391Z","iopub.execute_input":"2025-02-21T17:05:23.707664Z","iopub.status.idle":"2025-02-21T17:24:43.411194Z","shell.execute_reply.started":"2025-02-21T17:05:23.707641Z","shell.execute_reply":"2025-02-21T17:24:43.410274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\n\n# โหลดโมเดลที่เทรนเสร็จแล้ว\nmodel = load_model('vgg16_model.hdf5')  # เปลี่ยนเป็น path ของโมเดลที่เซฟไว้\n\n# เตรียม ImageDataGenerator สำหรับ test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลจากโฟลเดอร์ test\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=1,  # โหลดทีละ 1 รูป\n    target_size=(224, 224),\n    shuffle=True  # สุ่มลำดับของภาพ\n)\n\n# ดึงรูปจาก test set (สุ่ม 10 รูป คลาสละ 5 รูป)\nnum_samples = 10\nselected_images = []\nselected_labels = []\n\n# จำนวนรูปที่ต้องการจากแต่ละคลาส\nnum_dogs = 0\nnum_cats = 0\n\n# เลือกรูป 10 รูป โดย 5 รูปจากสุนัขและ 5 รูปจากแมว\nwhile len(selected_images) < num_samples:\n    img, label = next(test_it)  # ดึงรูปจาก test_it\n    if label[0] == 1 and num_dogs < 5:  # เลือกสุนัข\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_dogs += 1\n    elif label[0] == 0 and num_cats < 5:  # เลือกแมว\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_cats += 1\n\n# แปลงข้อมูลภาพให้เป็น numpy array\nselected_images = np.array(selected_images)\n\n# ใช้โมเดลทำนาย\npredictions = model.predict(selected_images)\n\n# เปลี่ยนค่าผลลัพธ์จาก sigmoid ให้เป็น 0 หรือ 1\npred_labels = (predictions > 0.5).astype(int)\n\n# แสดงผลลัพธ์\nfig, axes = plt.subplots(2, 5, figsize=(12, 6))\naxes = axes.ravel()\n\nfor i in range(num_samples):\n    axes[i].imshow(selected_images[i])  # แสดงรูปภาพ\n    true_label = \"Dog\" if selected_labels[i] == 1 else \"Cat\"  # ป้ายจริง\n    pred_label = \"Dog\" if pred_labels[i] == 1 else \"Cat\"  # ป้ายที่ทำนาย\n    pred_confidence = predictions[i][0] * 100  # ความมั่นใจของการทำนาย\n    axes[i].set_title(f\"True: {true_label}\\nPred: {pred_label} ({pred_confidence:.2f}%)\")  # แสดงผลลัพธ์\n    axes[i].axis('off')\n\nplt.tight_layout()  # ปรับการจัดตำแหน่งภาพ\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:43.41246Z","iopub.execute_input":"2025-02-21T17:24:43.412732Z","iopub.status.idle":"2025-02-21T17:24:47.422698Z","shell.execute_reply.started":"2025-02-21T17:24:43.412709Z","shell.execute_reply":"2025-02-21T17:24:47.421862Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import Xception\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras\n\n# โหลดโมเดล Xception\nmodel = Xception(\n    include_top=False, \n    input_shape=(299, 299, 3)  # ใช้ขนาด input ที่ Xception ต้องการ\n)\n\n# พิมพ์ summary ของโมเดล Xception\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:47.423689Z","iopub.execute_input":"2025-02-21T17:24:47.423966Z","iopub.status.idle":"2025-02-21T17:24:49.617306Z","shell.execute_reply.started":"2025-02-21T17:24:47.423943Z","shell.execute_reply":"2025-02-21T17:24:49.616442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# mark loaded layers as not trainable (freeze layers)\nfor index, layer in enumerate(model.layers[:15]):\n    if hasattr(layer, 'output_shape'):\n        print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n\n# unfreeze the remaining layers\nfor index, layer in enumerate(model.layers[15:]):\n    if hasattr(layer, 'output_shape'):\n        print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:49.619078Z","iopub.execute_input":"2025-02-21T17:24:49.619526Z","iopub.status.idle":"2025-02-21T17:24:49.641262Z","shell.execute_reply.started":"2025-02-21T17:24:49.619489Z","shell.execute_reply":"2025-02-21T17:24:49.640311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เพิ่ม new classifier layers\nflat1 = Flatten()(model.layers[-1].output)  # ใช้ output จากเลเยอร์สุดท้าย\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)  # ReLU และ He initializer\noutput = Dense(1, activation='sigmoid')(class1)  # Layer สุดท้ายสำหรับ binary classification","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:49.642315Z","iopub.execute_input":"2025-02-21T17:24:49.642557Z","iopub.status.idle":"2025-02-21T17:24:49.701161Z","shell.execute_reply.started":"2025-02-21T17:24:49.642537Z","shell.execute_reply":"2025-02-21T17:24:49.700491Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model\nmy_model = Model(inputs=model.inputs, outputs=output)\n\n# compile model\nopt = SGD(learning_rate=0.0001, momentum=0.9)  # ใช้ learning_rate แทน lr\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# display model summary\nmy_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:49.702143Z","iopub.execute_input":"2025-02-21T17:24:49.70239Z","iopub.status.idle":"2025-02-21T17:24:50.033777Z","shell.execute_reply.started":"2025-02-21T17:24:49.702367Z","shell.execute_reply":"2025-02-21T17:24:50.03287Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เตรียม ImageDataGenerator สำหรับการฝึก\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_it = train_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',  # โฟลเดอร์ train set\n    class_mode='binary',\n    batch_size=32,  # ปรับ batch size ตามที่ต้องการ\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ Xception ต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:50.034888Z","iopub.execute_input":"2025-02-21T17:24:50.035133Z","iopub.status.idle":"2025-02-21T17:24:50.69648Z","shell.execute_reply.started":"2025-02-21T17:24:50.03511Z","shell.execute_reply":"2025-02-21T17:24:50.695495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=32,  # ปรับ batch size ตามที่ต้องการ\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ Xception ต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:50.697818Z","iopub.execute_input":"2025-02-21T17:24:50.698142Z","iopub.status.idle":"2025-02-21T17:24:50.862361Z","shell.execute_reply.started":"2025-02-21T17:24:50.698116Z","shell.execute_reply":"2025-02-21T17:24:50.861672Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory = my_model.fit(\n    train_it, \n    validation_data=test_it, \n    epochs=3,  # ปรับเป็นจำนวน epochs ที่ต้องการ\n    verbose=1,\n)\n\n# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)  # ใช้ evaluate แทน evaluate_generator\nprint('> %.3f' % (acc * 100.0))\n\n# learning curves\nsummarize_diagnostics(history)\n\n# save model\nbest_model = 'xception_model.hdf5'  # เปลี่ยนชื่อไฟล์เป็นของ Xception\nmy_model.save(best_model)\nprint(f'Model saved to {best_model}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:24:50.863435Z","iopub.execute_input":"2025-02-21T17:24:50.863809Z","iopub.status.idle":"2025-02-21T17:52:39.054236Z","shell.execute_reply.started":"2025-02-21T17:24:50.863774Z","shell.execute_reply":"2025-02-21T17:52:39.053255Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\n\n# โหลดโมเดล Xception ที่ฝึกเสร็จแล้ว\nmodel = load_model('xception_model.hdf5')  # เปลี่ยนเป็น path ของโมเดลที่เซฟไว้\n\n# เตรียม ImageDataGenerator สำหรับ test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลจากโฟลเดอร์ test\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=1,  # โหลดทีละ 1 รูป\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ Xception ต้องการ\n    shuffle=True  # สุ่มลำดับของภาพ\n)\n\n# ดึงรูปจาก test set (สุ่ม 10 รูป คลาสละ 5 รูป)\nnum_samples = 10\nselected_images = []\nselected_labels = []\n\n# จำนวนรูปที่ต้องการจากแต่ละคลาส\nnum_dogs = 0\nnum_cats = 0\n\n# เลือกรูป 10 รูป โดย 5 รูปจากสุนัขและ 5 รูปจากแมว\nwhile len(selected_images) < num_samples:\n    img, label = next(test_it)  # ดึงรูปจาก test_it\n    if label[0] == 1 and num_dogs < 5:  # เลือกสุนัข\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_dogs += 1\n    elif label[0] == 0 and num_cats < 5:  # เลือกแมว\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_cats += 1\n\n# แปลงข้อมูลภาพให้เป็น numpy array\nselected_images = np.array(selected_images)\n\n# ใช้โมเดลทำนาย\npredictions = model.predict(selected_images)\n\n# เปลี่ยนค่าผลลัพธ์จาก sigmoid ให้เป็น 0 หรือ 1\npred_labels = (predictions > 0.5).astype(int)\n\n# แสดงผลลัพธ์\nfig, axes = plt.subplots(2, 5, figsize=(12, 6))\naxes = axes.ravel()\n\nfor i in range(num_samples):\n    axes[i].imshow(selected_images[i])  # แสดงรูปภาพ\n    true_label = \"Dog\" if selected_labels[i] == 1 else \"Cat\"  # ป้ายจริง\n    pred_label = \"Dog\" if pred_labels[i] == 1 else \"Cat\"  # ป้ายที่ทำนาย\n    pred_confidence = predictions[i][0] * 100  # ความมั่นใจของการทำนาย\n    axes[i].set_title(f\"True: {true_label}\\nPred: {pred_label} ({pred_confidence:.2f}%)\")  # แสดงผลลัพธ์\n    axes[i].axis('off')\n\nplt.tight_layout()  # ปรับการจัดตำแหน่งภาพ\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:39.055957Z","iopub.execute_input":"2025-02-21T17:52:39.0563Z","iopub.status.idle":"2025-02-21T17:52:45.107106Z","shell.execute_reply.started":"2025-02-21T17:52:39.056268Z","shell.execute_reply":"2025-02-21T17:52:45.106072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import InceptionV3\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras\n\n# โหลดโมเดล InceptionV3\nmodel = InceptionV3(\n    include_top=False, \n    input_shape=(299, 299, 3)  # ขนาดที่โมเดล InceptionV3 ต้องการ\n)\n\n# พิมพ์ summary ของโมเดล InceptionV3\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:45.108118Z","iopub.execute_input":"2025-02-21T17:52:45.108356Z","iopub.status.idle":"2025-02-21T17:52:48.642758Z","shell.execute_reply.started":"2025-02-21T17:52:45.108335Z","shell.execute_reply":"2025-02-21T17:52:48.641803Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# mark loaded layers as not trainable (freeze layers)\nfor index, layer in enumerate(model.layers[:15]):\n    if hasattr(layer, 'output_shape'):\n        print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n\n# unfreeze the remaining layers\nfor index, layer in enumerate(model.layers[15:]):\n    if hasattr(layer, 'output_shape'):\n        print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:48.643851Z","iopub.execute_input":"2025-02-21T17:52:48.644113Z","iopub.status.idle":"2025-02-21T17:52:48.670057Z","shell.execute_reply.started":"2025-02-21T17:52:48.644091Z","shell.execute_reply":"2025-02-21T17:52:48.669375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เพิ่ม new classifier layers\nflat1 = Flatten()(model.layers[-1].output)  # ใช้ output จากเลเยอร์สุดท้าย\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)  # ReLU และ He initializer\noutput = Dense(1, activation='sigmoid')(class1)  # Layer สุดท้ายสำหรับ binary classification","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:48.671049Z","iopub.execute_input":"2025-02-21T17:52:48.671294Z","iopub.status.idle":"2025-02-21T17:52:48.705601Z","shell.execute_reply.started":"2025-02-21T17:52:48.671265Z","shell.execute_reply":"2025-02-21T17:52:48.704963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model\nmy_model = Model(inputs=model.inputs, outputs=output)\n\n# compile model\nopt = SGD(learning_rate=0.0001, momentum=0.9)  # ใช้ learning_rate แทน lr\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# display model summary\nmy_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:48.706429Z","iopub.execute_input":"2025-02-21T17:52:48.70669Z","iopub.status.idle":"2025-02-21T17:52:49.395073Z","shell.execute_reply.started":"2025-02-21T17:52:48.706632Z","shell.execute_reply":"2025-02-21T17:52:49.394256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เตรียม ImageDataGenerator สำหรับการฝึก\ntrain_datagen = ImageDataGenerator(rescale=1./255)\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_it = train_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',  # โฟลเดอร์ train set\n    class_mode='binary',\n    batch_size=32,  # ปรับ batch size ตามที่ต้องการ\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ InceptionV3 ต้องการ\n)\n\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=32,  # ปรับ batch size ตามที่ต้องการ\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ InceptionV3 ต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:49.396324Z","iopub.execute_input":"2025-02-21T17:52:49.396671Z","iopub.status.idle":"2025-02-21T17:52:50.121527Z","shell.execute_reply.started":"2025-02-21T17:52:49.396639Z","shell.execute_reply":"2025-02-21T17:52:50.120877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory = my_model.fit(\n    train_it, \n    validation_data=test_it, \n    epochs=5,  # ปรับเป็นจำนวน epochs ที่ต้องการ\n    verbose=1,\n)\n\n# evaluate model\n_, acc = my_model.evaluate(test_it, verbose=1)  # ใช้ evaluate แทน evaluate_generator\nprint('> %.3f' % (acc * 100.0))\n\n# learning curves\nsummarize_diagnostics(history)\n\n# save model\nbest_model = 'inceptionv3_model.hdf5'  # เปลี่ยนชื่อไฟล์เป็นของ InceptionV3\nmy_model.save(best_model)\nprint(f'Model saved to {best_model}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T17:52:50.122537Z","iopub.execute_input":"2025-02-21T17:52:50.122791Z","iopub.status.idle":"2025-02-21T18:14:48.443558Z","shell.execute_reply.started":"2025-02-21T17:52:50.122769Z","shell.execute_reply":"2025-02-21T18:14:48.442638Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\n\n# โหลดโมเดล InceptionV3 ที่ฝึกเสร็จแล้ว\nmodel = load_model('inceptionv3_model.hdf5')  # เปลี่ยนเป็น path ของโมเดลที่เซฟไว้\n\n# เตรียม ImageDataGenerator สำหรับ test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลจากโฟลเดอร์ test\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=1,  # โหลดทีละ 1 รูป\n    target_size=(299, 299),  # ปรับขนาดให้ตรงกับที่ InceptionV3 ต้องการ\n    shuffle=True  # สุ่มลำดับของภาพ\n)\n\n# ดึงรูปจาก test set (สุ่ม 10 รูป คลาสละ 5 รูป)\nnum_samples = 10\nselected_images = []\nselected_labels = []\n\n# จำนวนรูปที่ต้องการจากแต่ละคลาส\nnum_dogs = 0\nnum_cats = 0\n\n# เลือกรูป 10 รูป โดย 5 รูปจากสุนัขและ 5 รูปจากแมว\nwhile len(selected_images) < num_samples:\n    img, label = next(test_it)  # ดึงรูปจาก test_it\n    if label[0] == 1 and num_dogs < 5:  # เลือกสุนัข\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_dogs += 1\n    elif label[0] == 0 and num_cats < 5:  # เลือกแมว\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_cats += 1\n\n# แปลงข้อมูลภาพให้เป็น numpy array\nselected_images = np.array(selected_images)\n\n# ใช้โมเดลทำนาย\npredictions = model.predict(selected_images)\n\n# เปลี่ยนค่าผลลัพธ์จาก sigmoid ให้เป็น 0 หรือ 1\npred_labels = (predictions > 0.5).astype(int)\n\n# แสดงผลลัพธ์\nfig, axes = plt.subplots(2, 5, figsize=(12, 6))\naxes = axes.ravel()\n\nfor i in range(num_samples):\n    axes[i].imshow(selected_images[i])  # แสดงรูปภาพ\n    true_label = \"Dog\" if selected_labels[i] == 1 else \"Cat\"  # ป้ายจริง\n    pred_label = \"Dog\" if pred_labels[i] == 1 else \"Cat\"  # ป้ายที่ทำนาย\n    pred_confidence = predictions[i][0] * 100  # ความมั่นใจของการทำนาย\n    axes[i].set_title(f\"True: {true_label}\\nPred: {pred_label} ({pred_confidence:.2f}%)\")  # แสดงผลลัพธ์\n    axes[i].axis('off')\n\nplt.tight_layout()  # ปรับการจัดตำแหน่งภาพ\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:48.444853Z","iopub.execute_input":"2025-02-21T18:14:48.445679Z","iopub.status.idle":"2025-02-21T18:14:56.002824Z","shell.execute_reply.started":"2025-02-21T18:14:48.445635Z","shell.execute_reply":"2025-02-21T18:14:56.001911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n\n# โหลด MobileNetV2 model โดยไม่รวม top layers\nbase_model = MobileNetV2(\n    include_top=False,  # ลบ fully connected layer ที่ใช้ในการจำแนก\n    input_shape=(224, 224, 3)  # ขนาดที่โมเดลต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:56.004143Z","iopub.execute_input":"2025-02-21T18:14:56.00478Z","iopub.status.idle":"2025-02-21T18:14:57.437481Z","shell.execute_reply.started":"2025-02-21T18:14:56.004746Z","shell.execute_reply":"2025-02-21T18:14:57.436817Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ทำให้ layer ของ base model ไม่สามารถฝึกได้ (freeze)\nfor layer in base_model.layers:\n    layer.trainable = False\n\n# เพิ่ม classifier layer สำหรับโมเดลที่ใช้กับงาน binary classification\nx = Flatten()(base_model.output)  # แปลงข้อมูลเป็น 1D\nx = Dense(128, activation='relu')(x)  # Dense layer แรก\nx = Dense(1, activation='sigmoid')(x)  # สุดท้ายเป็น sigmoid สำหรับ binary classification (แมวหรือสุนัข)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:57.438478Z","iopub.execute_input":"2025-02-21T18:14:57.438732Z","iopub.status.idle":"2025-02-21T18:14:57.471205Z","shell.execute_reply.started":"2025-02-21T18:14:57.438709Z","shell.execute_reply":"2025-02-21T18:14:57.470627Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# สร้างโมเดลใหม่โดยใช้ base model และ classifier ที่เราเพิ่ม\nmodel = Model(inputs=base_model.input, outputs=x)\n\n# คอมไพล์โมเดล\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:57.472251Z","iopub.execute_input":"2025-02-21T18:14:57.472561Z","iopub.status.idle":"2025-02-21T18:14:57.494065Z","shell.execute_reply.started":"2025-02-21T18:14:57.472533Z","shell.execute_reply":"2025-02-21T18:14:57.493259Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เตรียม ImageDataGenerator สำหรับ train และ test sets\ntrain_datagen = 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\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลการฝึกและการทดสอบ\ntrain_it = train_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',  # เปลี่ยนเป็น path ของ train set\n    class_mode='binary',\n    batch_size=32,\n    target_size=(224, 224)  # ขนาดที่โมเดลต้องการ\n)\n\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # เปลี่ยนเป็น path ของ test set\n    class_mode='binary',\n    batch_size=32,\n    target_size=(224, 224)  # ขนาดที่โมเดลต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:57.495239Z","iopub.execute_input":"2025-02-21T18:14:57.495566Z","iopub.status.idle":"2025-02-21T18:14:58.294804Z","shell.execute_reply.started":"2025-02-21T18:14:57.495542Z","shell.execute_reply":"2025-02-21T18:14:58.293816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ฝึกโมเดล\nhistory = model.fit(\n    train_it,\n    validation_data=test_it,\n    epochs=13,  # ปรับจำนวน epochs ตามที่ต้องการ\n    verbose=1\n)\n\n# ประเมินโมเดล\n_, acc = model.evaluate(test_it, verbose=1)\nprint(f'Model Accuracy: {acc * 100:.2f}%')\n\n# แสดงผลการฝึก\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Model Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# บันทึกโมเดลที่ฝึกเสร็จแล้ว\nmodel.save('mobilenetv2_model.hdf5')\nprint(\"Model saved to 'mobilenetv2_model.hdf5'\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T18:14:58.295973Z","iopub.execute_input":"2025-02-21T18:14:58.296211Z","iopub.status.idle":"2025-02-21T19:02:15.96098Z","shell.execute_reply.started":"2025-02-21T18:14:58.29619Z","shell.execute_reply":"2025-02-21T19:02:15.960011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications import MobileNetV2\n\n# โหลดโมเดล MobileNetV2 ที่ฝึกเสร็จแล้ว\nmodel = load_model('mobilenetv2_model.hdf5')  # เปลี่ยนเป็น path ของโมเดลที่เซฟไว้\n\n# เตรียม ImageDataGenerator สำหรับ test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลจากโฟลเดอร์ test\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=1,  # โหลดทีละ 1 รูป\n    target_size=(224, 224),  # ปรับขนาดให้ตรงกับที่ MobileNetV2 ต้องการ\n    shuffle=True  # สุ่มลำดับของภาพ\n)\n\n# ดึงรูปจาก test set (สุ่ม 10 รูป คลาสละ 5 รูป)\nnum_samples = 10\nselected_images = []\nselected_labels = []\n\n# จำนวนรูปที่ต้องการจากแต่ละคลาส\nnum_dogs = 0\nnum_cats = 0\n\n# เลือกรูป 10 รูป โดย 5 รูปจากสุนัขและ 5 รูปจากแมว\nwhile len(selected_images) < num_samples:\n    img, label = next(test_it)  # ดึงรูปจาก test_it\n    if label[0] == 1 and num_dogs < 5:  # เลือกสุนัข\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_dogs += 1\n    elif label[0] == 0 and num_cats < 5:  # เลือกแมว\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_cats += 1\n\n# แปลงข้อมูลภาพให้เป็น numpy array\nselected_images = np.array(selected_images)\n\n# ใช้โมเดลทำนาย\npredictions = model.predict(selected_images)\n\n# เปลี่ยนค่าผลลัพธ์จาก sigmoid ให้เป็น 0 หรือ 1\npred_labels = (predictions > 0.5).astype(int)\n\n# แสดงผลลัพธ์\nfig, axes = plt.subplots(2, 5, figsize=(12, 6))\naxes = axes.ravel()\n\nfor i in range(num_samples):\n    axes[i].imshow(selected_images[i])  # แสดงรูปภาพ\n    true_label = \"Dog\" if selected_labels[i] == 1 else \"Cat\"  # ป้ายจริง\n    pred_label = \"Dog\" if pred_labels[i] == 1 else \"Cat\"  # ป้ายที่ทำนาย\n    pred_confidence = predictions[i][0] * 100  # ความมั่นใจของการทำนาย\n    axes[i].set_title(f\"True: {true_label}\\nPred: {pred_label} ({pred_confidence:.2f}%)\")  # แสดงผลลัพธ์\n    axes[i].axis('off')\n\nplt.tight_layout()  # ปรับการจัดตำแหน่งภาพ\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:15.962074Z","iopub.execute_input":"2025-02-21T19:02:15.962344Z","iopub.status.idle":"2025-02-21T19:02:20.030575Z","shell.execute_reply.started":"2025-02-21T19:02:15.962322Z","shell.execute_reply":"2025-02-21T19:02:20.029644Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.optimizers import Adam\n\n# โหลดโมเดล DenseNet121 โดยไม่รวม top layers (จะใช้ classifier ของตัวเอง)\nbase_model = DenseNet121(\n    include_top=False,  # ลบ fully connected layers\n    input_shape=(224, 224, 3)  # ขนาดที่โมเดลต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:20.032106Z","iopub.execute_input":"2025-02-21T19:02:20.03235Z","iopub.status.idle":"2025-02-21T19:02:23.227826Z","shell.execute_reply.started":"2025-02-21T19:02:20.032329Z","shell.execute_reply":"2025-02-21T19:02:23.227114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ทำให้ layer ของ base model ไม่สามารถฝึกได้ (freeze)\nfor layer in base_model.layers:\n    layer.trainable = False\n\n# เพิ่ม classifier layer สำหรับโมเดลที่ใช้กับงาน binary classification\nx = Flatten()(base_model.output)  # แปลงข้อมูลเป็น 1D\nx = Dense(128, activation='relu')(x)  # Dense layer แรก\nx = Dense(1, activation='sigmoid')(x)  # สุดท้ายเป็น sigmoid สำหรับ binary classification (แมวหรือสุนัข)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:23.229Z","iopub.execute_input":"2025-02-21T19:02:23.229308Z","iopub.status.idle":"2025-02-21T19:02:23.269589Z","shell.execute_reply.started":"2025-02-21T19:02:23.22928Z","shell.execute_reply":"2025-02-21T19:02:23.269021Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# สร้างโมเดลใหม่โดยใช้ base model และ classifier ที่เราเพิ่ม\nmodel = Model(inputs=base_model.input, outputs=x)\n\n# คอมไพล์โมเดล\nmodel.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:23.270515Z","iopub.execute_input":"2025-02-21T19:02:23.270776Z","iopub.status.idle":"2025-02-21T19:02:23.309223Z","shell.execute_reply.started":"2025-02-21T19:02:23.270751Z","shell.execute_reply":"2025-02-21T19:02:23.308416Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เตรียม ImageDataGenerator สำหรับ train และ test sets\ntrain_datagen = 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\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลการฝึกและการทดสอบ\ntrain_it = train_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',  # เปลี่ยนเป็น path ของ train set\n    class_mode='binary',\n    batch_size=32,\n    target_size=(224, 224)  # ขนาดที่โมเดลต้องการ\n)\n\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # เปลี่ยนเป็น path ของ test set\n    class_mode='binary',\n    batch_size=32,\n    target_size=(224, 224)  # ขนาดที่โมเดลต้องการ\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:23.310234Z","iopub.execute_input":"2025-02-21T19:02:23.310488Z","iopub.status.idle":"2025-02-21T19:02:24.03973Z","shell.execute_reply.started":"2025-02-21T19:02:23.310467Z","shell.execute_reply":"2025-02-21T19:02:24.039096Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ฝึกโมเดล\nhistory = model.fit(\n    train_it,\n    validation_data=test_it,\n    epochs=13,  # ปรับจำนวน epochs ตามที่ต้องการ\n    verbose=1\n)\n\n# ประเมินโมเดล\n_, acc = model.evaluate(test_it, verbose=1)\nprint(f'Model Accuracy: {acc * 100:.2f}%')\n\n# แสดงผลการฝึก\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Model Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# บันทึกโมเดลที่ฝึกเสร็จแล้ว\nmodel.save('densenet121_model.hdf5')\nprint(\"Model saved to 'densenet121_model.hdf5'\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:02:24.040667Z","iopub.execute_input":"2025-02-21T19:02:24.040943Z","iopub.status.idle":"2025-02-21T19:52:16.559142Z","shell.execute_reply.started":"2025-02-21T19:02:24.040919Z","shell.execute_reply":"2025-02-21T19:52:16.558215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications import DenseNet121  # เปลี่ยนจาก MobileNetV2 เป็น DenseNet121\n\n# โหลดโมเดล DenseNet121 ที่ฝึกเสร็จแล้ว\nmodel = load_model('densenet121_model.hdf5')  # เปลี่ยนเป็น path ของโมเดลที่เซฟไว้\n\n# เตรียม ImageDataGenerator สำหรับ test set\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\n# โหลดข้อมูลจากโฟลเดอร์ test\ntest_it = test_datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',  # โฟลเดอร์ test set\n    class_mode='binary',\n    batch_size=1,  # โหลดทีละ 1 รูป\n    target_size=(224, 224),  # ปรับขนาดให้ตรงกับที่ DenseNet121 ต้องการ\n    shuffle=True  # สุ่มลำดับของภาพ\n)\n\n# ดึงรูปจาก test set (สุ่ม 10 รูป คลาสละ 5 รูป)\nnum_samples = 10\nselected_images = []\nselected_labels = []\n\n# จำนวนรูปที่ต้องการจากแต่ละคลาส\nnum_dogs = 0\nnum_cats = 0\n\n# เลือกรูป 10 รูป โดย 5 รูปจากสุนัขและ 5 รูปจากแมว\nwhile len(selected_images) < num_samples:\n    img, label = next(test_it)  # ดึงรูปจาก test_it\n    if label[0] == 1 and num_dogs < 5:  # เลือกสุนัข\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_dogs += 1\n    elif label[0] == 0 and num_cats < 5:  # เลือกแมว\n        selected_images.append(img[0])  # ดึงภาพ\n        selected_labels.append(label[0])  # ดึง label\n        num_cats += 1\n\n# แปลงข้อมูลภาพให้เป็น numpy array\nselected_images = np.array(selected_images)\n\n# ใช้โมเดลทำนาย\npredictions = model.predict(selected_images)\n\n# เปลี่ยนค่าผลลัพธ์จาก sigmoid ให้เป็น 0 หรือ 1\npred_labels = (predictions > 0.5).astype(int)\n\n# แสดงผลลัพธ์\nfig, axes = plt.subplots(2, 5, figsize=(12, 6))\naxes = axes.ravel()\n\nfor i in range(num_samples):\n    axes[i].imshow(selected_images[i])  # แสดงรูปภาพ\n    true_label = \"Dog\" if selected_labels[i] == 1 else \"Cat\"  # ป้ายจริง\n    pred_label = \"Dog\" if pred_labels[i] == 1 else \"Cat\"  # ป้ายที่ทำนาย\n    pred_confidence = predictions[i][0] * 100  # ความมั่นใจของการทำนาย\n    axes[i].set_title(f\"True: {true_label}\\nPred: {pred_label} ({pred_confidence:.2f}%)\")  # แสดงผลลัพธ์\n    axes[i].axis('off')\n\nplt.tight_layout()  # ปรับการจัดตำแหน่งภาพ\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-21T19:52:16.560487Z","iopub.execute_input":"2025-02-21T19:52:16.560864Z","iopub.status.idle":"2025-02-21T19:52:24.78Z","shell.execute_reply.started":"2025-02-21T19:52:16.560811Z","shell.execute_reply":"2025-02-21T19:52:24.779188Z"}},"outputs":[],"execution_count":null}]}