{"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\n# import os\n# for 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-19T17:30:58.685635Z","iopub.execute_input":"2026-09-19T17:30:58.68599Z","iopub.status.idle":"2026-09-19T17:30:58.690191Z","shell.execute_reply.started":"2026-09-19T17:30:58.685962Z","shell.execute_reply":"2026-09-19T17:30:58.689528Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"/kaggle/input\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:30:58.692652Z","iopub.execute_input":"2026-09-19T17:30:58.692939Z","iopub.status.idle":"2026-09-19T17:30:58.707031Z","shell.execute_reply.started":"2026-09-19T17:30:58.692917Z","shell.execute_reply":"2026-09-19T17:30:58.706227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:30:58.708215Z","iopub.execute_input":"2026-09-19T17:30:58.708481Z","iopub.status.idle":"2026-09-19T17:30:58.915006Z","shell.execute_reply.started":"2026-09-19T17:30:58.708459Z","shell.execute_reply":"2026-09-19T17:30:58.913957Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:30:58.916493Z","iopub.execute_input":"2026-09-19T17:30:58.916768Z","iopub.status.idle":"2026-09-19T17:30:59.110802Z","shell.execute_reply.started":"2026-09-19T17:30:58.916703Z","shell.execute_reply":"2026-09-19T17:30:59.109778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\nif os.path.exists(\"/kaggle/input\"):\n    print(\"Folders found:\", os.listdir(\"/kaggle/input\"))\nelse:\n    print(\"Directory /kaggle/input does not exist.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:30:59.113009Z","iopub.execute_input":"2026-09-19T17:30:59.113624Z","iopub.status.idle":"2026-09-19T17:30:59.11865Z","shell.execute_reply.started":"2026-09-19T17:30:59.113591Z","shell.execute_reply":"2026-09-19T17:30:59.117975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport 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(\".\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:30:59.119696Z","iopub.execute_input":"2026-09-19T17:30:59.120066Z","iopub.status.idle":"2026-09-19T17:31:08.032027Z","shell.execute_reply.started":"2026-09-19T17:30:59.12004Z","shell.execute_reply":"2026-09-19T17:31:08.031036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.034233Z","iopub.execute_input":"2026-09-19T17:31:08.034533Z","iopub.status.idle":"2026-09-19T17:31:08.226909Z","shell.execute_reply.started":"2026-09-19T17:31:08.034509Z","shell.execute_reply":"2026-09-19T17:31:08.225894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.228783Z","iopub.execute_input":"2026-09-19T17:31:08.229454Z","iopub.status.idle":"2026-09-19T17:31:08.423845Z","shell.execute_reply.started":"2026-09-19T17:31:08.229415Z","shell.execute_reply":"2026-09-19T17:31:08.422826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.425425Z","iopub.execute_input":"2026-09-19T17:31:08.426367Z","iopub.status.idle":"2026-09-19T17:31:08.66485Z","shell.execute_reply.started":"2026-09-19T17:31:08.426326Z","shell.execute_reply":"2026-09-19T17:31:08.664063Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.666452Z","iopub.execute_input":"2026-09-19T17:31:08.666859Z","iopub.status.idle":"2026-09-19T17:31:08.976881Z","shell.execute_reply.started":"2026-09-19T17:31:08.666826Z","shell.execute_reply":"2026-09-19T17:31:08.976126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.980045Z","iopub.execute_input":"2026-09-19T17:31:08.980719Z","iopub.status.idle":"2026-09-19T17:31:08.984394Z","shell.execute_reply.started":"2026-09-19T17:31:08.980687Z","shell.execute_reply":"2026-09-19T17:31:08.983606Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:08.985452Z","iopub.execute_input":"2026-09-19T17:31:08.985796Z","iopub.status.idle":"2026-09-19T17:31:09.25564Z","shell.execute_reply.started":"2026-09-19T17:31:08.985766Z","shell.execute_reply":"2026-09-19T17:31:09.254807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:09.25714Z","iopub.execute_input":"2026-09-19T17:31:09.257573Z","iopub.status.idle":"2026-09-19T17:31:09.491311Z","shell.execute_reply.started":"2026-09-19T17:31:09.257537Z","shell.execute_reply":"2026-09-19T17:31:09.490512Z"}},"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-19T17:31:09.492936Z","iopub.execute_input":"2026-09-19T17:31:09.493575Z","iopub.status.idle":"2026-09-19T17:31:10.160376Z","shell.execute_reply.started":"2026-09-19T17:31:09.493543Z","shell.execute_reply":"2026-09-19T17:31:10.159501Z"}},"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-19T17:31:10.161377Z","iopub.execute_input":"2026-09-19T17:31:10.161675Z","iopub.status.idle":"2026-09-19T17:31:10.704578Z","shell.execute_reply.started":"2026-09-19T17:31:10.161644Z","shell.execute_reply":"2026-09-19T17:31:10.703965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:10.705597Z","iopub.execute_input":"2026-09-19T17:31:10.705968Z","iopub.status.idle":"2026-09-19T17:31:10.902306Z","shell.execute_reply.started":"2026-09-19T17:31:10.705943Z","shell.execute_reply":"2026-09-19T17:31:10.901504Z"}},"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-19T17:31:10.903808Z","iopub.execute_input":"2026-09-19T17:31:10.904165Z","iopub.status.idle":"2026-09-19T17:31:10.909411Z","shell.execute_reply.started":"2026-09-19T17:31:10.904133Z","shell.execute_reply":"2026-09-19T17:31:10.908469Z"}},"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-19T17:31:10.910418Z","iopub.execute_input":"2026-09-19T17:31:10.910716Z","iopub.status.idle":"2026-09-19T17:31:10.924468Z","shell.execute_reply.started":"2026-09-19T17:31:10.910694Z","shell.execute_reply":"2026-09-19T17:31:10.923711Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/' photos, labels = list(), list()","metadata":{}},{"cell_type":"markdown","source":"# enumerate files in the directory\nfor file in listdir(folder): # determine class output = 0.0 if file.startswith('dog'): output = 1.0 # load image photo = load_img(folder + file, target_size=(200, 200)) # convert to numpy array photo = img_to_array(photo) # store photos.append(photo) labels.append(output)","metadata":{}},{"cell_type":"code","source":"import os\n\nimg_dir = None\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if any(f.lower().endswith(('.jpg', '.jpeg', '.png')) for f in files):\n        img_dir = root\n        break\n\nprint(\"Image directory found:\", img_dir)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:10.925431Z","iopub.execute_input":"2026-09-19T17:31:10.92639Z","iopub.status.idle":"2026-09-19T17:31:10.955658Z","shell.execute_reply.started":"2026-09-19T17:31:10.926368Z","shell.execute_reply":"2026-09-19T17:31:10.955116Z"}},"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-19T17:31:10.956556Z","iopub.execute_input":"2026-09-19T17:31:10.956852Z","iopub.status.idle":"2026-09-19T17:31:10.960499Z","shell.execute_reply.started":"2026-09-19T17:31:10.956831Z","shell.execute_reply":"2026-09-19T17:31:10.959955Z"}},"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-19T17:31:10.961596Z","iopub.execute_input":"2026-09-19T17:31:10.961901Z","iopub.status.idle":"2026-09-19T17:31:10.973557Z","shell.execute_reply.started":"2026-09-19T17:31:10.96188Z","shell.execute_reply":"2026-09-19T17:31:10.972805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:10.974374Z","iopub.execute_input":"2026-09-19T17:31:10.974672Z","iopub.status.idle":"2026-09-19T17:31:11.177556Z","shell.execute_reply.started":"2026-09-19T17:31:10.974638Z","shell.execute_reply":"2026-09-19T17:31:11.176535Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:11.179032Z","iopub.execute_input":"2026-09-19T17:31:11.179389Z","iopub.status.idle":"2026-09-19T17:31:11.371217Z","shell.execute_reply.started":"2026-09-19T17:31:11.179348Z","shell.execute_reply":"2026-09-19T17:31:11.370404Z"}},"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-19T17:31:11.37253Z","iopub.execute_input":"2026-09-19T17:31:11.372935Z","iopub.status.idle":"2026-09-19T17:31:11.566784Z","shell.execute_reply.started":"2026-09-19T17:31:11.372906Z","shell.execute_reply":"2026-09-19T17:31:11.566018Z"}},"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-19T17:31:11.568083Z","iopub.execute_input":"2026-09-19T17:31:11.568647Z","iopub.status.idle":"2026-09-19T17:31:14.630137Z","shell.execute_reply.started":"2026-09-19T17:31:11.568617Z","shell.execute_reply":"2026-09-19T17:31:14.629376Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:14.631129Z","iopub.execute_input":"2026-09-19T17:31:14.631914Z","iopub.status.idle":"2026-09-19T17:31:14.636142Z","shell.execute_reply.started":"2026-09-19T17:31:14.631885Z","shell.execute_reply":"2026-09-19T17:31:14.635493Z"}},"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-19T17:31:14.636942Z","iopub.execute_input":"2026-09-19T17:31:14.637163Z","iopub.status.idle":"2026-09-19T17:31:17.542573Z","shell.execute_reply.started":"2026-09-19T17:31:14.637142Z","shell.execute_reply":"2026-09-19T17:31:17.541643Z"}},"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-19T17:31:17.544024Z","iopub.execute_input":"2026-09-19T17:31:17.544647Z","iopub.status.idle":"2026-09-19T17:31:17.982649Z","shell.execute_reply.started":"2026-09-19T17:31:17.544616Z","shell.execute_reply":"2026-09-19T17:31:17.981931Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:17.988681Z","iopub.execute_input":"2026-09-19T17:31:17.988958Z","iopub.status.idle":"2026-09-19T17:31:21.427412Z","shell.execute_reply.started":"2026-09-19T17:31:17.98893Z","shell.execute_reply":"2026-09-19T17:31:21.426519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.428796Z","iopub.execute_input":"2026-09-19T17:31:21.429104Z","iopub.status.idle":"2026-09-19T17:31:21.434394Z","shell.execute_reply.started":"2026-09-19T17:31:21.429069Z","shell.execute_reply":"2026-09-19T17:31:21.433534Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.435472Z","iopub.execute_input":"2026-09-19T17:31:21.435808Z","iopub.status.idle":"2026-09-19T17:31:21.448589Z","shell.execute_reply.started":"2026-09-19T17:31:21.435771Z","shell.execute_reply":"2026-09-19T17:31:21.447911Z"}},"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\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.449673Z","iopub.execute_input":"2026-09-19T17:31:21.450011Z","iopub.status.idle":"2026-09-19T17:31:21.462721Z","shell.execute_reply.started":"2026-09-19T17:31:21.449976Z","shell.execute_reply":"2026-09-19T17:31:21.462011Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def define_model_1():\n    model = Sequential()\n    model.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n    model.add(MaxPooling2D((2, 2)))\n    model.add(Flatten())\n    model.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n    model.add(Dense(1, activation='sigmoid'))\n    \n    # compile model (แก้ lr เป็น learning_rate แล้ว)\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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.463843Z","iopub.execute_input":"2026-09-19T17:31:21.464598Z","iopub.status.idle":"2026-09-19T17:31:21.476562Z","shell.execute_reply.started":"2026-09-19T17:31:21.464561Z","shell.execute_reply":"2026-09-19T17:31:21.476018Z"}},"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-19T17:31:21.477483Z","iopub.execute_input":"2026-09-19T17:31:21.477762Z","iopub.status.idle":"2026-09-19T17:31:21.546366Z","shell.execute_reply.started":"2026-09-19T17:31:21.477713Z","shell.execute_reply":"2026-09-19T17:31:21.545613Z"}},"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-19T17:31:21.547317Z","iopub.execute_input":"2026-09-19T17:31:21.54761Z","iopub.status.idle":"2026-09-19T17:31:21.553127Z","shell.execute_reply.started":"2026-09-19T17:31:21.547579Z","shell.execute_reply":"2026-09-19T17:31:21.552369Z"}},"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-19T17:31:21.55393Z","iopub.execute_input":"2026-09-19T17:31:21.554144Z","iopub.status.idle":"2026-09-19T17:31:21.607809Z","shell.execute_reply.started":"2026-09-19T17:31:21.554125Z","shell.execute_reply":"2026-09-19T17:31:21.606997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.608766Z","iopub.execute_input":"2026-09-19T17:31:21.609243Z","iopub.status.idle":"2026-09-19T17:31:21.656781Z","shell.execute_reply.started":"2026-09-19T17:31:21.609223Z","shell.execute_reply":"2026-09-19T17:31:21.656208Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# The Functional API - new cell\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense\n\n# explicitly define the input tensor topology\nmy_inputs = Input(shape=(200, 200, 3))\n\n# Construct the forward pass of the computational graph\nx1 = Conv2D(32, (3, 3), activation='relu')(my_inputs)\n\nx1 = Conv2D(64, (3, 3), activation='relu')(x1)\n\nx2 = MaxPooling2D((2, 2))(x1)\n\nx3 = Flatten()(x2)\n\nx5 = Dense(256, activation='relu')(x3)\n\nx4 = Dense(128, activation='relu')(x5)\n\n# Define the output tensor with the target objective function representation\nmy_outputs = Dense(2, activation='softmax')(x4)\n\n# Instantiate the formal model architecture\nmodel = Model(inputs=my_inputs, outputs=my_outputs)\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.657548Z","iopub.execute_input":"2026-09-19T17:31:21.657831Z","iopub.status.idle":"2026-09-19T17:31:21.720569Z","shell.execute_reply.started":"2026-09-19T17:31:21.657811Z","shell.execute_reply":"2026-09-19T17:31:21.720017Z"}},"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-19T17:31:21.721334Z","iopub.execute_input":"2026-09-19T17:31:21.721657Z","iopub.status.idle":"2026-09-19T17:31:21.726438Z","shell.execute_reply.started":"2026-09-19T17:31:21.721606Z","shell.execute_reply":"2026-09-19T17:31:21.725806Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.727525Z","iopub.execute_input":"2026-09-19T17:31:21.727836Z","iopub.status.idle":"2026-09-19T17:31:21.92586Z","shell.execute_reply.started":"2026-09-19T17:31:21.727806Z","shell.execute_reply":"2026-09-19T17:31:21.924807Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = 224 #for vgg16\nBATCH_SIZE = 64\nEPOCHS = 30","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.927392Z","iopub.execute_input":"2026-09-19T17:31:21.927805Z","iopub.status.idle":"2026-09-19T17:31:21.93229Z","shell.execute_reply.started":"2026-09-19T17:31:21.927764Z","shell.execute_reply":"2026-09-19T17:31:21.931667Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use another dataset\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# 1. Instantiate the generator with the validation_split ratio\ndatagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True,\n    validation_split=0.2  # Defined here at initialization\n)\n\ntrain_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/train'\n\n# 2. Extract the training subset (80% of data)\ntrain_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='training',     # Explicitly request the training partition\n    shuffle=True           # Stochastic sampling is standard for training\n)\n\n# 3. Extract the validation subset (20% of data)\nval_it = datagen.flow_from_directory(\n    train_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE),\n    subset='validation',   # Explicitly request the validation partition\n    shuffle=False          # Disable shuffle to maintain index alignment for metrics\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:21.933324Z","iopub.execute_input":"2026-09-19T17:31:21.934003Z","iopub.status.idle":"2026-09-19T17:31:29.492434Z","shell.execute_reply.started":"2026-09-19T17:31:21.93397Z","shell.execute_reply":"2026-09-19T17:31:29.4918Z"}},"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-19T17:31:29.493299Z","iopub.execute_input":"2026-09-19T17:31:29.493532Z","iopub.status.idle":"2026-09-19T17:31:29.499874Z","shell.execute_reply.started":"2026-09-19T17:31:29.493512Z","shell.execute_reply":"2026-09-19T17:31:29.499136Z"}},"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-19T17:31:29.500975Z","iopub.execute_input":"2026-09-19T17:31:29.501325Z","iopub.status.idle":"2026-09-19T17:31:29.514772Z","shell.execute_reply.started":"2026-09-19T17:31:29.501293Z","shell.execute_reply":"2026-09-19T17:31:29.513967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\n# model_1.reset_states()\n# history_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#     callbacks = [PlotLossesKeras()]\n#     )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.515838Z","iopub.execute_input":"2026-09-19T17:31:29.516173Z","iopub.status.idle":"2026-09-19T17:31:29.52614Z","shell.execute_reply.started":"2026-09-19T17:31:29.516142Z","shell.execute_reply":"2026-09-19T17:31:29.525215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.527265Z","iopub.execute_input":"2026-09-19T17:31:29.527858Z","iopub.status.idle":"2026-09-19T17:31:29.539615Z","shell.execute_reply.started":"2026-09-19T17:31:29.527826Z","shell.execute_reply":"2026-09-19T17:31:29.5387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n# _, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\n# print('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.541205Z","iopub.execute_input":"2026-09-19T17:31:29.542378Z","iopub.status.idle":"2026-09-19T17:31:29.552969Z","shell.execute_reply.started":"2026-09-19T17:31:29.542342Z","shell.execute_reply":"2026-09-19T17:31:29.552312Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Create test datagenerator from 308-456 Dogs vs Cats","metadata":{}},{"cell_type":"code","source":"ls /kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.555665Z","iopub.execute_input":"2026-09-19T17:31:29.556184Z","iopub.status.idle":"2026-09-19T17:31:29.765431Z","shell.execute_reply.started":"2026-09-19T17:31:29.556152Z","shell.execute_reply":"2026-09-19T17:31:29.764588Z"}},"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\ntest_path = '/kaggle/input/datasets/kasikrit/308-456-dogs-vs-cats-dataset/dataset_dogs_vs_cats/test'\n\nprint(test_path)\n# # List all .jpg files in the directory (adjust the pattern if needed)\n# image_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# # Check if images were found\n# if not image_files:\n#     print(\"No images found. Please verify the directory and file extensions.\")\n    \n# # Create a DataFrame with the file paths\n# test_df = 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-19T17:31:29.766879Z","iopub.execute_input":"2026-09-19T17:31:29.767183Z","iopub.status.idle":"2026-09-19T17:31:29.77332Z","shell.execute_reply.started":"2026-09-19T17:31:29.767153Z","shell.execute_reply":"2026-09-19T17:31:29.772441Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.774267Z","iopub.execute_input":"2026-09-19T17:31:29.774549Z","iopub.status.idle":"2026-09-19T17:31:29.791176Z","shell.execute_reply.started":"2026-09-19T17:31:29.774529Z","shell.execute_reply":"2026-09-19T17:31:29.79055Z"}},"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-19T17:31:29.79212Z","iopub.execute_input":"2026-09-19T17:31:29.792629Z","iopub.status.idle":"2026-09-19T17:31:29.802565Z","shell.execute_reply.started":"2026-09-19T17:31:29.792594Z","shell.execute_reply":"2026-09-19T17:31:29.801924Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.803604Z","iopub.execute_input":"2026-09-19T17:31:29.803955Z","iopub.status.idle":"2026-09-19T17:31:29.813426Z","shell.execute_reply.started":"2026-09-19T17:31:29.803933Z","shell.execute_reply":"2026-09-19T17:31:29.812797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.814306Z","iopub.execute_input":"2026-09-19T17:31:29.814602Z","iopub.status.idle":"2026-09-19T17:31:29.824358Z","shell.execute_reply.started":"2026-09-19T17:31:29.814568Z","shell.execute_reply":"2026-09-19T17:31:29.823564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.825411Z","iopub.execute_input":"2026-09-19T17:31:29.826329Z","iopub.status.idle":"2026-09-19T17:31:29.835277Z","shell.execute_reply.started":"2026-09-19T17:31:29.826298Z","shell.execute_reply":"2026-09-19T17:31:29.834635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Create test data generator\n# from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# # Initialize your ImageDataGenerator (modify parameters as needed)\n# datagen_test = ImageDataGenerator(rescale=1./255,\n#                                  vertical_flip=True)\n\n# # Create the data generator using the DataFrame\n# test_it = datagen_test.flow_from_dataframe(\n#     dataframe=test_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=BATCH_SIZE,\n#     class_mode=None,       # Since there are no labels\n#     # shuffle=True,         # Usually testing data should not be shuffled\n#     shuffle=False,\n# )\n\n# type(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.836173Z","iopub.execute_input":"2026-09-19T17:31:29.836449Z","iopub.status.idle":"2026-09-19T17:31:29.846809Z","shell.execute_reply.started":"2026-09-19T17:31:29.836429Z","shell.execute_reply":"2026-09-19T17:31:29.846012Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.847661Z","iopub.execute_input":"2026-09-19T17:31:29.847937Z","iopub.status.idle":"2026-09-19T17:31:29.861618Z","shell.execute_reply.started":"2026-09-19T17:31:29.847906Z","shell.execute_reply":"2026-09-19T17:31:29.860801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 1. Instantiate the generator with the validation_split ratio\ntest_datagen = ImageDataGenerator(\n    rescale=1.0/255.0,\n    horizontal_flip=True\n)\n\ntest_it = test_datagen.flow_from_directory(\n    test_path,\n    class_mode='binary',\n    batch_size=BATCH_SIZE,\n    target_size=(IMAGE_SIZE, IMAGE_SIZE)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:29.863484Z","iopub.execute_input":"2026-09-19T17:31:29.863724Z","iopub.status.idle":"2026-09-19T17:31:31.281866Z","shell.execute_reply.started":"2026-09-19T17:31:29.863704Z","shell.execute_reply":"2026-09-19T17:31:31.28126Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\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            ax.axis(\"on\")\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-19T17:31:31.282722Z","iopub.execute_input":"2026-09-19T17:31:31.283147Z","iopub.status.idle":"2026-09-19T17:31:31.289014Z","shell.execute_reply.started":"2026-09-19T17:31:31.28311Z","shell.execute_reply":"2026-09-19T17:31:31.288333Z"}},"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-19T17:31:31.290021Z","iopub.execute_input":"2026-09-19T17:31:31.290324Z","iopub.status.idle":"2026-09-19T17:31:37.432367Z","shell.execute_reply.started":"2026-09-19T17:31:31.290282Z","shell.execute_reply":"2026-09-19T17:31:37.43151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:37.43337Z","iopub.execute_input":"2026-09-19T17:31:37.433695Z","iopub.status.idle":"2026-09-19T17:31:42.89554Z","shell.execute_reply.started":"2026-09-19T17:31:37.433672Z","shell.execute_reply":"2026-09-19T17:31:42.893542Z"}},"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-19T17:31:42.896647Z","iopub.execute_input":"2026-09-19T17:31:42.897512Z","iopub.status.idle":"2026-09-19T17:31:42.902955Z","shell.execute_reply.started":"2026-09-19T17:31:42.897467Z","shell.execute_reply":"2026-09-19T17:31:42.902112Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images, test_labels = test_it.__next__()  # หรือ next(test_it)\nprint(f\"{test_images.shape=}, {test_labels.shape}\")\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple(test_images, test_labels)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:42.904183Z","iopub.execute_input":"2026-09-19T17:31:42.904587Z","iopub.status.idle":"2026-09-19T17:31:48.937468Z","shell.execute_reply.started":"2026-09-19T17:31:42.904554Z","shell.execute_reply":"2026-09-19T17:31:48.935811Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import numpy as np\n\n\n# # 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\n# sample_indices = np.random.choice(len(test_images), size=10, replace=False)\n# sample_images = test_images[sample_indices]\n\n# # 2. Predict \n# predictions = model_1.predict(sample_images)\n# predicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# # 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\n# fig, axes = plt.subplots(2, 5, figsize=(15, 6))\n# axes = axes.flatten()\n\n# for 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\n# plt.tight_layout()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:48.938366Z","iopub.execute_input":"2026-09-19T17:31:48.938586Z","iopub.status.idle":"2026-09-19T17:31:48.942614Z","shell.execute_reply.started":"2026-09-19T17:31:48.938565Z","shell.execute_reply":"2026-09-19T17:31:48.941939Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2026-09-13\n# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:48.943852Z","iopub.execute_input":"2026-09-19T17:31:48.944319Z","iopub.status.idle":"2026-09-19T17:31:48.958942Z","shell.execute_reply.started":"2026-09-19T17:31:48.944287Z","shell.execute_reply":"2026-09-19T17:31:48.95831Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it), id(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:48.959946Z","iopub.execute_input":"2026-09-19T17:31:48.960342Z","iopub.status.idle":"2026-09-19T17:31:48.973102Z","shell.execute_reply.started":"2026-09-19T17:31:48.960311Z","shell.execute_reply":"2026-09-19T17:31:48.972347Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\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\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nweights_path = \"/root/.keras/models/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\"\nif os.path.exists(weights_path):\n    os.remove(weights_path)\n\n# Hyperparameter => changable\nIMAGE_SIZE = 224\nBATCH_SIE = 64\nEPOCHS = 20\n\n# define cnn model\ndef define_model_vgg16():\n    model = VGG16(include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 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    opt = SGD(learning_rate=0.001, momentum=0.9)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\nvgg16 = define_model_vgg16()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:48.974147Z","iopub.execute_input":"2026-09-19T17:31:48.974632Z","iopub.status.idle":"2026-09-19T17:31:49.649795Z","shell.execute_reply.started":"2026-09-19T17:31:48.974601Z","shell.execute_reply":"2026-09-19T17:31:49.649163Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_vgg16_top = VGG16(include_top=True,\n                        input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)\n                       )\nmodel_vgg16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:49.650606Z","iopub.execute_input":"2026-09-19T17:31:49.65099Z","iopub.status.idle":"2026-09-19T17:31:51.81995Z","shell.execute_reply.started":"2026-09-19T17:31:49.65096Z","shell.execute_reply":"2026-09-19T17:31:51.818995Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load model\nmodel_16_feature_extractor = VGG16(include_top=False,\n                                   input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)\n                                  )\nmodel_16_feature_extractor.summary() #feature extractor as a backbone","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:51.821068Z","iopub.execute_input":"2026-09-19T17:31:51.821691Z","iopub.status.idle":"2026-09-19T17:31:52.092061Z","shell.execute_reply.started":"2026-09-19T17:31:51.821665Z","shell.execute_reply":"2026-09-19T17:31:52.09123Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n\t\tprint(index, layer.trainable, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.093328Z","iopub.execute_input":"2026-09-19T17:31:52.094012Z","iopub.status.idle":"2026-09-19T17:31:52.098549Z","shell.execute_reply.started":"2026-09-19T17:31:52.093986Z","shell.execute_reply":"2026-09-19T17:31:52.097647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model_16_feature_extractor.layers):\n    if index <= 15:\n        layer.trainable = False\n\nfor index, layer in enumerate(model_16_feature_extractor.layers):\n    print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.099456Z","iopub.execute_input":"2026-09-19T17:31:52.099705Z","iopub.status.idle":"2026-09-19T17:31:52.112576Z","shell.execute_reply.started":"2026-09-19T17:31:52.099684Z","shell.execute_reply":"2026-09-19T17:31:52.111805Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.113494Z","iopub.execute_input":"2026-09-19T17:31:52.113797Z","iopub.status.idle":"2026-09-19T17:31:52.128955Z","shell.execute_reply.started":"2026-09-19T17:31:52.113766Z","shell.execute_reply":"2026-09-19T17:31:52.128294Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Use functional API\nflat1 = Flatten()(model_16_feature_extractor.layers[-1].output)\nprint(flat1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.129816Z","iopub.execute_input":"2026-09-19T17:31:52.130351Z","iopub.status.idle":"2026-09-19T17:31:52.141919Z","shell.execute_reply.started":"2026-09-19T17:31:52.130322Z","shell.execute_reply":"2026-09-19T17:31:52.141004Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\nprint(class1.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.142967Z","iopub.execute_input":"2026-09-19T17:31:52.143397Z","iopub.status.idle":"2026-09-19T17:31:52.162226Z","shell.execute_reply.started":"2026-09-19T17:31:52.143377Z","shell.execute_reply":"2026-09-19T17:31:52.161604Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output = Dense(1, activation='sigmoid')(class1)\nprint(output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.162972Z","iopub.execute_input":"2026-09-19T17:31:52.163315Z","iopub.status.idle":"2026-09-19T17:31:52.175602Z","shell.execute_reply.started":"2026-09-19T17:31:52.163292Z","shell.execute_reply":"2026-09-19T17:31:52.174918Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define new model to be trained\nmodel_vgg16 = Model(inputs=model_16_feature_extractor.inputs, outputs=output)\n\n# compile model (แก้ไขจาก lr เป็น learning_rate)\nopt = SGD(learning_rate=0.001, momentum=0.9)\n\nmodel_vgg16.compile(optimizer=opt,\n                    loss='binary_crossentropy',\n                    metrics=['accuracy']\n                   )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.176561Z","iopub.execute_input":"2026-09-19T17:31:52.176891Z","iopub.status.idle":"2026-09-19T17:31:52.189002Z","shell.execute_reply.started":"2026-09-19T17:31:52.176869Z","shell.execute_reply":"2026-09-19T17:31:52.188142Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.189915Z","iopub.execute_input":"2026-09-19T17:31:52.190251Z","iopub.status.idle":"2026-09-19T17:31:52.2167Z","shell.execute_reply.started":"2026-09-19T17:31:52.190218Z","shell.execute_reply":"2026-09-19T17:31:52.216072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.217557Z","iopub.execute_input":"2026-09-19T17:31:52.217866Z","iopub.status.idle":"2026-09-19T17:31:52.22241Z","shell.execute_reply.started":"2026-09-19T17:31:52.217845Z","shell.execute_reply":"2026-09-19T17:31:52.221718Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# model_vgg16 = define_model_vgg16()\n# print(model_vgg16)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.223368Z","iopub.execute_input":"2026-09-19T17:31:52.224149Z","iopub.status.idle":"2026-09-19T17:31:52.234043Z","shell.execute_reply.started":"2026-09-19T17:31:52.224114Z","shell.execute_reply":"2026-09-19T17:31:52.233371Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nimport tensorflow as tf\n\n# 1. Verify that TensorFlow can communicate with the GPU hardware\nphysical_devices = tf.config.list_physical_devices('GPU')\nprint(f\"Hardware status: {len(physical_devices)} GPU(s) detected.\")\n\nif len(physical_devices) > 0:\n    try:\n        tf.config.experimental.set_memory_growth(physical_devices[0], True)\n    except Exception as e:\n        print(f\"Memory growth configuration failed: {e}\")\n\n    # 2. Explicitly bind the execution to the primary GPU\n    with tf.device('/GPU:0'):\n        print(f\"Model ID: {id(model_vgg16)}\")\n        \n        # ตัดคำสั่ง reset_states() ออกไปแล้ว\n        \n        model_vgg16_history = model_vgg16.fit(\n            train_it, \n            steps_per_epoch=len(train_it),\n            validation_data=val_it,\n            validation_steps=len(val_it),\n            epochs=1, \n            verbose=1,\n            callbacks=[PlotLossesKeras()] # คำสั่งนี้จะสร้างกราฟเหมือนรูปของอาจารย์\n        )\nelse:\n    print(\"WARNING: No GPU detected. Execution will proceed on the CPU, which will be significantly slower.\")\n    # Fallback to standard execution\n    model_vgg16_history = model_vgg16.fit(\n        train_it, \n        steps_per_epoch=len(train_it),\n        validation_data=val_it,\n        validation_steps=len(val_it),\n        epochs=1, \n        verbose=1,\n        callbacks=[PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:31:52.234882Z","iopub.execute_input":"2026-09-19T17:31:52.235165Z","iopub.status.idle":"2026-09-19T17:33:44.115563Z","shell.execute_reply.started":"2026-09-19T17:31:52.23513Z","shell.execute_reply":"2026-09-19T17:33:44.114974Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:33:44.116567Z","iopub.execute_input":"2026-09-19T17:33:44.116861Z","iopub.status.idle":"2026-09-19T17:33:44.288563Z","shell.execute_reply.started":"2026-09-19T17:33:44.116838Z","shell.execute_reply":"2026-09-19T17:33:44.288022Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_vgg16.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:33:44.289696Z","iopub.execute_input":"2026-09-19T17:33:44.290466Z","iopub.status.idle":"2026-09-19T17:34:04.888867Z","shell.execute_reply.started":"2026-09-19T17:33:44.29044Z","shell.execute_reply":"2026-09-19T17:34:04.888227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model for the test set\n_, test_acc = model_vgg16.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (test_acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:34:04.89026Z","iopub.execute_input":"2026-09-19T17:34:04.890589Z","iopub.status.idle":"2026-09-19T17:34:38.827179Z","shell.execute_reply.started":"2026-09-19T17:34:04.890565Z","shell.execute_reply":"2026-09-19T17:34:38.826474Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. โหลด test_it ใหม่ให้ขนาดภาพเป็น (224, 224) ตรงกับโมเดล และปิด shuffle\ntest_it = test_it.image_data_generator.flow_from_directory(\n    test_it.directory,\n    target_size=(224, 224),\n    batch_size=test_it.batch_size,\n    class_mode='binary',\n    shuffle=False\n)\n\n# 2. ดึงเฉลยจริง\ny_true = test_it.classes\n\n# 3. ทำนายผล (ไม่ต้องใส่ steps ก็ได้ Keras จะคำนวณให้อัตโนมัติ)\nprobabilities = model_vgg16.predict(test_it, verbose=1).squeeze()\nprint(\"Probabilities shape:\", probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:34:38.833986Z","iopub.execute_input":"2026-09-19T17:34:38.834295Z","iopub.status.idle":"2026-09-19T17:35:14.294881Z","shell.execute_reply.started":"2026-09-19T17:34:38.834272Z","shell.execute_reply":"2026-09-19T17:35:14.294216Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:14.295845Z","iopub.execute_input":"2026-09-19T17:35:14.296158Z","iopub.status.idle":"2026-09-19T17:35:14.302152Z","shell.execute_reply.started":"2026-09-19T17:35:14.296135Z","shell.execute_reply":"2026-09-19T17:35:14.301324Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:14.303078Z","iopub.execute_input":"2026-09-19T17:35:14.303397Z","iopub.status.idle":"2026-09-19T17:35:14.317364Z","shell.execute_reply.started":"2026-09-19T17:35:14.303372Z","shell.execute_reply":"2026-09-19T17:35:14.316695Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_pred = (probabilities > 0.5).astype(int)\n\ntarget_names = list(test_it.class_indices.keys())\n\nreport = classification_report(y_true, y_pred, target_names=target_names, digits=4)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:14.31825Z","iopub.execute_input":"2026-09-19T17:35:14.31857Z","iopub.status.idle":"2026-09-19T17:35:14.338405Z","shell.execute_reply.started":"2026-09-19T17:35:14.318543Z","shell.execute_reply":"2026-09-19T17:35:14.337561Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:14.339389Z","iopub.execute_input":"2026-09-19T17:35:14.339688Z","iopub.status.idle":"2026-09-19T17:35:14.344713Z","shell.execute_reply.started":"2026-09-19T17:35:14.339667Z","shell.execute_reply":"2026-09-19T17:35:14.344033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 1. Aggregate sufficient samples from the iterator\nimages_list = []\nlabels_list = []\n\n# Fetch 2 batches (2 * 64 = 128 samples) to ensure we have pool > 100\nfor _ in range(2):\n    batch_images, batch_labels = next(test_it)\n    images_list.append(batch_images)\n    labels_list.append(batch_labels)\n\n# Concatenate into a single tensor\nall_images = np.concatenate(images_list, axis=0)\nall_labels = np.concatenate(labels_list, axis=0)\n\n# 2. Stochastically sample 100 unique indices\nnp.random.seed(42) # For reproducibility\nrandom_indices = np.random.choice(all_images.shape[0], size=100, replace=False)\n\nsample_images = all_images[random_indices]\nsample_labels = all_labels[random_indices]\n\n# 3. Execute the forward pass\n# Squeeze is used to convert shape (100, 1) to (100,)\nprobabilities = model_vgg16.predict(sample_images).squeeze()\n\n# 4. Thresholding (Assuming standard mapping: 0 = Cat, 1 = Dog)\npredictions = (probabilities > 0.5).astype(int)\nclass_mapping = {0: 'Cat', 1: 'Dog'}\n\nprint(\"Done.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:14.346461Z","iopub.execute_input":"2026-09-19T17:35:14.346717Z","iopub.status.idle":"2026-09-19T17:35:16.667517Z","shell.execute_reply.started":"2026-09-19T17:35:14.346697Z","shell.execute_reply":"2026-09-19T17:35:16.666864Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Initialize a 10x10 matrix visualization\nfig, axes = plt.subplots(10, 10, figsize=(20, 22))\naxes = axes.flatten()\n\nfor i in range(100):\n    ax = axes[i]\n    \n    # Isolate image tensor. \n    # NOTE: If your VGG16 preprocessor applies mean-centering (caffe style) \n    # instead of standard [0,1] scaling, you must reverse it here for correct plt.imshow() rendering.\n    # We assume standard [0, 1] or [0, 255] spatial tensors below.\n    img = sample_images[i]\n    if img.max() > 1.0 or img.min() < 0:\n        # Simple normalization for display purposes\n        img = (img - img.min()) / (img.max() - img.min())\n        \n    ax.imshow(img)\n    ax.axis('off')\n    \n    # Extract structural labels\n    gt_class = class_mapping[int(sample_labels[i])]\n    pred_class = class_mapping[predictions[i]]\n    prob = probabilities[i]\n    \n    # Apply conditional color coding (Green for True Positives/Negatives, Red for False Positives/Negatives)\n    text_color = 'darkgreen' if gt_class == pred_class else 'darkred'\n    \n    title_str = f\"GT: {gt_class}\\nPred: {pred_class}\\nProb: {prob:.3f}\"\n    ax.set_title(title_str, color=text_color, fontsize=9, pad=4)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:16.668411Z","iopub.execute_input":"2026-09-19T17:35:16.66878Z","iopub.status.idle":"2026-09-19T17:35:22.647989Z","shell.execute_reply.started":"2026-09-19T17:35:16.668711Z","shell.execute_reply":"2026-09-19T17:35:22.646883Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"InceptionV3","metadata":{}},{"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(learning_rate=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-19T17:53:17.609124Z","iopub.execute_input":"2026-09-19T17:53:17.609421Z","iopub.status.idle":"2026-09-19T17:53:17.627886Z","shell.execute_reply.started":"2026-09-19T17:53:17.609391Z","shell.execute_reply":"2026-09-19T17:53:17.62725Z"}},"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-19T17:35:22.663367Z","iopub.execute_input":"2026-09-19T17:35:22.663687Z","iopub.status.idle":"2026-09-19T17:35:24.365877Z","shell.execute_reply.started":"2026-09-19T17:35:22.663662Z","shell.execute_reply":"2026-09-19T17:35:24.365199Z"}},"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-19T17:35:24.366816Z","iopub.execute_input":"2026-09-19T17:35:24.36757Z","iopub.status.idle":"2026-09-19T17:35:24.373143Z","shell.execute_reply.started":"2026-09-19T17:35:24.367544Z","shell.execute_reply":"2026-09-19T17:35:24.37228Z"}},"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-19T17:35:24.374027Z","iopub.execute_input":"2026-09-19T17:35:24.374312Z","iopub.status.idle":"2026-09-19T17:35:24.387691Z","shell.execute_reply.started":"2026-09-19T17:35:24.37428Z","shell.execute_reply":"2026-09-19T17:35:24.386922Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import layers\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten\nfrom keras.optimizers import SGD\n\nbase_model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n\nfor layer in base_model.layers:\n    layer.trainable = False\n\ninputs = layers.Input(shape=(None, None, 3))\nx = layers.Resizing(299, 299)(inputs)\nx = base_model(x, training=False)\nflat1 = Flatten()(x)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n\nmodel_inceptionv3 = Model(inputs=inputs, outputs=output)\n\nopt = SGD(learning_rate=0.001, momentum=0.9)\nmodel_inceptionv3.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\nhistory_inceptionv3 = model_inceptionv3.fit(\n    train_it, \n    steps_per_epoch=100,\n    validation_data=val_it,\n    validation_steps=30,\n    epochs=3, \n    verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:35:24.388843Z","iopub.execute_input":"2026-09-19T17:35:24.389113Z","iopub.status.idle":"2026-09-19T17:37:09.829671Z","shell.execute_reply.started":"2026-09-19T17:35:24.389092Z","shell.execute_reply":"2026-09-19T17:37:09.829057Z"}},"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-19T17:37:09.830625Z","iopub.execute_input":"2026-09-19T17:37:09.830921Z","iopub.status.idle":"2026-09-19T17:37:09.838481Z","shell.execute_reply.started":"2026-09-19T17:37:09.830898Z","shell.execute_reply":"2026-09-19T17:37:09.837566Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:37:09.839498Z","iopub.execute_input":"2026-09-19T17:37:09.83985Z","iopub.status.idle":"2026-09-19T17:37:09.854558Z","shell.execute_reply.started":"2026-09-19T17:37:09.839828Z","shell.execute_reply":"2026-09-19T17:37:09.853857Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:37:09.855644Z","iopub.execute_input":"2026-09-19T17:37:09.856203Z","iopub.status.idle":"2026-09-19T17:37:09.868562Z","shell.execute_reply.started":"2026-09-19T17:37:09.85618Z","shell.execute_reply":"2026-09-19T17:37:09.867787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # mark loaded layers as not trainable\n# for index, layer in enumerate(model.layers[:15]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = False\n    \n# for index, layer in enumerate(model.layers[15:]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = True","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:37:09.869421Z","iopub.execute_input":"2026-09-19T17:37:09.869597Z","iopub.status.idle":"2026-09-19T17:37:09.882511Z","shell.execute_reply.started":"2026-09-19T17:37:09.869579Z","shell.execute_reply":"2026-09-19T17:37:09.881867Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_it = test_it.image_data_generator.flow_from_directory(\n    test_it.directory,\n    class_mode=test_it.class_mode,\n    batch_size=test_it.batch_size,\n    target_size=(299, 299),\n    shuffle=False  \n)\n\n_, acc = model_inceptionv3.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:37:09.883303Z","iopub.execute_input":"2026-09-19T17:37:09.883756Z","iopub.status.idle":"2026-09-19T17:38:01.016413Z","shell.execute_reply.started":"2026-09-19T17:37:09.883707Z","shell.execute_reply":"2026-09-19T17:38:01.015595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = test_it.__next__()\n\nprint(images.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:38:01.017526Z","iopub.execute_input":"2026-09-19T17:38:01.017915Z","iopub.status.idle":"2026-09-19T17:38:01.226322Z","shell.execute_reply.started":"2026-09-19T17:38:01.01789Z","shell.execute_reply":"2026-09-19T17:38:01.225451Z"}},"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-19T17:38:01.227217Z","iopub.execute_input":"2026-09-19T17:38:01.22743Z","iopub.status.idle":"2026-09-19T17:38:01.233005Z","shell.execute_reply.started":"2026-09-19T17:38:01.227409Z","shell.execute_reply":"2026-09-19T17:38:01.232088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:38:01.233953Z","iopub.execute_input":"2026-09-19T17:38:01.234271Z","iopub.status.idle":"2026-09-19T17:38:10.457072Z","shell.execute_reply.started":"2026-09-19T17:38:01.234236Z","shell.execute_reply":"2026-09-19T17:38:10.456346Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"ฝึกใช้ pre-trained models อย่างน้อย 3 โมเดล เลือกเอาตามความชอบ \nAccuracy สำหรับ test set ขั้นต่ำ 0.97","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom sklearn.metrics import classification_report, accuracy_score\n\ndef build_custom_model(base_model):\n    inputs = layers.Input(shape=(None, None, 3))\n    x = layers.Resizing(224, 224)(inputs)\n    x = base_model(x, training=False)\n    x = layers.GlobalAveragePooling2D()(x)\n    x = layers.Dropout(0.2)(x)\n    outputs = layers.Dense(1, activation='sigmoid')(x)\n    return models.Model(inputs, outputs)\n\ndef evaluate_result(model, model_name):\n    test_it.reset()\n    probs = model.predict(test_it, verbose=1).flatten()\n    preds = (probs > 0.5).astype(int)\n    y_true = test_it.classes\n    target_names = list(test_it.class_indices.keys())\n    \n    print(f\"\\n================ Classification Report: {model_name} ================\")\n    print(classification_report(y_true, preds, target_names=target_names, digits=4))\n    acc = accuracy_score(y_true, preds)\n    status = \"PASSED (>= 0.97)\" if acc >= 0.97 else \"FAILED\"\n    print(f\"--> Test Accuracy: {acc:.4f} [{status}]\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:38:10.458194Z","iopub.execute_input":"2026-09-19T17:38:10.458841Z","iopub.status.idle":"2026-09-19T17:38:10.46653Z","shell.execute_reply.started":"2026-09-19T17:38:10.458804Z","shell.execute_reply":"2026-09-19T17:38:10.465904Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#MobileNetV2\nfrom tensorflow.keras.applications import MobileNetV2\n\nbase_mob = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_mob.trainable = False\n\nmodel_1 = build_custom_model(base_mob)\n\nmodel_1.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_1.fit(train_it, steps_per_epoch=150, validation_data=val_it, validation_steps=30, epochs=3, verbose=1)\n\nbase_mob.trainable = True\nfor layer in base_mob.layers[:-40]:\n    layer.trainable = False\n\nmodel_1.compile(optimizer=tf.keras.optimizers.Adam(1e-5), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_1.fit(train_it, steps_per_epoch=150, validation_data=val_it, validation_steps=30, epochs=3, verbose=1)\n\nevaluate_result(model_1, \"MobileNetV2\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:38:10.467618Z","iopub.execute_input":"2026-09-19T17:38:10.46804Z","iopub.status.idle":"2026-09-19T17:43:33.191231Z","shell.execute_reply.started":"2026-09-19T17:38:10.468005Z","shell.execute_reply":"2026-09-19T17:43:33.190315Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\ntest_it.reset()\npreds_1 = (model_1.predict(test_it, verbose=0).flatten() > 0.5).astype(int)\nacc_1 = accuracy_score(y_true, preds_1)\ncm_1 = confusion_matrix(y_true, preds_1)\n\nplt.figure(figsize=(6, 5))\nsns.heatmap(cm_1, annot=True, fmt='d', cmap='Blues', xticklabels=target_names, yticklabels=target_names, cbar=False)\nplt.title(f'Confusion Matrix: MobileNetV2\\nAccuracy: {acc_1:.4f} ({acc_1*100:.2f}%)', fontsize=12)\nplt.ylabel('Actual Label')\nplt.xlabel('Predicted Label')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:43:33.192252Z","iopub.execute_input":"2026-09-19T17:43:33.192563Z","iopub.status.idle":"2026-09-19T17:44:07.013523Z","shell.execute_reply.started":"2026-09-19T17:43:33.19254Z","shell.execute_reply":"2026-09-19T17:44:07.012872Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ResNet50V2\nfrom tensorflow.keras.applications import ResNet50V2\n\nbase_res = ResNet50V2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_res.trainable = False\n\nmodel_2 = build_custom_model(base_res)\nmodel_2.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_2.fit(train_it, steps_per_epoch=120, validation_data=val_it, validation_steps=30, epochs=2, verbose=1)\n\nbase_res.trainable = True\nfor layer in base_res.layers[:-30]:\n    layer.trainable = False\n\nmodel_2.compile(optimizer=tf.keras.optimizers.Adam(1e-5), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_2.fit(train_it, steps_per_epoch=120, validation_data=val_it, validation_steps=30, epochs=2, verbose=1)\n\nevaluate_result(model_2, \"ResNet50V2\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:44:07.014545Z","iopub.execute_input":"2026-09-19T17:44:07.014842Z","iopub.status.idle":"2026-09-19T17:47:55.093469Z","shell.execute_reply.started":"2026-09-19T17:44:07.014813Z","shell.execute_reply":"2026-09-19T17:47:55.09281Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\ntest_it.reset()\npreds_2 = (model_2.predict(test_it, verbose=0).flatten() > 0.5).astype(int)\nacc_2 = accuracy_score(y_true, preds_2)\ncm_2 = confusion_matrix(y_true, preds_2)\n\nplt.figure(figsize=(6, 5))\nsns.heatmap(cm_2, annot=True, fmt='d', cmap='Greens', xticklabels=target_names, yticklabels=target_names, cbar=False)\nplt.title(f'Confusion Matrix: ResNet50V2\\nAccuracy: {acc_2:.4f} ({acc_2*100:.2f}%)', fontsize=12)\nplt.ylabel('Actual Label')\nplt.xlabel('Predicted Label')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:47:55.094429Z","iopub.execute_input":"2026-09-19T17:47:55.095057Z","iopub.status.idle":"2026-09-19T17:48:23.197305Z","shell.execute_reply.started":"2026-09-19T17:47:55.095029Z","shell.execute_reply":"2026-09-19T17:48:23.196463Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#EfficientNetB0\nfrom tensorflow.keras.applications import EfficientNetB0\nbase_eff = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(224, 224, 3))\nbase_eff.trainable = False\n\ninputs = layers.Input(shape=(None, None, 3))\nx = layers.Resizing(224, 224)(inputs)\nx = layers.Lambda(lambda img: img * 255.0)(x)\nx = base_eff(x, training=False)\nx = layers.GlobalAveragePooling2D()(x)\nx = layers.Dropout(0.2)(x)\noutputs = layers.Dense(1, activation='sigmoid')(x)\nmodel_3 = models.Model(inputs, outputs)\n\nmodel_3.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_3.fit(train_it, steps_per_epoch=120, validation_data=val_it, validation_steps=30, epochs=2, verbose=1)\n\nbase_eff.trainable = True\nfor layer in base_eff.layers[:-30]:\n    layer.trainable = False\n\nmodel_3.compile(optimizer=tf.keras.optimizers.Adam(1e-5), loss='binary_crossentropy', metrics=['accuracy'])\nmodel_3.fit(train_it, steps_per_epoch=120, validation_data=val_it, validation_steps=30, epochs=2, verbose=1)\n\nevaluate_result(model_3, \"EfficientNetB0\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:48:23.198296Z","iopub.execute_input":"2026-09-19T17:48:23.198648Z","iopub.status.idle":"2026-09-19T17:52:49.48067Z","shell.execute_reply.started":"2026-09-19T17:48:23.198624Z","shell.execute_reply":"2026-09-19T17:52:49.47965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\ntest_it.reset()\npreds_3 = (model_3.predict(test_it, verbose=0).flatten() > 0.5).astype(int)\nacc_3 = accuracy_score(y_true, preds_3)\ncm_3 = confusion_matrix(y_true, preds_3)\n\nplt.figure(figsize=(6, 5))\nsns.heatmap(cm_3, annot=True, fmt='d', cmap='Oranges', xticklabels=target_names, yticklabels=target_names, cbar=False)\nplt.title(f'Confusion Matrix: EfficientNetB0\\nAccuracy: {acc_3:.4f} ({acc_3*100:.2f}%)', fontsize=12)\nplt.ylabel('Actual Label')\nplt.xlabel('Predicted Label')\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-19T17:52:49.481891Z","iopub.execute_input":"2026-09-19T17:52:49.482253Z","iopub.status.idle":"2026-09-19T17:53:17.598367Z","shell.execute_reply.started":"2026-09-19T17:52:49.482211Z","shell.execute_reply":"2026-09-19T17:53:17.597715Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}