{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:16.159268Z","iopub.execute_input":"2026-09-12T17:45:16.16008Z","iopub.status.idle":"2026-09-12T17:45:16.16735Z","shell.execute_reply.started":"2026-09-12T17:45:16.160042Z","shell.execute_reply":"2026-09-12T17:45:16.166674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:16.169007Z","iopub.execute_input":"2026-09-12T17:45:16.169365Z","iopub.status.idle":"2026-09-12T17:45:17.229172Z","shell.execute_reply.started":"2026-09-12T17:45:16.169332Z","shell.execute_reply":"2026-09-12T17:45:17.228163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:17.230802Z","iopub.execute_input":"2026-09-12T17:45:17.231208Z","iopub.status.idle":"2026-09-12T17:45:27.035448Z","shell.execute_reply.started":"2026-09-12T17:45:17.231175Z","shell.execute_reply":"2026-09-12T17:45:27.03468Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:27.037323Z","iopub.execute_input":"2026-09-12T17:45:27.037737Z","iopub.status.idle":"2026-09-12T17:45:28.087038Z","shell.execute_reply.started":"2026-09-12T17:45:27.037711Z","shell.execute_reply":"2026-09-12T17:45:28.085487Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:28.088811Z","iopub.execute_input":"2026-09-12T17:45:28.089127Z","iopub.status.idle":"2026-09-12T17:45:29.176404Z","shell.execute_reply.started":"2026-09-12T17:45:28.089099Z","shell.execute_reply":"2026-09-12T17:45:29.175392Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:29.178201Z","iopub.execute_input":"2026-09-12T17:45:29.178587Z","iopub.status.idle":"2026-09-12T17:45:30.269545Z","shell.execute_reply.started":"2026-09-12T17:45:29.178549Z","shell.execute_reply":"2026-09-12T17:45:30.268637Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:30.27097Z","iopub.execute_input":"2026-09-12T17:45:30.271293Z","iopub.status.idle":"2026-09-12T17:45:31.343349Z","shell.execute_reply.started":"2026-09-12T17:45:30.271264Z","shell.execute_reply":"2026-09-12T17:45:31.342368Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:31.344924Z","iopub.execute_input":"2026-09-12T17:45:31.345232Z","iopub.status.idle":"2026-09-12T17:45:32.491451Z","shell.execute_reply.started":"2026-09-12T17:45:31.345205Z","shell.execute_reply":"2026-09-12T17:45:32.490423Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:32.492913Z","iopub.execute_input":"2026-09-12T17:45:32.493233Z","iopub.status.idle":"2026-09-12T17:45:33.535828Z","shell.execute_reply.started":"2026-09-12T17:45:32.493206Z","shell.execute_reply":"2026-09-12T17:45:33.534811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:33.539682Z","iopub.execute_input":"2026-09-12T17:45:33.540034Z","iopub.status.idle":"2026-09-12T17:45:34.656009Z","shell.execute_reply.started":"2026-09-12T17:45:33.540006Z","shell.execute_reply":"2026-09-12T17:45:34.655104Z"}},"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":"2026-09-12T17:45:34.657399Z","iopub.execute_input":"2026-09-12T17:45:34.658165Z","iopub.status.idle":"2026-09-12T17:45:35.608036Z","shell.execute_reply.started":"2026-09-12T17:45:34.658127Z","shell.execute_reply":"2026-09-12T17:45:35.607304Z"}},"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":"2026-09-12T17:45:35.609178Z","iopub.execute_input":"2026-09-12T17:45:35.609455Z","iopub.status.idle":"2026-09-12T17:45:36.568632Z","shell.execute_reply.started":"2026-09-12T17:45:35.609431Z","shell.execute_reply":"2026-09-12T17:45:36.56762Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:36.569929Z","iopub.execute_input":"2026-09-12T17:45:36.570273Z","iopub.status.idle":"2026-09-12T17:45:37.617489Z","shell.execute_reply.started":"2026-09-12T17:45:36.57024Z","shell.execute_reply":"2026-09-12T17:45:37.616538Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow\nprint(tensorflow.__version__)\n\nimport keras\nprint(keras.__version__)\n\nimport tensorflow.keras\nprint(tensorflow.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:37.619066Z","iopub.execute_input":"2026-09-12T17:45:37.619469Z","iopub.status.idle":"2026-09-12T17:45:37.625114Z","shell.execute_reply.started":"2026-09-12T17:45:37.61944Z","shell.execute_reply":"2026-09-12T17:45:37.624156Z"}},"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":"2026-09-12T17:45:37.626369Z","iopub.execute_input":"2026-09-12T17:45:37.627144Z","iopub.status.idle":"2026-09-12T17:45:37.633725Z","shell.execute_reply.started":"2026-09-12T17:45:37.627084Z","shell.execute_reply":"2026-09-12T17:45:37.632755Z"}},"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":"code","source":"import zipfile\nimport os\n\n# แตกไฟล์ train.zip มาไว้ที่โฟลเดอร์ปัจจุบัน (.)\ntrain_zip = '/kaggle/input/competitions/dogs-vs-cats/train.zip'\nif not os.path.exists(train_zip):\n    train_zip = '/kaggle/input/dogs-vs-cats/train.zip'\n\nwith zipfile.ZipFile(train_zip, 'r') as z:\n    z.extractall('.')\n\nprint(\"แตกไฟล์ train.zip เสร็จสิ้น!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:37.634983Z","iopub.execute_input":"2026-09-12T17:45:37.635339Z","iopub.status.idle":"2026-09-12T17:45:43.351497Z","shell.execute_reply.started":"2026-09-12T17:45:37.635278Z","shell.execute_reply":"2026-09-12T17:45:43.35046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nfrom random import seed, random\n\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n    for labldir in ['dogs/', 'cats/']:\n        newdir = os.path.join(dataset_home, subdir, labldir)\n        os.makedirs(newdir, exist_ok=True)\n\nseed(1)\nval_ratio = 0.25\nsrc_directory = 'train/'\n\nfor file in os.listdir(src_directory):\n    if not file.endswith('.jpg'):\n        continue\n    \n    src = os.path.join(src_directory, file)\n    dst_dir = 'train/'\n    if random() < val_ratio:\n        dst_dir = 'test/'\n        \n    if file.startswith('cat'):\n        dst = os.path.join(dataset_home, dst_dir, 'cats/', file)\n        shutil.copyfile(src, dst)\n    elif file.startswith('dog'):\n        dst = os.path.join(dataset_home, dst_dir, 'dogs/', file)\n        shutil.copyfile(src, dst)\n\nprint(\"succes!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:43.352765Z","iopub.execute_input":"2026-09-12T17:45:43.353009Z","iopub.status.idle":"2026-09-12T17:45:46.592071Z","shell.execute_reply.started":"2026-09-12T17:45:43.352988Z","shell.execute_reply":"2026-09-12T17:45:46.591093Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:46.594548Z","iopub.execute_input":"2026-09-12T17:45:46.594909Z","iopub.status.idle":"2026-09-12T17:45:46.599349Z","shell.execute_reply.started":"2026-09-12T17:45:46.594882Z","shell.execute_reply":"2026-09-12T17:45:46.598556Z"}},"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":"2026-09-12T17:45:46.600557Z","iopub.execute_input":"2026-09-12T17:45:46.601518Z","iopub.status.idle":"2026-09-12T17:45:47.243319Z","shell.execute_reply.started":"2026-09-12T17:45:46.601492Z","shell.execute_reply":"2026-09-12T17:45:47.242304Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!rm dogs_vs_cats_photos.npy dogs_vs_cats_labels.npy","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:47.244918Z","iopub.execute_input":"2026-09-12T17:45:47.245306Z","iopub.status.idle":"2026-09-12T17:45:48.355519Z","shell.execute_reply.started":"2026-09-12T17:45:47.24527Z","shell.execute_reply":"2026-09-12T17:45:48.354416Z"}},"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":"2026-09-12T17:45:48.357062Z","iopub.execute_input":"2026-09-12T17:45:48.35742Z","iopub.status.idle":"2026-09-12T17:45:49.578083Z","shell.execute_reply.started":"2026-09-12T17:45:48.35739Z","shell.execute_reply":"2026-09-12T17:45:49.576778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:49.579974Z","iopub.execute_input":"2026-09-12T17:45:49.580375Z","iopub.status.idle":"2026-09-12T17:45:50.620526Z","shell.execute_reply.started":"2026-09-12T17:45:49.580338Z","shell.execute_reply":"2026-09-12T17:45:50.619581Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:50.622055Z","iopub.execute_input":"2026-09-12T17:45:50.622365Z","iopub.status.idle":"2026-09-12T17:45:51.656563Z","shell.execute_reply.started":"2026-09-12T17:45:50.622338Z","shell.execute_reply":"2026-09-12T17:45:51.655659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:51.658001Z","iopub.execute_input":"2026-09-12T17:45:51.658409Z","iopub.status.idle":"2026-09-12T17:45:52.715876Z","shell.execute_reply.started":"2026-09-12T17:45:51.658381Z","shell.execute_reply":"2026-09-12T17:45:52.714588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:52.71773Z","iopub.execute_input":"2026-09-12T17:45:52.718114Z","iopub.status.idle":"2026-09-12T17:45:55.875882Z","shell.execute_reply.started":"2026-09-12T17:45:52.718077Z","shell.execute_reply":"2026-09-12T17:45:55.875132Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:45:55.876968Z","iopub.execute_input":"2026-09-12T17:45:55.877255Z","iopub.status.idle":"2026-09-12T17:45:55.882364Z","shell.execute_reply.started":"2026-09-12T17:45:55.877232Z","shell.execute_reply":"2026-09-12T17:45:55.881408Z"}},"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":"2026-09-12T17:45:55.883588Z","iopub.execute_input":"2026-09-12T17:45:55.883977Z","iopub.status.idle":"2026-09-12T17:45:58.153822Z","shell.execute_reply.started":"2026-09-12T17:45:55.883944Z","shell.execute_reply":"2026-09-12T17:45:58.15282Z"}},"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":"2026-09-12T17:45:58.16187Z","iopub.execute_input":"2026-09-12T17:45:58.162158Z","iopub.status.idle":"2026-09-12T17:46:00.414697Z","shell.execute_reply.started":"2026-09-12T17:45:58.162133Z","shell.execute_reply":"2026-09-12T17:46:00.413646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:00.416102Z","iopub.execute_input":"2026-09-12T17:46:00.41636Z","iopub.status.idle":"2026-09-12T17:46:02.328891Z","shell.execute_reply.started":"2026-09-12T17:46:00.416336Z","shell.execute_reply":"2026-09-12T17:46:02.327919Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.330285Z","iopub.execute_input":"2026-09-12T17:46:02.330774Z","iopub.status.idle":"2026-09-12T17:46:02.335324Z","shell.execute_reply.started":"2026-09-12T17:46:02.330746Z","shell.execute_reply":"2026-09-12T17:46:02.334468Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.336547Z","iopub.execute_input":"2026-09-12T17:46:02.336956Z","iopub.status.idle":"2026-09-12T17:46:02.346396Z","shell.execute_reply.started":"2026-09-12T17:46:02.336931Z","shell.execute_reply":"2026-09-12T17:46:02.345378Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.347584Z","iopub.execute_input":"2026-09-12T17:46:02.347912Z","iopub.status.idle":"2026-09-12T17:46:02.354268Z","shell.execute_reply.started":"2026-09-12T17:46:02.347882Z","shell.execute_reply":"2026-09-12T17:46:02.353399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.355367Z","iopub.execute_input":"2026-09-12T17:46:02.35572Z","iopub.status.idle":"2026-09-12T17:46:02.370005Z","shell.execute_reply.started":"2026-09-12T17:46:02.355687Z","shell.execute_reply":"2026-09-12T17:46:02.36901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model =Sequential()\n\nmodel.add(Conv2D(32,\n                (3, 3),\n                activation='relu',\n                input_shape=(200,200,3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.371108Z","iopub.execute_input":"2026-09-12T17:46:02.371449Z","iopub.status.idle":"2026-09-12T17:46:02.435431Z","shell.execute_reply.started":"2026-09-12T17:46:02.371419Z","shell.execute_reply":"2026-09-12T17:46:02.433958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,\n                 (3, 3),\n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(2, activation='softmax'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.436418Z","iopub.execute_input":"2026-09-12T17:46:02.436668Z","iopub.status.idle":"2026-09-12T17:46:02.490049Z","shell.execute_reply.started":"2026-09-12T17:46:02.436634Z","shell.execute_reply":"2026-09-12T17:46:02.489278Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.491253Z","iopub.execute_input":"2026-09-12T17:46:02.491856Z","iopub.status.idle":"2026-09-12T17:46:02.4987Z","shell.execute_reply.started":"2026-09-12T17:46:02.491823Z","shell.execute_reply":"2026-09-12T17:46:02.497811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    # plot loss\n    pyplot.subplot(211)\n    pyplot.title('Cross Entropy Loss')\n    pyplot.plot(history.history['loss'], color='blue', label='train')\n    pyplot.plot(history.history['val_loss'], color='orange', label='test')\n    # plot accuracy\n    pyplot.subplot(212)\n    pyplot.title('Classification Accuracy')\n    pyplot.plot(history.history['accuracy'], color='blue', label='train')\n    pyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n    pyplot.show()\n    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png') \n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.499581Z","iopub.execute_input":"2026-09-12T17:46:02.499846Z","iopub.status.idle":"2026-09-12T17:46:02.508183Z","shell.execute_reply.started":"2026-09-12T17:46:02.499826Z","shell.execute_reply":"2026-09-12T17:46:02.507539Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model, not recommend to call this function\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.509578Z","iopub.execute_input":"2026-09-12T17:46:02.509957Z","iopub.status.idle":"2026-09-12T17:46:02.518802Z","shell.execute_reply.started":"2026-09-12T17:46:02.509932Z","shell.execute_reply":"2026-09-12T17:46:02.517948Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.519911Z","iopub.execute_input":"2026-09-12T17:46:02.520219Z","iopub.status.idle":"2026-09-12T17:46:02.588482Z","shell.execute_reply.started":"2026-09-12T17:46:02.52019Z","shell.execute_reply":"2026-09-12T17:46:02.587582Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:02.58953Z","iopub.execute_input":"2026-09-12T17:46:02.590641Z","iopub.status.idle":"2026-09-12T17:46:03.606831Z","shell.execute_reply.started":"2026-09-12T17:46:02.590578Z","shell.execute_reply":"2026-09-12T17:46:03.606101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_it), len(train_it.classes), train_it.classes[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:03.607852Z","iopub.execute_input":"2026-09-12T17:46:03.608129Z","iopub.status.idle":"2026-09-12T17:46:03.616111Z","shell.execute_reply.started":"2026-09-12T17:46:03.608105Z","shell.execute_reply":"2026-09-12T17:46:03.614924Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BATCH_SIZE = 64\nIMAGE_SIZE = (200, 200)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0)\n\ntrain_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE\n)\n\nval_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:03.617199Z","iopub.execute_input":"2026-09-12T17:46:03.617499Z","iopub.status.idle":"2026-09-12T17:46:04.485083Z","shell.execute_reply.started":"2026-09-12T17:46:03.61747Z","shell.execute_reply":"2026-09-12T17:46:04.484389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(val_it), len(val_it.classes), val_it.classes[-10:]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:04.486037Z","iopub.execute_input":"2026-09-12T17:46:04.486373Z","iopub.status.idle":"2026-09-12T17:46:04.493356Z","shell.execute_reply.started":"2026-09-12T17:46:04.486349Z","shell.execute_reply":"2026-09-12T17:46:04.49265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install livelossplot\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:04.494456Z","iopub.execute_input":"2026-09-12T17:46:04.494969Z","iopub.status.idle":"2026-09-12T17:46:06.291933Z","shell.execute_reply.started":"2026-09-12T17:46:04.494937Z","shell.execute_reply":"2026-09-12T17:46:06.290959Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install livelossplot tf-keras\n\nimport tensorflow as tf\nfrom tf_keras.models import Sequential\nfrom tf_keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tf_keras.optimizers import SGD","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:06.293386Z","iopub.execute_input":"2026-09-12T17:46:06.294045Z","iopub.status.idle":"2026-09-12T17:46:08.712822Z","shell.execute_reply.started":"2026-09-12T17:46:06.294017Z","shell.execute_reply":"2026-09-12T17:46:08.711805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, GlobalAveragePooling2D, RandomFlip, RandomRotation, RandomZoom\nfrom tensorflow.keras.applications import MobileNetV2\nfrom tensorflow.keras.optimizers import Adam\nfrom livelossplot import PlotLossesKeras\n\n\nbase_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(200, 200, 3))\nbase_model.trainable = False\n\n\nmodel_1 = Sequential([\n    \n    RandomFlip(\"horizontal\"),\n    RandomRotation(0.1),\n    RandomZoom(0.1),\n    \n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),  \n    Dense(1, activation='sigmoid')\n])\n\n\nopt = Adam(learning_rate=0.0001)\nmodel_1.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n\nplot_losses = PlotLossesKeras()\nhistory_1 = model_1.fit(\n    train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=20,\n    verbose=1,\n    callbacks=[plot_losses]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T17:46:08.71452Z","iopub.execute_input":"2026-09-12T17:46:08.714923Z","iopub.status.idle":"2026-09-12T18:05:50.522779Z","shell.execute_reply.started":"2026-09-12T17:46:08.714887Z","shell.execute_reply":"2026-09-12T18:05:50.521644Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from matplotlib import pyplot\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n    pyplot.figure(figsize=(8, 8))\n    \n    # 1. plot loss (กราฟสีส้ม-ฟ้า Cross Entropy 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    # 2. plot accuracy (Classification 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    pyplot.tight_layout()\n    pyplot.show()\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:50.524134Z","iopub.execute_input":"2026-09-12T18:05:50.525154Z","iopub.status.idle":"2026-09-12T18:05:50.53135Z","shell.execute_reply.started":"2026-09-12T18:05:50.525118Z","shell.execute_reply":"2026-09-12T18:05:50.530523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:50.532458Z","iopub.execute_input":"2026-09-12T18:05:50.532772Z","iopub.status.idle":"2026-09-12T18:05:51.594005Z","shell.execute_reply.started":"2026-09-12T18:05:50.532746Z","shell.execute_reply":"2026-09-12T18:05:51.592695Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.595734Z","iopub.execute_input":"2026-09-12T18:05:51.596053Z","iopub.status.idle":"2026-09-12T18:05:51.604073Z","shell.execute_reply.started":"2026-09-12T18:05:51.596025Z","shell.execute_reply":"2026-09-12T18:05:51.603139Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_files[:5], type(image_files), len(image_files)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.605418Z","iopub.execute_input":"2026-09-12T18:05:51.605797Z","iopub.status.idle":"2026-09-12T18:05:51.613758Z","shell.execute_reply.started":"2026-09-12T18:05:51.605763Z","shell.execute_reply":"2026-09-12T18:05:51.612776Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.615142Z","iopub.execute_input":"2026-09-12T18:05:51.615889Z","iopub.status.idle":"2026-09-12T18:05:51.637783Z","shell.execute_reply.started":"2026-09-12T18:05:51.615851Z","shell.execute_reply":"2026-09-12T18:05:51.636925Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.63899Z","iopub.execute_input":"2026-09-12T18:05:51.639308Z","iopub.status.idle":"2026-09-12T18:05:51.645663Z","shell.execute_reply.started":"2026-09-12T18:05:51.639278Z","shell.execute_reply":"2026-09-12T18:05:51.644763Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.646746Z","iopub.execute_input":"2026-09-12T18:05:51.647096Z","iopub.status.idle":"2026-09-12T18:05:51.65641Z","shell.execute_reply.started":"2026-09-12T18:05:51.647074Z","shell.execute_reply":"2026-09-12T18:05:51.655466Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.657813Z","iopub.execute_input":"2026-09-12T18:05:51.658148Z","iopub.status.idle":"2026-09-12T18:05:51.666561Z","shell.execute_reply.started":"2026-09-12T18:05:51.658119Z","shell.execute_reply":"2026-09-12T18:05:51.665561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (224, 224)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0,\n                            horizontal_flip=True,)\n#print(IMAGE_SIZE)\n# prepare iterators\n#train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n #   class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n#val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n #   class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen_test = ImageDataGenerator(rescale=1./255,\n                                 horizontal_flip=True)\n\n# Create the data generator using the DataFrame\ntest_it = datagen_test.flow_from_dataframe(\n    dataframe=df,\n    x_col='filename',\n    y_col=None,            # No labels for testing, so set to None\n    target_size=IMAGE_SIZE,\n    batch_size=64,\n    class_mode=None,       # Since there are no labels\n    # shuffle=True,         # Usually testing data should not be shuffled\n    shuffle=False,\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.667856Z","iopub.execute_input":"2026-09-12T18:05:51.668097Z","iopub.status.idle":"2026-09-12T18:05:51.759815Z","shell.execute_reply.started":"2026-09-12T18:05:51.668076Z","shell.execute_reply":"2026-09-12T18:05:51.758971Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_exmaple(images,labels):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        if i < images.shape[0]:\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))\n            ax.axis('off')  # Turn off axis ticks/labels for clarity\n        ax.axis('on')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.76112Z","iopub.execute_input":"2026-09-12T18:05:51.761457Z","iopub.status.idle":"2026-09-12T18:05:51.768036Z","shell.execute_reply.started":"2026-09-12T18:05:51.761424Z","shell.execute_reply":"2026-09-12T18:05:51.767117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\ntrain_images.shape\nplot_exmaple(train_images,train_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:05:51.769253Z","iopub.execute_input":"2026-09-12T18:05:51.769559Z","iopub.status.idle":"2026-09-12T18:06:02.65211Z","shell.execute_reply.started":"2026-09-12T18:05:51.76953Z","shell.execute_reply":"2026-09-12T18:06:02.651079Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\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_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:02.653445Z","iopub.execute_input":"2026-09-12T18:06:02.654003Z","iopub.status.idle":"2026-09-12T18:06:02.660842Z","shell.execute_reply.started":"2026-09-12T18:06:02.653975Z","shell.execute_reply":"2026-09-12T18:06:02.660034Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_example_test(images):\n    plt.figure(figsize=(6, 6))\n    \n    if len(images.shape) == 4:\n        img = images[0]\n    else:\n        img = images\n        \n    if img.min() < 0:\n        img = (img + 1) / 2.0\n        \n    plt.imshow(img)\n    plt.axis('off')\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:02.662051Z","iopub.execute_input":"2026-09-12T18:06:02.662431Z","iopub.status.idle":"2026-09-12T18:06:02.674139Z","shell.execute_reply.started":"2026-09-12T18:06:02.662408Z","shell.execute_reply":"2026-09-12T18:06:02.673199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape\nplot_example_test(test_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:02.675257Z","iopub.execute_input":"2026-09-12T18:06:02.676096Z","iopub.status.idle":"2026-09-12T18:06:03.057082Z","shell.execute_reply.started":"2026-09-12T18:06:02.676066Z","shell.execute_reply":"2026-09-12T18:06:03.056406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#load model\nmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n#mark loaded layers as not trainable\nfor layer in model.layers:\n   layer.trainable = False\nprint(model.layers[-1].output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:03.058118Z","iopub.execute_input":"2026-09-12T18:06:03.058706Z","iopub.status.idle":"2026-09-12T18:06:03.367518Z","shell.execute_reply.started":"2026-09-12T18:06:03.058678Z","shell.execute_reply":"2026-09-12T18:06:03.366464Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#load model\nmodel_16_feature_extractor = VGG16(include_top=False, input_shape=(224, 224, 3))\nmodel_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:03.368822Z","iopub.execute_input":"2026-09-12T18:06:03.369882Z","iopub.status.idle":"2026-09-12T18:06:03.705164Z","shell.execute_reply.started":"2026-09-12T18:06:03.369854Z","shell.execute_reply":"2026-09-12T18:06:03.704363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" for index, layer in enumerate(model_16_feature_extractor.layers):\n\tprint(index, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:03.706254Z","iopub.execute_input":"2026-09-12T18:06:03.706544Z","iopub.status.idle":"2026-09-12T18:06:03.711685Z","shell.execute_reply.started":"2026-09-12T18:06:03.70652Z","shell.execute_reply":"2026-09-12T18:06:03.710646Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#load model\nmodel_16_top = VGG16(include_top=True, input_shape=(224, 224, 3))\nmodel_16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:03.713049Z","iopub.execute_input":"2026-09-12T18:06:03.713493Z","iopub.status.idle":"2026-09-12T18:06:05.896588Z","shell.execute_reply.started":"2026-09-12T18:06:03.713459Z","shell.execute_reply":"2026-09-12T18:06:05.895902Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:05.897926Z","iopub.execute_input":"2026-09-12T18:06:05.898208Z","iopub.status.idle":"2026-09-12T18:06:06.266716Z","shell.execute_reply.started":"2026-09-12T18:06:05.898184Z","shell.execute_reply":"2026-09-12T18:06:06.26589Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" for index, layer in enumerate(vgg16_model.layers):\n     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.268053Z","iopub.execute_input":"2026-09-12T18:06:06.268401Z","iopub.status.idle":"2026-09-12T18:06:06.274191Z","shell.execute_reply.started":"2026-09-12T18:06:06.268368Z","shell.execute_reply":"2026-09-12T18:06:06.273357Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(vgg16_model.layers[-7:]):\n    print(index, layer.name, layer.trainable)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.275355Z","iopub.execute_input":"2026-09-12T18:06:06.276098Z","iopub.status.idle":"2026-09-12T18:06:06.288537Z","shell.execute_reply.started":"2026-09-12T18:06:06.276073Z","shell.execute_reply":"2026-09-12T18:06:06.287788Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" for index, layer in enumerate(vgg16_model.layers[-7:]):layer.trainable = True\nprint(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.289522Z","iopub.execute_input":"2026-09-12T18:06:06.290125Z","iopub.status.idle":"2026-09-12T18:06:06.298055Z","shell.execute_reply.started":"2026-09-12T18:06:06.290101Z","shell.execute_reply":"2026-09-12T18:06:06.297023Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" for index, layer in enumerate(vgg16_model.layers):\n   if index >= 15:\n        layer.trainable = True\n\nfor index, layer in enumerate(vgg16_model.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.299364Z","iopub.execute_input":"2026-09-12T18:06:06.29998Z","iopub.status.idle":"2026-09-12T18:06:06.307006Z","shell.execute_reply.started":"2026-09-12T18:06:06.299941Z","shell.execute_reply":"2026-09-12T18:06:06.306131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.308232Z","iopub.execute_input":"2026-09-12T18:06:06.308619Z","iopub.status.idle":"2026-09-12T18:06:06.315959Z","shell.execute_reply.started":"2026-09-12T18:06:06.308564Z","shell.execute_reply":"2026-09-12T18:06:06.315106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        # layer.trainable = True #try to test\n    \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n    # output = Dense(1, activation='sigmoid')(flat1)\n    output = Dense(2, activation='softmax')(class4)\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.316993Z","iopub.execute_input":"2026-09-12T18:06:06.317294Z","iopub.status.idle":"2026-09-12T18:06:06.325127Z","shell.execute_reply.started":"2026-09-12T18:06:06.317265Z","shell.execute_reply":"2026-09-12T18:06:06.324297Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:06.32725Z","iopub.execute_input":"2026-09-12T18:06:06.32747Z","iopub.status.idle":"2026-09-12T18:06:08.502635Z","shell.execute_reply.started":"2026-09-12T18:06:06.327451Z","shell.execute_reply":"2026-09-12T18:06:08.501665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.503897Z","iopub.execute_input":"2026-09-12T18:06:08.504232Z","iopub.status.idle":"2026-09-12T18:06:08.510954Z","shell.execute_reply.started":"2026-09-12T18:06:08.5042Z","shell.execute_reply":"2026-09-12T18:06:08.509984Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nfor w in model_inceptionv3.trainable_weights:\n    print(w.name, K.count_params(w))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.512253Z","iopub.execute_input":"2026-09-12T18:06:08.51259Z","iopub.status.idle":"2026-09-12T18:06:08.522222Z","shell.execute_reply.started":"2026-09-12T18:06:08.51256Z","shell.execute_reply":"2026-09-12T18:06:08.521369Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.523282Z","iopub.execute_input":"2026-09-12T18:06:08.523586Z","iopub.status.idle":"2026-09-12T18:06:08.534268Z","shell.execute_reply.started":"2026-09-12T18:06:08.523556Z","shell.execute_reply":"2026-09-12T18:06:08.533479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.535322Z","iopub.execute_input":"2026-09-12T18:06:08.535829Z","iopub.status.idle":"2026-09-12T18:06:08.645552Z","shell.execute_reply.started":"2026-09-12T18:06:08.535786Z","shell.execute_reply":"2026-09-12T18:06:08.644824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5 first img: 1, 0, 1, 1, 0\nimages_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.646492Z","iopub.execute_input":"2026-09-12T18:06:08.646773Z","iopub.status.idle":"2026-09-12T18:06:08.6522Z","shell.execute_reply.started":"2026-09-12T18:06:08.646749Z","shell.execute_reply":"2026-09-12T18:06:08.651295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tf_keras.applications.vgg16 import VGG16\nfrom tf_keras.models import Model\nfrom tf_keras.layers import Flatten, Dense\nfrom tf_keras.optimizers import SGD\nfrom tf_keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras\n\nBATCH_SIZE = 64\nIMAGE_SIZE = (224, 224)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0)\n\ntrain_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/train/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE\n)\n\nval_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=IMAGE_SIZE\n)\n\nbase_model = VGG16(include_top=False, input_shape=(224, 224, 3))\nfor layer in base_model.layers:\n    layer.trainable = False\n\nflat = Flatten()(base_model.output)\ndense1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat)\noutput = Dense(1, activation='sigmoid')(dense1)\n\nvgg16_model = Model(inputs=base_model.inputs, outputs=output)\nopt = SGD(learning_rate=0.001, momentum=0.9)\nvgg16_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\nplot_losses = PlotLossesKeras()\nplot_losses._implements_train_batch_hooks = lambda: False\nplot_losses._implements_test_batch_hooks = lambda: False\nplot_losses._implements_predict_batch_hooks = lambda: False\n\nvgg16_model.reset_states()\nvgg16_history = vgg16_model.fit(\n    train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3,\n    verbose=1,\n    workers=4,\n    callbacks=[plot_losses]\n)\n\nval_loss, val_acc = vgg16_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint(f\"Validation Loss: {val_loss:.4f}\")\nprint(f\"Validation Accuracy: {val_acc * 100.0:.2f}%\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:06:08.653304Z","iopub.execute_input":"2026-09-12T18:06:08.653676Z","iopub.status.idle":"2026-09-12T18:15:50.984424Z","shell.execute_reply.started":"2026-09-12T18:06:08.653646Z","shell.execute_reply":"2026-09-12T18:15:50.983683Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":" # สุ่มรูปจากกลุ่ม test มา predict อย่างน้อย 10 รูป","metadata":{}},{"cell_type":"code","source":"import os\nimport glob\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tf_keras.preprocessing.image import load_img, img_to_array\n\ntest_dir = '/kaggle/working/test1/'\nif os.path.exists(test_dir) and len(glob.glob(test_dir + '*.jpg')) > 0:\n    test_files = glob.glob(test_dir + '*.jpg')\nelse:\n    test_files = glob.glob('dataset_dogs_vs_cats/test/*/*.jpg')\n\nrandom.seed(42)\nsampled_paths = random.sample(test_files, 10)\n\nsampled_images = []\nfor path in sampled_paths:\n    img = load_img(path, target_size=(224, 224))\n    sampled_images.append(img_to_array(img) / 255.0)\n\nsampled_images = np.array(sampled_images)\n\npreds = vgg16_model.predict(sampled_images, verbose=0)\n\nplt.figure(figsize=(15, 6))\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(sampled_images[i])\n    score = preds[i][0]\n    label = \"Dog\" if score >= 0.5 else \"Cat\"\n    prob = score if score >= 0.5 else (1.0 - score)\n    plt.title(f\"{label} ({prob * 100:.1f}%)\")\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T18:15:50.985729Z","iopub.execute_input":"2026-09-12T18:15:50.986066Z","iopub.status.idle":"2026-09-12T18:15:53.185313Z","shell.execute_reply.started":"2026-09-12T18:15:50.986033Z","shell.execute_reply":"2026-09-12T18:15:53.184298Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}}]}