{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-12T20:58:43.057913Z","iopub.execute_input":"2026-09-12T20:58:43.058425Z","iopub.status.idle":"2026-09-12T20:58:44.181874Z","shell.execute_reply.started":"2026-09-12T20:58:43.058400Z","shell.execute_reply":"2026-09-12T20:58:44.181106Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"/kaggle/input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:44.183948Z","iopub.execute_input":"2026-09-12T20:58:44.184598Z","iopub.status.idle":"2026-09-12T20:58:44.189714Z","shell.execute_reply.started":"2026-09-12T20:58:44.184571Z","shell.execute_reply":"2026-09-12T20:58:44.188876Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:44.190961Z","iopub.execute_input":"2026-09-12T20:58:44.191263Z","iopub.status.idle":"2026-09-12T20:58:44.324227Z","shell.execute_reply.started":"2026-09-12T20:58:44.191231Z","shell.execute_reply":"2026-09-12T20:58:44.323200Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:44.325498Z","iopub.execute_input":"2026-09-12T20:58:44.325783Z","iopub.status.idle":"2026-09-12T20:58:44.447024Z","shell.execute_reply.started":"2026-09-12T20:58:44.325753Z","shell.execute_reply":"2026-09-12T20:58:44.445987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/test1.zip\", \"r\") as z:\n    z.extractall(\".\")\n\nwith zipfile.ZipFile(\"/kaggle/input/competitions/dogs-vs-cats/train.zip\", \"r\") as z:\n    z.extractall(\".\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:44.448416Z","iopub.execute_input":"2026-09-12T20:58:44.448729Z","iopub.status.idle":"2026-09-12T20:58:53.738991Z","shell.execute_reply.started":"2026-09-12T20:58:44.448691Z","shell.execute_reply":"2026-09-12T20:58:53.738323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:53.739908Z","iopub.execute_input":"2026-09-12T20:58:53.740188Z","iopub.status.idle":"2026-09-12T20:58:53.863316Z","shell.execute_reply.started":"2026-09-12T20:58:53.740164Z","shell.execute_reply":"2026-09-12T20:58:53.862158Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:53.866782Z","iopub.execute_input":"2026-09-12T20:58:53.867015Z","iopub.status.idle":"2026-09-12T20:58:53.988235Z","shell.execute_reply.started":"2026-09-12T20:58:53.866987Z","shell.execute_reply":"2026-09-12T20:58:53.987534Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:53.989588Z","iopub.execute_input":"2026-09-12T20:58:53.989934Z","iopub.status.idle":"2026-09-12T20:58:54.174777Z","shell.execute_reply.started":"2026-09-12T20:58:53.989903Z","shell.execute_reply":"2026-09-12T20:58:54.173678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.176151Z","iopub.execute_input":"2026-09-12T20:58:54.177811Z","iopub.status.idle":"2026-09-12T20:58:54.353029Z","shell.execute_reply.started":"2026-09-12T20:58:54.177775Z","shell.execute_reply":"2026-09-12T20:58:54.352335Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.354205Z","iopub.execute_input":"2026-09-12T20:58:54.354585Z","iopub.status.idle":"2026-09-12T20:58:54.596244Z","shell.execute_reply.started":"2026-09-12T20:58:54.354554Z","shell.execute_reply":"2026-09-12T20:58:54.595489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.597622Z","iopub.execute_input":"2026-09-12T20:58:54.597964Z","iopub.status.idle":"2026-09-12T20:58:54.602054Z","shell.execute_reply.started":"2026-09-12T20:58:54.597935Z","shell.execute_reply":"2026-09-12T20:58:54.601308Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.603075Z","iopub.execute_input":"2026-09-12T20:58:54.603873Z","iopub.status.idle":"2026-09-12T20:58:54.617318Z","shell.execute_reply.started":"2026-09-12T20:58:54.603849Z","shell.execute_reply":"2026-09-12T20:58:54.616686Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.618357Z","iopub.execute_input":"2026-09-12T20:58:54.618650Z","iopub.status.idle":"2026-09-12T20:58:54.743749Z","shell.execute_reply.started":"2026-09-12T20:58:54.618627Z","shell.execute_reply":"2026-09-12T20:58:54.743004Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.745004Z","iopub.execute_input":"2026-09-12T20:58:54.745910Z","iopub.status.idle":"2026-09-12T20:58:54.937357Z","shell.execute_reply.started":"2026-09-12T20:58:54.745865Z","shell.execute_reply":"2026-09-12T20:58:54.936349Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:54.939191Z","iopub.execute_input":"2026-09-12T20:58:54.939560Z","iopub.status.idle":"2026-09-12T20:58:55.106316Z","shell.execute_reply.started":"2026-09-12T20:58:54.939529Z","shell.execute_reply":"2026-09-12T20:58:55.105049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\n# from matplotlib import pyplot as plt\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-12T20:58:55.107884Z","iopub.execute_input":"2026-09-12T20:58:55.108553Z","iopub.status.idle":"2026-09-12T20:58:56.890626Z","shell.execute_reply.started":"2026-09-12T20:58:55.108516Z","shell.execute_reply":"2026-09-12T20:58:56.889854Z"}},"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-12T20:58:56.891709Z","iopub.execute_input":"2026-09-12T20:58:56.892059Z","iopub.status.idle":"2026-09-12T20:58:57.536531Z","shell.execute_reply.started":"2026-09-12T20:58:56.892035Z","shell.execute_reply":"2026-09-12T20:58:57.535770Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:58:57.537626Z","iopub.execute_input":"2026-09-12T20:58:57.537920Z","iopub.status.idle":"2026-09-12T20:58:57.662290Z","shell.execute_reply.started":"2026-09-12T20:58:57.537897Z","shell.execute_reply":"2026-09-12T20:58:57.661544Z"}},"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-12T20:58:57.663593Z","iopub.execute_input":"2026-09-12T20:58:57.663966Z","iopub.status.idle":"2026-09-12T20:59:13.139523Z","shell.execute_reply.started":"2026-09-12T20:58:57.663937Z","shell.execute_reply":"2026-09-12T20:59:13.138723Z"}},"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-12T20:59:13.140436Z","iopub.execute_input":"2026-09-12T20:59:13.140952Z","iopub.status.idle":"2026-09-12T20:59:13.145839Z","shell.execute_reply.started":"2026-09-12T20:59:13.140928Z","shell.execute_reply":"2026-09-12T20:59:13.144897Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# > **define location of dataset**> \n\nfolder = 'train/' photos, labels = list(), list()","metadata":{}},{"cell_type":"markdown","source":"# enumerate files in the directory¶\nfor file in listdir(folder):","metadata":{}},{"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-12T20:59:13.146859Z","iopub.execute_input":"2026-09-12T20:59:13.147142Z","iopub.status.idle":"2026-09-12T20:59:19.239239Z","shell.execute_reply.started":"2026-09-12T20:59:13.147119Z","shell.execute_reply":"2026-09-12T20:59:19.238345Z"}},"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-12T20:59:19.243707Z","iopub.execute_input":"2026-09-12T20:59:19.244113Z","iopub.status.idle":"2026-09-12T20:59:21.481899Z","shell.execute_reply.started":"2026-09-12T20:59:19.244086Z","shell.execute_reply":"2026-09-12T20:59:21.481117Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# convert to a numpy arrays¶\nphotos = asarray(photos) labels = asarray(labels) print(photos.shape, labels.shape)","metadata":{}},{"cell_type":"markdown","source":"# save the reshaped photos¶\nsave('dogs_vs_cats_photos.npy', photos) save('dogs_vs_cats_labels.npy', labels)","metadata":{}},{"cell_type":"markdown","source":"# load and confirm the shape¶\nfrom numpy import load photos = load('dogs_vs_cats_photos.npy') labels = load('dogs_vs_cats_labels.npy')","metadata":{}},{"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-12T20:59:21.482715Z","iopub.execute_input":"2026-09-12T20:59:21.483119Z","iopub.status.idle":"2026-09-12T20:59:21.487436Z","shell.execute_reply.started":"2026-09-12T20:59:21.483061Z","shell.execute_reply":"2026-09-12T20:59:21.486531Z"}},"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-12T20:59:21.488430Z","iopub.execute_input":"2026-09-12T20:59:21.488845Z","iopub.status.idle":"2026-09-12T20:59:21.502236Z","shell.execute_reply.started":"2026-09-12T20:59:21.488823Z","shell.execute_reply":"2026-09-12T20:59:21.501427Z"}},"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-12T20:59:21.503324Z","iopub.execute_input":"2026-09-12T20:59:21.503784Z","iopub.status.idle":"2026-09-12T20:59:21.640860Z","shell.execute_reply.started":"2026-09-12T20:59:21.503751Z","shell.execute_reply":"2026-09-12T20:59:21.639813Z"}},"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-12T20:59:21.642286Z","iopub.execute_input":"2026-09-12T20:59:21.642657Z","iopub.status.idle":"2026-09-12T20:59:21.857548Z","shell.execute_reply.started":"2026-09-12T20:59:21.642628Z","shell.execute_reply":"2026-09-12T20:59:21.856790Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:21.858919Z","iopub.execute_input":"2026-09-12T20:59:21.859338Z","iopub.status.idle":"2026-09-12T20:59:21.989342Z","shell.execute_reply.started":"2026-09-12T20:59:21.859306Z","shell.execute_reply":"2026-09-12T20:59:21.988610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:21.990823Z","iopub.execute_input":"2026-09-12T20:59:21.991156Z","iopub.status.idle":"2026-09-12T20:59:22.124064Z","shell.execute_reply.started":"2026-09-12T20:59:21.991128Z","shell.execute_reply":"2026-09-12T20:59:22.123274Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test #validation","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:22.125635Z","iopub.execute_input":"2026-09-12T20:59:22.125970Z","iopub.status.idle":"2026-09-12T20:59:22.256717Z","shell.execute_reply.started":"2026-09-12T20:59:22.125928Z","shell.execute_reply":"2026-09-12T20:59:22.255983Z"}},"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-12T20:59:22.258037Z","iopub.execute_input":"2026-09-12T20:59:22.258426Z","iopub.status.idle":"2026-09-12T20:59:25.222936Z","shell.execute_reply.started":"2026-09-12T20:59:22.258398Z","shell.execute_reply":"2026-09-12T20:59:25.222006Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:25.224116Z","iopub.execute_input":"2026-09-12T20:59:25.224537Z","iopub.status.idle":"2026-09-12T20:59:25.228901Z","shell.execute_reply.started":"2026-09-12T20:59:25.224512Z","shell.execute_reply":"2026-09-12T20:59:25.228189Z"}},"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-12T20:59:25.229974Z","iopub.execute_input":"2026-09-12T20:59:25.230284Z","iopub.status.idle":"2026-09-12T20:59:25.715041Z","shell.execute_reply.started":"2026-09-12T20:59:25.230233Z","shell.execute_reply":"2026-09-12T20:59:25.714007Z"}},"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-12T20:59:25.716634Z","iopub.execute_input":"2026-09-12T20:59:25.717542Z","iopub.status.idle":"2026-09-12T20:59:26.073180Z","shell.execute_reply.started":"2026-09-12T20:59:25.717506Z","shell.execute_reply":"2026-09-12T20:59:26.072447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:26.074670Z","iopub.execute_input":"2026-09-12T20:59:26.075103Z","iopub.status.idle":"2026-09-12T20:59:31.603424Z","shell.execute_reply.started":"2026-09-12T20:59:26.075071Z","shell.execute_reply":"2026-09-12T20:59:31.602571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:31.604711Z","iopub.execute_input":"2026-09-12T20:59:31.605175Z","iopub.status.idle":"2026-09-12T20:59:31.621244Z","shell.execute_reply.started":"2026-09-12T20:59:31.605146Z","shell.execute_reply":"2026-09-12T20:59:31.620400Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial","metadata":{}},{"cell_type":"markdown","source":"# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:31.622574Z","iopub.execute_input":"2026-09-12T20:59:31.623042Z","iopub.status.idle":"2026-09-12T20:59:31.626619Z","shell.execute_reply.started":"2026-09-12T20:59:31.623016Z","shell.execute_reply":"2026-09-12T20:59:31.625838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom tf_keras.utils import to_categorical\nfrom tf_keras.models import Sequential\nfrom tf_keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom tf_keras.optimizers import SGD\nfrom tf_keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:31.627705Z","iopub.execute_input":"2026-09-12T20:59:31.628029Z","iopub.status.idle":"2026-09-12T20:59:32.840361Z","shell.execute_reply.started":"2026-09-12T20:59:31.627994Z","shell.execute_reply":"2026-09-12T20:59:32.839564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:32.841215Z","iopub.execute_input":"2026-09-12T20:59:32.841531Z","iopub.status.idle":"2026-09-12T20:59:34.488946Z","shell.execute_reply.started":"2026-09-12T20:59:32.841508Z","shell.execute_reply":"2026-09-12T20:59:34.488205Z"}},"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-12T20:59:34.489819Z","iopub.execute_input":"2026-09-12T20:59:34.490430Z","iopub.status.idle":"2026-09-12T20:59:34.618094Z","shell.execute_reply.started":"2026-09-12T20:59:34.490405Z","shell.execute_reply":"2026-09-12T20:59:34.617522Z"}},"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-12T20:59:34.619072Z","iopub.execute_input":"2026-09-12T20:59:34.619425Z","iopub.status.idle":"2026-09-12T20:59:34.678272Z","shell.execute_reply.started":"2026-09-12T20:59:34.619383Z","shell.execute_reply":"2026-09-12T20:59:34.677672Z"}},"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-12T20:59:34.679182Z","iopub.execute_input":"2026-09-12T20:59:34.679560Z","iopub.status.idle":"2026-09-12T20:59:34.684576Z","shell.execute_reply.started":"2026-09-12T20:59:34.679536Z","shell.execute_reply":"2026-09-12T20:59:34.683889Z"}},"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-12T20:59:34.685575Z","iopub.execute_input":"2026-09-12T20:59:34.685880Z","iopub.status.idle":"2026-09-12T20:59:34.770060Z","shell.execute_reply.started":"2026-09-12T20:59:34.685859Z","shell.execute_reply":"2026-09-12T20:59:34.769151Z"}},"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-12T20:59:34.771147Z","iopub.execute_input":"2026-09-12T20:59:34.771628Z","iopub.status.idle":"2026-09-12T20:59:34.777444Z","shell.execute_reply.started":"2026-09-12T20:59:34.771604Z","shell.execute_reply":"2026-09-12T20:59:34.776411Z"}},"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-12T20:59:34.778402Z","iopub.execute_input":"2026-09-12T20:59:34.778663Z","iopub.status.idle":"2026-09-12T20:59:34.791675Z","shell.execute_reply.started":"2026-09-12T20:59:34.778642Z","shell.execute_reply":"2026-09-12T20:59:34.790920Z"}},"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-12T20:59:34.792694Z","iopub.execute_input":"2026-09-12T20:59:34.792998Z","iopub.status.idle":"2026-09-12T20:59:34.900382Z","shell.execute_reply.started":"2026-09-12T20:59:34.792964Z","shell.execute_reply":"2026-09-12T20:59:34.899442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\ntype(datagen)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:34.901552Z","iopub.execute_input":"2026-09-12T20:59:34.901903Z","iopub.status.idle":"2026-09-12T20:59:34.907834Z","shell.execute_reply.started":"2026-09-12T20:59:34.901878Z","shell.execute_reply":"2026-09-12T20:59:34.906874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:34.909068Z","iopub.execute_input":"2026-09-12T20:59:34.909779Z","iopub.status.idle":"2026-09-12T20:59:35.057103Z","shell.execute_reply.started":"2026-09-12T20:59:34.909755Z","shell.execute_reply":"2026-09-12T20:59:35.056342Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hyperparameter => changable\nIMAGE_SIZE = (200, 200)\nBATCH_SIE = 64\nEPOCHS = 20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:35.058464Z","iopub.execute_input":"2026-09-12T20:59:35.058852Z","iopub.status.idle":"2026-09-12T20:59:35.063890Z","shell.execute_reply.started":"2026-09-12T20:59:35.058820Z","shell.execute_reply":"2026-09-12T20:59:35.063113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIE, \n        target_size=IMAGE_SIZE\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:35.064761Z","iopub.execute_input":"2026-09-12T20:59:35.065174Z","iopub.status.idle":"2026-09-12T20:59:35.680597Z","shell.execute_reply.started":"2026-09-12T20:59:35.065152Z","shell.execute_reply":"2026-09-12T20:59:35.679754Z"}},"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-12T20:59:35.681660Z","iopub.execute_input":"2026-09-12T20:59:35.681969Z","iopub.status.idle":"2026-09-12T20:59:35.689768Z","shell.execute_reply.started":"2026-09-12T20:59:35.681946Z","shell.execute_reply":"2026-09-12T20:59:35.688789Z"}},"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-12T20:59:35.690809Z","iopub.execute_input":"2026-09-12T20:59:35.691317Z","iopub.status.idle":"2026-09-12T20:59:36.487211Z","shell.execute_reply.started":"2026-09-12T20:59:35.691283Z","shell.execute_reply":"2026-09-12T20:59:36.486333Z"}},"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-12T20:59:36.488463Z","iopub.execute_input":"2026-09-12T20:59:36.489009Z","iopub.status.idle":"2026-09-12T20:59:36.495147Z","shell.execute_reply.started":"2026-09-12T20:59:36.488984Z","shell.execute_reply":"2026-09-12T20:59:36.494449Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tf_keras.models import Sequential\nfrom tf_keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tf_keras.optimizers import SGD\n\n# 1. นิยามโครงสร้างโมเดล Baseline (1 VGG block)\nmodel_1 = Sequential([\n    Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)),\n    MaxPooling2D((2, 2)),\n    Flatten(),\n    Dense(128, activation='relu', kernel_initializer='he_uniform'),\n    Dense(1, activation='sigmoid')\n])\n\n# 2. คอมไพล์โมเดล\nopt = SGD(learning_rate=0.001, momentum=0.9)\nmodel_1.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\nprint(\"Model 1 created and compiled successfully.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:36.496220Z","iopub.execute_input":"2026-09-12T20:59:36.497202Z","iopub.status.idle":"2026-09-12T20:59:36.562740Z","shell.execute_reply.started":"2026-09-12T20:59:36.497175Z","shell.execute_reply":"2026-09-12T20:59:36.561847Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install livelossplot\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\nfrom livelossplot import PlotLossesKeras\n\n# 1. กำหนดจำนวนรอบ (ป้องกัน NameError: EPOCHS)\nEPOCHS = 20\n\n# 2. ตรวจสอบและสร้าง model_1 อัตโนมัติหากยังไม่มีในหน่วยความจำ\nif 'model_1' not in globals():\n    model_1 = Sequential([\n        Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)),\n        MaxPooling2D((2, 2)),\n        Flatten(),\n        Dense(128, activation='relu', kernel_initializer='he_uniform'),\n        Dense(1, activation='sigmoid')\n    ])\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model_1.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# 3. Patch livelossplot สำหรับ tf_keras\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\n# 4. สั่งเริ่มเทรนโมเดล\nmodel_1.reset_states()\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=EPOCHS,\n    verbose=2,\n    workers=4,\n    callbacks=[plot_losses]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T20:59:36.563980Z","iopub.execute_input":"2026-09-12T20:59:36.564367Z","iopub.status.idle":"2026-09-12T21:12:24.829608Z","shell.execute_reply.started":"2026-09-12T20:59:36.564342Z","shell.execute_reply":"2026-09-12T21:12:24.828760Z"}},"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()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:24.830971Z","iopub.execute_input":"2026-09-12T21:12:24.831323Z","iopub.status.idle":"2026-09-12T21:12:24.836935Z","shell.execute_reply.started":"2026-09-12T21:12:24.831244Z","shell.execute_reply":"2026-09-12T21:12:24.836331Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:24.837851Z","iopub.execute_input":"2026-09-12T21:12:24.838140Z","iopub.status.idle":"2026-09-12T21:12:25.467941Z","shell.execute_reply.started":"2026-09-12T21:12:24.838117Z","shell.execute_reply":"2026-09-12T21:12:25.467270Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:25.468974Z","iopub.execute_input":"2026-09-12T21:12:25.469337Z","iopub.status.idle":"2026-09-12T21:12:42.576068Z","shell.execute_reply.started":"2026-09-12T21:12:25.469298Z","shell.execute_reply":"2026-09-12T21:12:42.575476Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:42.576951Z","iopub.execute_input":"2026-09-12T21:12:42.577208Z","iopub.status.idle":"2026-09-12T21:12:42.772999Z","shell.execute_reply.started":"2026-09-12T21:12:42.577183Z","shell.execute_reply":"2026-09-12T21:12:42.772314Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:42.778726Z","iopub.execute_input":"2026-09-12T21:12:42.779113Z","iopub.status.idle":"2026-09-12T21:12:42.786074Z","shell.execute_reply.started":"2026-09-12T21:12:42.779082Z","shell.execute_reply":"2026-09-12T21:12:42.785167Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:42.787112Z","iopub.execute_input":"2026-09-12T21:12:42.787773Z","iopub.status.idle":"2026-09-12T21:12:42.826853Z","shell.execute_reply.started":"2026-09-12T21:12:42.787725Z","shell.execute_reply":"2026-09-12T21:12:42.826224Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:42.827803Z","iopub.execute_input":"2026-09-12T21:12:42.828152Z","iopub.status.idle":"2026-09-12T21:12:42.833666Z","shell.execute_reply.started":"2026-09-12T21:12:42.828106Z","shell.execute_reply":"2026-09-12T21:12:42.832797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\nimport os\n\n# หาที่อยู่ของไฟล์ test1.zip\ntest_zip = '/kaggle/input/competitions/dogs-vs-cats/test1.zip'\nif not os.path.exists(test_zip):\n    test_zip = '/kaggle/input/dogs-vs-cats/test1.zip'\n\n# สั่งแตกไฟล์ออกมาไว้ที่ /kaggle/working/\nwith zipfile.ZipFile(test_zip, 'r') as z:\n    z.extractall('/kaggle/working')\n\nprint(\"แตกไฟล์ test1.zip เสร็จเรียบร้อย!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:42.834653Z","iopub.execute_input":"2026-09-12T21:12:42.835070Z","iopub.status.idle":"2026-09-12T21:12:45.680175Z","shell.execute_reply.started":"2026-09-12T21:12:42.835047Z","shell.execute_reply":"2026-09-12T21:12:45.679183Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import glob\n\n# ดึง path ของไฟล์รูปภาพทั้งหมดในโฟลเดอร์ test1\nimage_files = glob.glob('/kaggle/working/test1/*.jpg')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.681346Z","iopub.execute_input":"2026-09-12T21:12:45.681646Z","iopub.status.idle":"2026-09-12T21:12:45.708116Z","shell.execute_reply.started":"2026-09-12T21:12:45.681620Z","shell.execute_reply":"2026-09-12T21:12:45.707239Z"}},"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-12T21:12:45.709196Z","iopub.execute_input":"2026-09-12T21:12:45.709512Z","iopub.status.idle":"2026-09-12T21:12:45.715188Z","shell.execute_reply.started":"2026-09-12T21:12:45.709481Z","shell.execute_reply":"2026-09-12T21:12:45.714341Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport glob\nimport zipfile\nimport pandas as pd\n\n# 1. แตกไฟล์ test1.zip หากโฟลเดอร์ยังไม่มีรูป\nif not os.path.exists('/kaggle/working/test1') or len(glob.glob('/kaggle/working/test1/*.jpg')) == 0:\n    test_zip = '/kaggle/input/competitions/dogs-vs-cats/test1.zip'\n    if not os.path.exists(test_zip):\n        test_zip = '/kaggle/input/dogs-vs-cats/test1.zip'\n    \n    with zipfile.ZipFile(test_zip, 'r') as z:\n        z.extractall('/kaggle/working')\n    print(\"แตกไฟล์ test1.zip เรียบร้อยแล้ว\")\n\n# 2. ดึงรายชื่อรูปภาพทั้งหมด 12,500 รูป\nimage_files = glob.glob('/kaggle/working/test1/*.jpg')\n\n# 3. สร้าง DataFrame ใหม่จาก image_files\ndf = pd.DataFrame({'filename': image_files})\n\n# 4. แสดงข้อมูลสรุป\ndf.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.716084Z","iopub.execute_input":"2026-09-12T21:12:45.716362Z","iopub.status.idle":"2026-09-12T21:12:45.807496Z","shell.execute_reply.started":"2026-09-12T21:12:45.716342Z","shell.execute_reply":"2026-09-12T21:12:45.806808Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.808342Z","iopub.execute_input":"2026-09-12T21:12:45.809001Z","iopub.status.idle":"2026-09-12T21:12:45.815933Z","shell.execute_reply.started":"2026-09-12T21:12:45.808978Z","shell.execute_reply":"2026-09-12T21:12:45.815072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.823449Z","iopub.execute_input":"2026-09-12T21:12:45.823914Z","iopub.status.idle":"2026-09-12T21:12:45.836694Z","shell.execute_reply.started":"2026-09-12T21:12:45.823892Z","shell.execute_reply":"2026-09-12T21:12:45.835932Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.837504Z","iopub.execute_input":"2026-09-12T21:12:45.837688Z","iopub.status.idle":"2026-09-12T21:12:45.849759Z","shell.execute_reply.started":"2026-09-12T21:12:45.837671Z","shell.execute_reply":"2026-09-12T21:12:45.849042Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (200, 200)\n\n# datagen = 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                                 vertical_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\ntype(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.850776Z","iopub.execute_input":"2026-09-12T21:12:45.851115Z","iopub.status.idle":"2026-09-12T21:12:45.937089Z","shell.execute_reply.started":"2026-09-12T21:12:45.851093Z","shell.execute_reply":"2026-09-12T21:12:45.936496Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\ndef plot_exmaple(images, labels):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))  # Fixed: set_title instead of title\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.938126Z","iopub.execute_input":"2026-09-12T21:12:45.938478Z","iopub.status.idle":"2026-09-12T21:12:45.943992Z","shell.execute_reply.started":"2026-09-12T21:12:45.938455Z","shell.execute_reply":"2026-09-12T21:12:45.943130Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\nprint(train_images.shape, len(train_labels))\nplot_exmaple(train_images, train_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:45.944999Z","iopub.execute_input":"2026-09-12T21:12:45.945251Z","iopub.status.idle":"2026-09-12T21:12:49.209027Z","shell.execute_reply.started":"2026-09-12T21:12:45.945228Z","shell.execute_reply":"2026-09-12T21:12:49.207674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)\nval_labels[:8]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:49.210520Z","iopub.execute_input":"2026-09-12T21:12:49.210902Z","iopub.status.idle":"2026-09-12T21:12:52.814452Z","shell.execute_reply.started":"2026-09-12T21:12:49.210858Z","shell.execute_reply":"2026-09-12T21:12:52.813299Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images, indices):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(indices[i]))  # ตั้งค่า title ด้วย index จาก list/array indices\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:52.816166Z","iopub.execute_input":"2026-09-12T21:12:52.816616Z","iopub.status.idle":"2026-09-12T21:12:52.824963Z","shell.execute_reply.started":"2026-09-12T21:12:52.816562Z","shell.execute_reply":"2026-09-12T21:12:52.824064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()  # หรือ next(test_it)\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple_test(test_images, indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:52.825842Z","iopub.execute_input":"2026-09-12T21:12:52.826090Z","iopub.status.idle":"2026-09-12T21:12:56.380247Z","shell.execute_reply.started":"2026-09-12T21:12:52.826068Z","shell.execute_reply":"2026-09-12T21:12:56.379174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict \npreds = model_1.predict(test_it, steps=len(test_it), verbose=1)\ntype(preds), preds.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:12:56.381421Z","iopub.execute_input":"2026-09-12T21:12:56.381770Z","iopub.status.idle":"2026-09-12T21:13:17.188408Z","shell.execute_reply.started":"2026-09-12T21:12:56.381744Z","shell.execute_reply":"2026-09-12T21:13:17.187354Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:17.189533Z","iopub.execute_input":"2026-09-12T21:13:17.189939Z","iopub.status.idle":"2026-09-12T21:13:17.195907Z","shell.execute_reply.started":"2026-09-12T21:13:17.189914Z","shell.execute_reply":"2026-09-12T21:13:17.195188Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\n\n# 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\nsample_indices = np.random.choice(len(test_images), size=10, replace=False)\nsample_images = test_images[sample_indices]\n\n# 2. Predict \npredictions = model_1.predict(sample_images)\npredicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\nfig, axes = plt.subplots(2, 5, figsize=(15, 6))\naxes = axes.flatten()\n\nfor i, ax in enumerate(axes):\n    ax.imshow(sample_images[i])\n    # แสดง Index เดิม และ Class ที่ทายได้\n    ax.set_title(f\"Idx: {sample_indices[i]}\\nPred: {predicted_classes[i]}\")\n    ax.axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:17.197038Z","iopub.execute_input":"2026-09-12T21:13:17.197504Z","iopub.status.idle":"2026-09-12T21:13:18.102751Z","shell.execute_reply.started":"2026-09-12T21:13:17.197478Z","shell.execute_reply":"2026-09-12T21:13:18.101959Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Transfer Learning","metadata":{}},{"cell_type":"code","source":"# Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom tf_keras.utils import to_categorical\nfrom tf_keras.applications.vgg16 import VGG16\nfrom tf_keras.models import Model\nfrom tf_keras.layers import Dense, Flatten\nfrom tf_keras.optimizers import SGD\nfrom tf_keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model_vgg16():\n    # load model\n    model = VGG16(include_top=False, input_shape=(224, 224, 3))\n    \n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n        \n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n    output = Dense(1, activation='sigmoid')(class1)\n    \n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    \n    # compile model \n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\nmodel_vgg = define_model_vgg16()\nprint(\"create modal Success!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.103772Z","iopub.execute_input":"2026-09-12T21:13:18.104376Z","iopub.status.idle":"2026-09-12T21:13:18.908464Z","shell.execute_reply.started":"2026-09-12T21:13:18.104350Z","shell.execute_reply":"2026-09-12T21:13:18.907599Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model = VGG16(include_top=False, input_shape=(224, 224, 3))\n# mark loaded layers as not trainable\n# for layer in model.layers:\n#     layer.trainable = False\n\n# print(model.layers[-1].output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.909564Z","iopub.execute_input":"2026-09-12T21:13:18.910181Z","iopub.status.idle":"2026-09-12T21:13:18.914050Z","shell.execute_reply.started":"2026-09-12T21:13:18.910151Z","shell.execute_reply":"2026-09-12T21:13:18.913208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_feature_extractor = VGG16(include_top=False, input_shape=(224, 224, 3))\n# model_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.915099Z","iopub.execute_input":"2026-09-12T21:13:18.915464Z","iopub.status.idle":"2026-09-12T21:13:18.926375Z","shell.execute_reply.started":"2026-09-12T21:13:18.915442Z","shell.execute_reply":"2026-09-12T21:13:18.925686Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model_16_feature_extractor.layers):\n# \t\tprint(index, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.927350Z","iopub.execute_input":"2026-09-12T21:13:18.928078Z","iopub.status.idle":"2026-09-12T21:13:18.937677Z","shell.execute_reply.started":"2026-09-12T21:13:18.928056Z","shell.execute_reply":"2026-09-12T21:13:18.937046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_top = VGG16(include_top=True, input_shape=(224, 224, 3))\n# model_16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.938470Z","iopub.execute_input":"2026-09-12T21:13:18.938707Z","iopub.status.idle":"2026-09-12T21:13:18.948984Z","shell.execute_reply.started":"2026-09-12T21:13:18.938688Z","shell.execute_reply":"2026-09-12T21:13:18.948293Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:18.949992Z","iopub.execute_input":"2026-09-12T21:13:18.950329Z","iopub.status.idle":"2026-09-12T21:13:19.367194Z","shell.execute_reply.started":"2026-09-12T21:13:18.950299Z","shell.execute_reply":"2026-09-12T21:13:19.366614Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:19.368118Z","iopub.execute_input":"2026-09-12T21:13:19.368477Z","iopub.status.idle":"2026-09-12T21:13:19.373517Z","shell.execute_reply.started":"2026-09-12T21:13:19.368453Z","shell.execute_reply":"2026-09-12T21:13:19.372808Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tf_keras.preprocessing.image import ImageDataGenerator\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:19.374394Z","iopub.execute_input":"2026-09-12T21:13:19.374730Z","iopub.status.idle":"2026-09-12T21:13:20.342043Z","shell.execute_reply.started":"2026-09-12T21:13:19.374700Z","shell.execute_reply":"2026-09-12T21:13:20.341070Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras\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\nprint(id(vgg16_model))\nvgg16_model.reset_states()\n\nvgg16_model_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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:13:20.343100Z","iopub.execute_input":"2026-09-12T21:13:20.344537Z","iopub.status.idle":"2026-09-12T21:22:11.268737Z","shell.execute_reply.started":"2026-09-12T21:13:20.344510Z","shell.execute_reply":"2026-09-12T21:22:11.267127Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(vgg16_model_history)\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:22:11.270356Z","iopub.execute_input":"2026-09-12T21:22:11.270750Z","iopub.status.idle":"2026-09-12T21:23:25.434815Z","shell.execute_reply.started":"2026-09-12T21:22:11.270722Z","shell.execute_reply":"2026-09-12T21:23:25.434121Z"}},"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-12T21:23:25.435843Z","iopub.execute_input":"2026-09-12T21:23:25.436163Z","iopub.status.idle":"2026-09-12T21:23:25.443437Z","shell.execute_reply.started":"2026-09-12T21:23:25.436139Z","shell.execute_reply":"2026-09-12T21:23:25.442585Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tf_keras.applications.inception_v3 import InceptionV3\nfrom tf_keras.models import Model\nfrom tf_keras.layers import Flatten, Dense\nfrom tf_keras.optimizers import SGD\n\n# Define CNN model using InceptionV3\ndef define_model_inceptionv3():\n    # Load InceptionV3 pre-trained on ImageNet\n    base_model = InceptionV3(include_top=False, input_shape=(224, 224, 3))\n    \n    # Freeze base model layers\n    for layer in base_model.layers:\n        layer.trainable = False\n        \n    # Add new classifier layers\n    flat1 = Flatten()(base_model.output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n    output = Dense(1, activation='sigmoid')(class2)\n    \n    # Define new model\n    model = Model(inputs=base_model.inputs, outputs=output)\n    \n    # Compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# Instantiate model\nmodel_inceptionv3 = define_model_inceptionv3()\nprint(f\"Model ID: {id(model_inceptionv3)}\")\n# model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:23:25.444456Z","iopub.execute_input":"2026-09-12T21:23:25.444740Z","iopub.status.idle":"2026-09-12T21:23:28.323104Z","shell.execute_reply.started":"2026-09-12T21:23:25.444709Z","shell.execute_reply":"2026-09-12T21:23:28.322434Z"}},"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-12T21:23:28.323957Z","iopub.execute_input":"2026-09-12T21:23:28.325109Z","iopub.status.idle":"2026-09-12T21:23:30.570248Z","shell.execute_reply.started":"2026-09-12T21:23:28.325069Z","shell.execute_reply":"2026-09-12T21:23:30.569348Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:23:30.571283Z","iopub.execute_input":"2026-09-12T21:23:30.571588Z","iopub.status.idle":"2026-09-12T21:23:30.578337Z","shell.execute_reply.started":"2026-09-12T21:23:30.571555Z","shell.execute_reply":"2026-09-12T21:23:30.577493Z"}},"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))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:23:30.579607Z","iopub.execute_input":"2026-09-12T21:23:30.579870Z","iopub.status.idle":"2026-09-12T21:23:30.622569Z","shell.execute_reply.started":"2026-09-12T21:23:30.579849Z","shell.execute_reply":"2026-09-12T21:23:30.621839Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras\n\n# Patch livelossplot callback hooks for tf_keras\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\n# Fit InceptionV3 model\nmodel_inceptionv3.reset_states()\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3,\n    verbose=1,\n    workers=4,\n    callbacks=[plot_losses]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:23:30.623586Z","iopub.execute_input":"2026-09-12T21:23:30.623906Z","iopub.status.idle":"2026-09-12T21:27:56.300578Z","shell.execute_reply.started":"2026-09-12T21:23:30.623884Z","shell.execute_reply":"2026-09-12T21:27:56.299674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:27:56.301753Z","iopub.execute_input":"2026-09-12T21:27:56.302057Z","iopub.status.idle":"2026-09-12T21:27:56.309688Z","shell.execute_reply.started":"2026-09-12T21:27:56.302024Z","shell.execute_reply":"2026-09-12T21:27:56.308992Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\n# best_model = 'vgg16_model.hdf5'\n# my_model.save(best_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:27:56.310724Z","iopub.execute_input":"2026-09-12T21:27:56.311046Z","iopub.status.idle":"2026-09-12T21:28:16.340207Z","shell.execute_reply.started":"2026-09-12T21:27:56.311011Z","shell.execute_reply":"2026-09-12T21:28:16.339570Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:28:16.341134Z","iopub.execute_input":"2026-09-12T21:28:16.341507Z","iopub.status.idle":"2026-09-12T21:28:16.429909Z","shell.execute_reply.started":"2026-09-12T21:28:16.341481Z","shell.execute_reply":"2026-09-12T21:28:16.429215Z"}},"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-12T21:28:16.430883Z","iopub.execute_input":"2026-09-12T21:28:16.431214Z","iopub.status.idle":"2026-09-12T21:28:16.436616Z","shell.execute_reply.started":"2026-09-12T21:28:16.431190Z","shell.execute_reply":"2026-09-12T21:28:16.435678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\n\n# Resize input images to match expected shape (224, 224)\nimages_to_predict_224 = tf.image.resize(images_to_predict, (224, 224))\n\n# Predict\nprobs = model_inceptionv3.predict(images_to_predict_224, verbose=1)\nprint(probs.shape)\nprint(probs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:28:16.437692Z","iopub.execute_input":"2026-09-12T21:28:16.438000Z","iopub.status.idle":"2026-09-12T21:28:18.431688Z","shell.execute_reply.started":"2026-09-12T21:28:16.437978Z","shell.execute_reply":"2026-09-12T21:28:18.430916Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"markdown","source":"# เทรนให้ได้ Val accuracy อย่างน้อย 0.85","metadata":{}},{"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}%\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T21:28:18.432591Z","iopub.execute_input":"2026-09-12T21:28:18.432999Z","iopub.status.idle":"2026-09-12T21:37:51.061461Z","shell.execute_reply.started":"2026-09-12T21:28:18.432976Z","shell.execute_reply":"2026-09-12T21:37:51.060744Z"}},"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-12T21:37:51.062474Z","iopub.execute_input":"2026-09-12T21:37:51.062828Z","iopub.status.idle":"2026-09-12T21:37:53.661634Z","shell.execute_reply.started":"2026-09-12T21:37:51.062804Z","shell.execute_reply":"2026-09-12T21:37:53.660813Z"}},"outputs":[],"execution_count":null}]}