{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\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","execution":{"iopub.status.busy":"2026-09-18T14:04:34.034161Z","iopub.execute_input":"2026-09-18T14:04:34.034416Z","iopub.status.idle":"2026-09-18T14:04:34.355989Z","shell.execute_reply.started":"2026-09-18T14:04:34.034392Z","shell.execute_reply":"2026-09-18T14:04:34.354998Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:34.357911Z","iopub.execute_input":"2026-09-18T14:04:34.358538Z","iopub.status.idle":"2026-09-18T14:04:35.389949Z","shell.execute_reply.started":"2026-09-18T14:04:34.358513Z","shell.execute_reply":"2026-09-18T14:04:35.388594Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:35.391557Z","iopub.execute_input":"2026-09-18T14:04:35.391952Z","iopub.status.idle":"2026-09-18T14:04:36.442997Z","shell.execute_reply.started":"2026-09-18T14:04:35.391915Z","shell.execute_reply":"2026-09-18T14:04:36.442022Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:04:36.444554Z","iopub.execute_input":"2026-09-18T14:04:36.445268Z","iopub.status.idle":"2026-09-18T14:04:50.986656Z","shell.execute_reply.started":"2026-09-18T14:04:36.445241Z","shell.execute_reply":"2026-09-18T14:04:50.985950Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:50.987643Z","iopub.execute_input":"2026-09-18T14:04:50.987969Z","iopub.status.idle":"2026-09-18T14:04:51.980811Z","shell.execute_reply.started":"2026-09-18T14:04:50.987945Z","shell.execute_reply":"2026-09-18T14:04:51.979433Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:51.982231Z","iopub.execute_input":"2026-09-18T14:04:51.982526Z","iopub.status.idle":"2026-09-18T14:04:52.962598Z","shell.execute_reply.started":"2026-09-18T14:04:51.982499Z","shell.execute_reply":"2026-09-18T14:04:52.961665Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:52.966440Z","iopub.execute_input":"2026-09-18T14:04:52.966834Z","iopub.status.idle":"2026-09-18T14:04:54.001998Z","shell.execute_reply.started":"2026-09-18T14:04:52.966809Z","shell.execute_reply":"2026-09-18T14:04:54.000649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:54.004241Z","iopub.execute_input":"2026-09-18T14:04:54.004575Z","iopub.status.idle":"2026-09-18T14:04:55.053003Z","shell.execute_reply.started":"2026-09-18T14:04:54.004548Z","shell.execute_reply":"2026-09-18T14:04:55.052105Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:55.054596Z","iopub.execute_input":"2026-09-18T14:04:55.054986Z","iopub.status.idle":"2026-09-18T14:04:55.059449Z","shell.execute_reply.started":"2026-09-18T14:04:55.054952Z","shell.execute_reply":"2026-09-18T14:04:55.058696Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:55.060530Z","iopub.execute_input":"2026-09-18T14:04:55.060814Z","iopub.status.idle":"2026-09-18T14:04:56.112791Z","shell.execute_reply.started":"2026-09-18T14:04:55.060789Z","shell.execute_reply":"2026-09-18T14:04:56.111557Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:56.114267Z","iopub.execute_input":"2026-09-18T14:04:56.114561Z","iopub.status.idle":"2026-09-18T14:04:57.145563Z","shell.execute_reply.started":"2026-09-18T14:04:56.114536Z","shell.execute_reply":"2026-09-18T14:04:57.144632Z"}},"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":{"execution":{"iopub.status.busy":"2026-09-18T14:04:57.146991Z","iopub.execute_input":"2026-09-18T14:04:57.147294Z","iopub.status.idle":"2026-09-18T14:04:58.233348Z","shell.execute_reply.started":"2026-09-18T14:04:57.147269Z","shell.execute_reply":"2026-09-18T14:04:58.232420Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:04:58.234801Z","iopub.execute_input":"2026-09-18T14:04:58.235176Z","iopub.status.idle":"2026-09-18T14:04:59.445912Z","shell.execute_reply.started":"2026-09-18T14:04:58.235142Z","shell.execute_reply":"2026-09-18T14:04:59.444637Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:04:59.447316Z","iopub.execute_input":"2026-09-18T14:04:59.447622Z","iopub.status.idle":"2026-09-18T14:05:00.574192Z","shell.execute_reply.started":"2026-09-18T14:04:59.447596Z","shell.execute_reply":"2026-09-18T14:05:00.573061Z"}},"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-18T14:05:00.575865Z","iopub.execute_input":"2026-09-18T14:05:00.576249Z","iopub.status.idle":"2026-09-18T14:05:18.080291Z","shell.execute_reply.started":"2026-09-18T14:05:00.576214Z","shell.execute_reply":"2026-09-18T14:05:18.079228Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load dogs vs cats dataset, reshape and save to a new file\nfrom os import listdir\nfrom numpy import asarray\nfrom numpy import save\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:05:18.082775Z","iopub.execute_input":"2026-09-18T14:05:18.083394Z","iopub.status.idle":"2026-09-18T14:05:18.087948Z","shell.execute_reply.started":"2026-09-18T14:05:18.083366Z","shell.execute_reply":"2026-09-18T14:05:18.086965Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# define location of dataset\nfolder = 'train/'\nphotos, labels = list(), list()\n# enumerate files in the directory\nfor file in listdir(folder):\n\t# determine class\n\toutput = 0.0\n\tif file.startswith('dog'):\n\t\toutput = 1.0\n\t# load image\n\tphoto = load_img(folder + file, target_size=(200, 200))\n\t# convert to numpy array\n\tphoto = img_to_array(photo)\n\t# store\n\tphotos.append(photo)\n\tlabels.append(output)\n# convert to a numpy arrays\nphotos = asarray(photos)\nlabels = asarray(labels)\nprint(photos.shape, labels.shape)\n# save the reshaped photos\nsave('dogs_vs_cats_photos.npy', photos)\nsave('dogs_vs_cats_labels.npy', labels)","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:15.416611Z","iopub.execute_input":"2024-01-27T03:36:15.417128Z","iopub.status.idle":"2024-01-27T03:36:38.886396Z","shell.execute_reply.started":"2024-01-27T03:36:15.417101Z","shell.execute_reply":"2024-01-27T03:36:38.883149Z"}}},{"cell_type":"markdown","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')","metadata":{"execution":{"iopub.status.busy":"2024-01-27T03:36:38.88711Z","iopub.status.idle":"2024-01-27T03:36:38.887458Z","shell.execute_reply.started":"2024-01-27T03:36:38.887281Z","shell.execute_reply":"2024-01-27T03:36:38.887296Z"}}},{"cell_type":"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":{"execution":{"iopub.status.busy":"2026-09-18T14:05:18.089116Z","iopub.execute_input":"2026-09-18T14:05:18.090034Z","iopub.status.idle":"2026-09-18T14:05:18.109331Z","shell.execute_reply.started":"2026-09-18T14:05:18.089996Z","shell.execute_reply":"2026-09-18T14:05:18.108577Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2026-09-18T14:05:18.110497Z","iopub.execute_input":"2026-09-18T14:05:18.110816Z","iopub.status.idle":"2026-09-18T14:05:18.123103Z","shell.execute_reply.started":"2026-09-18T14:05:18.110782Z","shell.execute_reply":"2026-09-18T14:05:18.122138Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:05:18.124266Z","iopub.execute_input":"2026-09-18T14:05:18.124566Z","iopub.status.idle":"2026-09-18T14:05:19.126759Z","shell.execute_reply.started":"2026-09-18T14:05:18.124537Z","shell.execute_reply":"2026-09-18T14:05:19.125755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:05:19.128113Z","iopub.execute_input":"2026-09-18T14:05:19.128413Z","iopub.status.idle":"2026-09-18T14:05:20.123464Z","shell.execute_reply.started":"2026-09-18T14:05:19.128388Z","shell.execute_reply":"2026-09-18T14:05:20.122332Z"}},"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-18T14:05:20.124889Z","iopub.execute_input":"2026-09-18T14:05:20.125271Z","iopub.status.idle":"2026-09-18T14:05:21.118121Z","shell.execute_reply.started":"2026-09-18T14:05:20.125246Z","shell.execute_reply":"2026-09-18T14:05:21.117134Z"}},"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":{"execution":{"iopub.status.busy":"2026-09-18T14:05:21.124773Z","iopub.execute_input":"2026-09-18T14:05:21.125170Z","iopub.status.idle":"2026-09-18T14:05:23.116973Z","shell.execute_reply.started":"2026-09-18T14:05:21.125144Z","shell.execute_reply":"2026-09-18T14:05:23.116150Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:05:23.118078Z","iopub.execute_input":"2026-09-18T14:05:23.118384Z","iopub.status.idle":"2026-09-18T14:05:23.123162Z","shell.execute_reply.started":"2026-09-18T14:05:23.118360Z","shell.execute_reply":"2026-09-18T14:05:23.122224Z"}},"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":{"execution":{"iopub.status.busy":"2026-09-18T14:05:23.124118Z","iopub.execute_input":"2026-09-18T14:05:23.124459Z","iopub.status.idle":"2026-09-18T14:05:25.251052Z","shell.execute_reply.started":"2026-09-18T14:05:23.124437Z","shell.execute_reply":"2026-09-18T14:05:25.250060Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2026-09-18T14:05:25.252803Z","iopub.execute_input":"2026-09-18T14:05:25.253206Z","iopub.status.idle":"2026-09-18T14:05:27.315789Z","shell.execute_reply.started":"2026-09-18T14:05:25.253156Z","shell.execute_reply":"2026-09-18T14:05:27.314536Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:05:27.317494Z","iopub.execute_input":"2026-09-18T14:05:27.317908Z","iopub.status.idle":"2026-09-18T14:05:39.090269Z","shell.execute_reply.started":"2026-09-18T14:05:27.317871Z","shell.execute_reply":"2026-09-18T14:05:39.089236Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:05:39.091702Z","iopub.execute_input":"2026-09-18T14:05:39.092053Z","iopub.status.idle":"2026-09-18T14:05:39.111193Z","shell.execute_reply.started":"2026-09-18T14:05:39.092027Z","shell.execute_reply":"2026-09-18T14:05:39.110446Z"},"trusted":true},"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-18T14:05:39.112257Z","iopub.execute_input":"2026-09-18T14:05:39.112540Z","iopub.status.idle":"2026-09-18T14:05:39.116282Z","shell.execute_reply.started":"2026-09-18T14:05:39.112517Z","shell.execute_reply":"2026-09-18T14:05:39.115323Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model for the dogs vs cats dataset\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:05:39.117359Z","iopub.execute_input":"2026-09-18T14:05:39.117682Z","iopub.status.idle":"2026-09-18T14:05:39.126403Z","shell.execute_reply.started":"2026-09-18T14:05:39.117660Z","shell.execute_reply":"2026-09-18T14:05:39.125392Z"}},"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',\n                     kernel_initializer='he_uniform',\n                     padding='same',\n                     input_shape=(200, 200, 3))\n             )\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-18T14:05:39.127520Z","iopub.execute_input":"2026-09-18T14:05:39.127840Z","iopub.status.idle":"2026-09-18T14:05:39.138656Z","shell.execute_reply.started":"2026-09-18T14:05:39.127811Z","shell.execute_reply":"2026-09-18T14:05:39.137709Z"}},"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-18T14:05:39.139556Z","iopub.execute_input":"2026-09-18T14:05:39.140290Z","iopub.status.idle":"2026-09-18T14:05:41.401574Z","shell.execute_reply.started":"2026-09-18T14:05:39.140258Z","shell.execute_reply":"2026-09-18T14:05:41.400804Z"}},"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-18T14:05:41.402841Z","iopub.execute_input":"2026-09-18T14:05:41.403174Z","iopub.status.idle":"2026-09-18T14:05:41.410208Z","shell.execute_reply.started":"2026-09-18T14:05:41.403142Z","shell.execute_reply":"2026-09-18T14:05:41.409539Z"}},"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-18T14:05:41.411548Z","iopub.execute_input":"2026-09-18T14:05:41.412191Z","iopub.status.idle":"2026-09-18T14:05:41.485048Z","shell.execute_reply.started":"2026-09-18T14:05:41.412142Z","shell.execute_reply":"2026-09-18T14:05:41.484276Z"}},"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-18T14:05:41.486204Z","iopub.execute_input":"2026-09-18T14:05:41.486540Z","iopub.status.idle":"2026-09-18T14:05:41.563112Z","shell.execute_reply.started":"2026-09-18T14:05:41.486506Z","shell.execute_reply":"2026-09-18T14:05:41.562307Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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-18T14:05:41.564478Z","iopub.execute_input":"2026-09-18T14:05:41.564946Z","iopub.status.idle":"2026-09-18T14:05:41.657158Z","shell.execute_reply.started":"2026-09-18T14:05:41.564911Z","shell.execute_reply":"2026-09-18T14:05:41.655844Z"}},"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-18T14:05:41.658220Z","iopub.execute_input":"2026-09-18T14:05:41.658477Z","iopub.status.idle":"2026-09-18T14:05:41.664237Z","shell.execute_reply.started":"2026-09-18T14:05:41.658455Z","shell.execute_reply":"2026-09-18T14:05:41.663373Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:05:41.665133Z","iopub.execute_input":"2026-09-18T14:05:41.665333Z","iopub.status.idle":"2026-09-18T14:05:42.688098Z","shell.execute_reply.started":"2026-09-18T14:05:41.665315Z","shell.execute_reply":"2026-09-18T14:05:42.687129Z"}},"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-18T14:05:42.689400Z","iopub.execute_input":"2026-09-18T14:05:42.689711Z","iopub.status.idle":"2026-09-18T14:05:42.694320Z","shell.execute_reply.started":"2026-09-18T14:05:42.689685Z","shell.execute_reply":"2026-09-18T14:05:42.693486Z"}},"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-18T14:05:42.695547Z","iopub.execute_input":"2026-09-18T14:05:42.696139Z","iopub.status.idle":"2026-09-18T14:06:21.189919Z","shell.execute_reply.started":"2026-09-18T14:05:42.696108Z","shell.execute_reply":"2026-09-18T14:06:21.189091Z"}},"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-18T14:06:21.190948Z","iopub.execute_input":"2026-09-18T14:06:21.191236Z","iopub.status.idle":"2026-09-18T14:06:21.198099Z","shell.execute_reply.started":"2026-09-18T14:06:21.191212Z","shell.execute_reply":"2026-09-18T14:06:21.197092Z"}},"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-18T14:06:21.199318Z","iopub.execute_input":"2026-09-18T14:06:21.200099Z","iopub.status.idle":"2026-09-18T14:06:21.212877Z","shell.execute_reply.started":"2026-09-18T14:06:21.200033Z","shell.execute_reply":"2026-09-18T14:06:21.212009Z"}},"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-18T14:06:21.213952Z","iopub.execute_input":"2026-09-18T14:06:21.214247Z","iopub.status.idle":"2026-09-18T14:06:21.223371Z","shell.execute_reply.started":"2026-09-18T14:06:21.214218Z","shell.execute_reply":"2026-09-18T14:06:21.222701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\n# summarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:21.224367Z","iopub.execute_input":"2026-09-18T14:06:21.224609Z","iopub.status.idle":"2026-09-18T14:06:21.236525Z","shell.execute_reply.started":"2026-09-18T14:06:21.224588Z","shell.execute_reply":"2026-09-18T14:06:21.235549Z"}},"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-18T14:06:21.237503Z","iopub.execute_input":"2026-09-18T14:06:21.237798Z","iopub.status.idle":"2026-09-18T14:06:21.247759Z","shell.execute_reply.started":"2026-09-18T14:06:21.237763Z","shell.execute_reply":"2026-09-18T14:06:21.246775Z"}},"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-18T14:06:21.248941Z","iopub.execute_input":"2026-09-18T14:06:21.249451Z","iopub.status.idle":"2026-09-18T14:06:22.268036Z","shell.execute_reply.started":"2026-09-18T14:06:21.249428Z","shell.execute_reply":"2026-09-18T14:06:22.267116Z"}},"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'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.269401Z","iopub.execute_input":"2026-09-18T14:06:22.270225Z","iopub.status.idle":"2026-09-18T14:06:22.275713Z","shell.execute_reply.started":"2026-09-18T14:06:22.270198Z","shell.execute_reply":"2026-09-18T14:06:22.274798Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.277014Z","iopub.execute_input":"2026-09-18T14:06:22.277788Z","iopub.status.idle":"2026-09-18T14:06:22.292198Z","shell.execute_reply.started":"2026-09-18T14:06:22.277764Z","shell.execute_reply":"2026-09-18T14:06:22.291264Z"}},"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-18T14:06:22.293180Z","iopub.execute_input":"2026-09-18T14:06:22.293532Z","iopub.status.idle":"2026-09-18T14:06:22.304185Z","shell.execute_reply.started":"2026-09-18T14:06:22.293497Z","shell.execute_reply":"2026-09-18T14:06:22.303177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.305173Z","iopub.execute_input":"2026-09-18T14:06:22.305776Z","iopub.status.idle":"2026-09-18T14:06:22.314237Z","shell.execute_reply.started":"2026-09-18T14:06:22.305728Z","shell.execute_reply":"2026-09-18T14:06:22.313574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.315371Z","iopub.execute_input":"2026-09-18T14:06:22.315969Z","iopub.status.idle":"2026-09-18T14:06:22.325375Z","shell.execute_reply.started":"2026-09-18T14:06:22.315945Z","shell.execute_reply":"2026-09-18T14:06:22.324777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# test_df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.326391Z","iopub.execute_input":"2026-09-18T14:06:22.327152Z","iopub.status.idle":"2026-09-18T14:06:22.335377Z","shell.execute_reply.started":"2026-09-18T14:06:22.327122Z","shell.execute_reply":"2026-09-18T14:06:22.334774Z"}},"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-18T14:06:22.336435Z","iopub.execute_input":"2026-09-18T14:06:22.336923Z","iopub.status.idle":"2026-09-18T14:06:22.353099Z","shell.execute_reply.started":"2026-09-18T14:06:22.336900Z","shell.execute_reply":"2026-09-18T14:06:22.352219Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE, BATCH_SIZE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:22.354217Z","iopub.execute_input":"2026-09-18T14:06:22.355047Z","iopub.status.idle":"2026-09-18T14:06:22.362898Z","shell.execute_reply.started":"2026-09-18T14:06:22.355024Z","shell.execute_reply":"2026-09-18T14:06:22.362006Z"}},"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-18T14:06:22.363887Z","iopub.execute_input":"2026-09-18T14:06:22.364128Z","iopub.status.idle":"2026-09-18T14:06:38.656068Z","shell.execute_reply.started":"2026-09-18T14:06:22.364107Z","shell.execute_reply":"2026-09-18T14:06:38.655065Z"}},"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()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:06:38.657248Z","iopub.execute_input":"2026-09-18T14:06:38.657524Z","iopub.status.idle":"2026-09-18T14:06:38.662917Z","shell.execute_reply.started":"2026-09-18T14:06:38.657502Z","shell.execute_reply":"2026-09-18T14:06:38.662124Z"}},"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-18T14:06:38.664061Z","iopub.execute_input":"2026-09-18T14:06:38.664541Z","iopub.status.idle":"2026-09-18T14:06:48.176639Z","shell.execute_reply.started":"2026-09-18T14:06:38.664519Z","shell.execute_reply":"2026-09-18T14:06:48.175504Z"}},"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-18T14:06:48.178360Z","iopub.execute_input":"2026-09-18T14:06:48.178819Z","iopub.status.idle":"2026-09-18T14:06:57.703034Z","shell.execute_reply.started":"2026-09-18T14:06:48.178775Z","shell.execute_reply":"2026-09-18T14:06:57.701966Z"}},"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-18T14:06:57.704761Z","iopub.execute_input":"2026-09-18T14:06:57.705271Z","iopub.status.idle":"2026-09-18T14:06:57.711626Z","shell.execute_reply.started":"2026-09-18T14:06:57.705229Z","shell.execute_reply":"2026-09-18T14:06:57.710755Z"},"jupyter":{"source_hidden":true}},"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-18T14:06:57.712838Z","iopub.execute_input":"2026-09-18T14:06:57.713197Z","iopub.status.idle":"2026-09-18T14:07:07.209773Z","shell.execute_reply.started":"2026-09-18T14:06:57.713158Z","shell.execute_reply":"2026-09-18T14:07:07.208237Z"}},"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-18T14:07:07.211107Z","iopub.execute_input":"2026-09-18T14:07:07.211412Z","iopub.status.idle":"2026-09-18T14:07:07.216080Z","shell.execute_reply.started":"2026-09-18T14:07:07.211385Z","shell.execute_reply":"2026-09-18T14:07:07.215097Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2026-09-13\n# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:07:07.217146Z","iopub.execute_input":"2026-09-18T14:07:07.217623Z","iopub.status.idle":"2026-09-18T14:07:07.234784Z","shell.execute_reply.started":"2026-09-18T14:07:07.217599Z","shell.execute_reply":"2026-09-18T14:07:07.233842Z"}},"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-18T14:07:07.235920Z","iopub.execute_input":"2026-09-18T14:07:07.236229Z","iopub.status.idle":"2026-09-18T14:07:07.248636Z","shell.execute_reply.started":"2026-09-18T14:07:07.236182Z","shell.execute_reply":"2026-09-18T14:07:07.247622Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# Hyperparameter => changable\nIMAGE_SIZE = 224\nBATCH_SIE = 64\nEPOCHS = 20\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model\n\nvgg16 = define_model_vgg16()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:07:07.249951Z","iopub.execute_input":"2026-09-18T14:07:07.250253Z","iopub.status.idle":"2026-09-18T14:07:08.148104Z","shell.execute_reply.started":"2026-09-18T14:07:07.250230Z","shell.execute_reply":"2026-09-18T14:07:08.147269Z"}},"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-18T14:07:08.149238Z","iopub.execute_input":"2026-09-18T14:07:08.149632Z","iopub.status.idle":"2026-09-18T14:07:14.741072Z","shell.execute_reply.started":"2026-09-18T14:07:08.149603Z","shell.execute_reply":"2026-09-18T14:07:14.740204Z"}},"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-18T14:07:14.742245Z","iopub.execute_input":"2026-09-18T14:07:14.742574Z","iopub.status.idle":"2026-09-18T14:07:15.092217Z","shell.execute_reply.started":"2026-09-18T14:07:14.742542Z","shell.execute_reply":"2026-09-18T14:07:15.091392Z"}},"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-18T14:07:15.093365Z","iopub.execute_input":"2026-09-18T14:07:15.093703Z","iopub.status.idle":"2026-09-18T14:07:15.100129Z","shell.execute_reply.started":"2026-09-18T14:07:15.093668Z","shell.execute_reply":"2026-09-18T14:07:15.099283Z"}},"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-18T14:07:15.107779Z","iopub.execute_input":"2026-09-18T14:07:15.108051Z","iopub.status.idle":"2026-09-18T14:07:15.113376Z","shell.execute_reply.started":"2026-09-18T14:07:15.108029Z","shell.execute_reply":"2026-09-18T14:07:15.112558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_16_feature_extractor.layers[-1].output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:07:15.114462Z","iopub.execute_input":"2026-09-18T14:07:15.114807Z","iopub.status.idle":"2026-09-18T14:07:15.124434Z","shell.execute_reply.started":"2026-09-18T14:07:15.114767Z","shell.execute_reply":"2026-09-18T14:07:15.123705Z"}},"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-18T14:08:15.069098Z","iopub.execute_input":"2026-09-18T14:08:15.069441Z","iopub.status.idle":"2026-09-18T14:08:15.080239Z","shell.execute_reply.started":"2026-09-18T14:08:15.069418Z","shell.execute_reply":"2026-09-18T14:08:15.079225Z"}},"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-18T14:08:17.941506Z","iopub.execute_input":"2026-09-18T14:08:17.941850Z","iopub.status.idle":"2026-09-18T14:08:17.958542Z","shell.execute_reply.started":"2026-09-18T14:08:17.941824Z","shell.execute_reply":"2026-09-18T14:08:17.957325Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"output = Dense(1, activation='sigmoid')(class1)\nprint(output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:08:20.345914Z","iopub.execute_input":"2026-09-18T14:08:20.346519Z","iopub.status.idle":"2026-09-18T14:08:20.364110Z","shell.execute_reply.started":"2026-09-18T14:08:20.346489Z","shell.execute_reply":"2026-09-18T14:08:20.363110Z"}},"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# compile model\nopt = SGD(lr=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-18T14:08:21.868194Z","iopub.execute_input":"2026-09-18T14:08:21.869129Z","iopub.status.idle":"2026-09-18T14:08:21.884649Z","shell.execute_reply.started":"2026-09-18T14:08:21.869093Z","shell.execute_reply":"2026-09-18T14:08:21.883538Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(model_vgg16.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:08:22.972033Z","iopub.execute_input":"2026-09-18T14:08:22.972893Z","iopub.status.idle":"2026-09-18T14:08:23.015678Z","shell.execute_reply.started":"2026-09-18T14:08:22.972860Z","shell.execute_reply":"2026-09-18T14:08:23.014911Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(train_it), id(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:08:25.419231Z","iopub.execute_input":"2026-09-18T14:08:25.419677Z","iopub.status.idle":"2026-09-18T14:08:25.425590Z","shell.execute_reply.started":"2026-09-18T14:08:25.419643Z","shell.execute_reply":"2026-09-18T14:08:25.424558Z"}},"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-18T14:08:29.192113Z","iopub.execute_input":"2026-09-18T14:08:29.192418Z","iopub.status.idle":"2026-09-18T14:08:29.197696Z","shell.execute_reply.started":"2026-09-18T14:08:29.192397Z","shell.execute_reply":"2026-09-18T14:08:29.196595Z"}},"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    # Optional but highly recommended: Prevent TF from pre-allocating 100% of VRAM\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        \n        print(f\"Model ID: {id(model_vgg16)}\")\n        \n        # Note: reset_states() is strictly for stateful RNNs (LSTMs/GRUs). \n        # For a feed-forward CNN like VGG16, this method has no effect and can be removed.\n        model_vgg16.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-18T14:08:37.052414Z","iopub.execute_input":"2026-09-18T14:08:37.053210Z","iopub.status.idle":"2026-09-18T14:12:12.423447Z","shell.execute_reply.started":"2026-09-18T14:08:37.053176Z","shell.execute_reply":"2026-09-18T14:12:12.422576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(model_vgg16_history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:12:12.425324Z","iopub.execute_input":"2026-09-18T14:12:12.426162Z","iopub.status.idle":"2026-09-18T14:12:12.743025Z","shell.execute_reply.started":"2026-09-18T14:12:12.426135Z","shell.execute_reply":"2026-09-18T14:12:12.742320Z"}},"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-18T14:12:12.744094Z","iopub.execute_input":"2026-09-18T14:12:12.744366Z","iopub.status.idle":"2026-09-18T14:12:29.937404Z","shell.execute_reply.started":"2026-09-18T14:12:12.744345Z","shell.execute_reply":"2026-09-18T14:12:29.936684Z"}},"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-18T14:12:29.939696Z","iopub.execute_input":"2026-09-18T14:12:29.940492Z","iopub.status.idle":"2026-09-18T14:14:01.236037Z","shell.execute_reply.started":"2026-09-18T14:12:29.940459Z","shell.execute_reply":"2026-09-18T14:14:01.235248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom sklearn.metrics import classification_report\n\n# 1. Reset the generator state to ensure alignment from index 0\ntest_it.reset()\n\n# 2. Extract the ordered ground truth labels from the generator\ny_true = test_it.classes\nprint(y_true.shape)\n\n# 3. Execute the forward pass over the entire test dataset\n# Calculate exact steps to prevent infinite looping or partial evaluation\nsteps = np.ceil(test_it.samples / test_it.batch_size)\nprobabilities = model_vgg16.predict(test_it, steps=steps, verbose=1).squeeze()\nprint(probabilities.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:01.238578Z","iopub.execute_input":"2026-09-18T14:14:01.238942Z","iopub.status.idle":"2026-09-18T14:14:30.178823Z","shell.execute_reply.started":"2026-09-18T14:14:01.238915Z","shell.execute_reply":"2026-09-18T14:14:30.177798Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probabilities[:20]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:30.180082Z","iopub.execute_input":"2026-09-18T14:14:30.180642Z","iopub.status.idle":"2026-09-18T14:14:30.187294Z","shell.execute_reply.started":"2026-09-18T14:14:30.180614Z","shell.execute_reply":"2026-09-18T14:14:30.186460Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"(probabilities[0] > 0.5).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:30.188238Z","iopub.execute_input":"2026-09-18T14:14:30.188539Z","iopub.status.idle":"2026-09-18T14:14:30.203880Z","shell.execute_reply.started":"2026-09-18T14:14:30.188513Z","shell.execute_reply":"2026-09-18T14:14:30.203177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 4. Discretize continuous logistic probabilities into binary class predictions\ny_pred = (probabilities > 0.5).astype(int)\nprint(y_pred.shape)\n\n# 5. Extract dynamic class labels mapping (e.g., {'cats': 0, 'dogs': 1})\n# This ensures the report correctly maps index 0 and 1 to your string labels\ntarget_names = list(test_it.class_indices.keys())\n\n# 6. Compute and output the classification report\nreport = classification_report(y_true, y_pred, target_names=target_names)\nprint(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:30.204835Z","iopub.execute_input":"2026-09-18T14:14:30.205096Z","iopub.status.idle":"2026-09-18T14:14:30.235128Z","shell.execute_reply.started":"2026-09-18T14:14:30.205074Z","shell.execute_reply":"2026-09-18T14:14:30.234252Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_true[:10], y_pred[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:30.236142Z","iopub.execute_input":"2026-09-18T14:14:30.236866Z","iopub.status.idle":"2026-09-18T14:14:30.243374Z","shell.execute_reply.started":"2026-09-18T14:14:30.236837Z","shell.execute_reply":"2026-09-18T14:14:30.242605Z"}},"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-18T14:14:30.246092Z","iopub.execute_input":"2026-09-18T14:14:30.246395Z","iopub.status.idle":"2026-09-18T14:14:37.772339Z","shell.execute_reply.started":"2026-09-18T14:14:30.246371Z","shell.execute_reply":"2026-09-18T14:14:37.771266Z"}},"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()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:37.773594Z","iopub.execute_input":"2026-09-18T14:14:37.773898Z","iopub.status.idle":"2026-09-18T14:14:45.778391Z","shell.execute_reply.started":"2026-09-18T14:14:37.773873Z","shell.execute_reply":"2026-09-18T14:14:45.776821Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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(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-18T14:16:07.177718Z","iopub.execute_input":"2026-09-18T14:16:07.178299Z","iopub.status.idle":"2026-09-18T14:16:07.185854Z","shell.execute_reply.started":"2026-09-18T14:16:07.178267Z","shell.execute_reply":"2026-09-18T14:16:07.184714Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()\nprint(id(model_inceptionv3))\n# model_inceptionv3.summary()","metadata":{"execution":{"iopub.status.busy":"2026-09-18T14:16:10.344171Z","iopub.execute_input":"2026-09-18T14:16:10.344485Z","iopub.status.idle":"2026-09-18T14:16:13.287156Z","shell.execute_reply.started":"2026-09-18T14:16:10.344462Z","shell.execute_reply":"2026-09-18T14:16:13.286315Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras import backend as K\n\ntrainable_params = int(np.sum([K.count_params(w) for w in model_inceptionv3.trainable_weights]))\nprint(trainable_params)\n","metadata":{"trusted":true,"scrolled":true,"execution":{"iopub.status.busy":"2026-09-18T14:16:13.289031Z","iopub.execute_input":"2026-09-18T14:16:13.289382Z","iopub.status.idle":"2026-09-18T14:16:13.295043Z","shell.execute_reply.started":"2026-09-18T14:16:13.289346Z","shell.execute_reply":"2026-09-18T14:16:13.294114Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nfor w in model_inceptionv3.trainable_weights:\n    print(w.name, K.count_params(w))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:16:13.296322Z","iopub.execute_input":"2026-09-18T14:16:13.296644Z","iopub.status.idle":"2026-09-18T14:16:13.308937Z","shell.execute_reply.started":"2026-09-18T14:16:13.296613Z","shell.execute_reply":"2026-09-18T14:16:13.308136Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit 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, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:16:15.861547Z","iopub.execute_input":"2026-09-18T14:16:15.862515Z","iopub.status.idle":"2026-09-18T14:16:17.427930Z","shell.execute_reply.started":"2026-09-18T14:16:15.862469Z","shell.execute_reply":"2026-09-18T14:16:17.426567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:16:17.428551Z","iopub.status.idle":"2026-09-18T14:16:17.428932Z","shell.execute_reply.started":"2026-09-18T14:16:17.428762Z","shell.execute_reply":"2026-09-18T14:16:17.428792Z"}},"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-18T14:14:46.282320Z","iopub.status.idle":"2026-09-18T14:14:46.282633Z","shell.execute_reply.started":"2026-09-18T14:14:46.282494Z","shell.execute_reply":"2026-09-18T14:14:46.282510Z"}},"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-18T14:14:46.283830Z","iopub.status.idle":"2026-09-18T14:14:46.284144Z","shell.execute_reply.started":"2026-09-18T14:14:46.284005Z","shell.execute_reply":"2026-09-18T14:14:46.284021Z"}},"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-18T14:14:46.285132Z","iopub.status.idle":"2026-09-18T14:14:46.285435Z","shell.execute_reply.started":"2026-09-18T14:14:46.285300Z","shell.execute_reply":"2026-09-18T14:14:46.285314Z"}},"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-18T14:14:46.286987Z","iopub.status.idle":"2026-09-18T14:14:46.287303Z","shell.execute_reply.started":"2026-09-18T14:14:46.287164Z","shell.execute_reply":"2026-09-18T14:14:46.287179Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:14:46.288822Z","iopub.status.idle":"2026-09-18T14:14:46.289137Z","shell.execute_reply.started":"2026-09-18T14:14:46.288997Z","shell.execute_reply":"2026-09-18T14:14:46.289013Z"}},"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-18T14:14:46.290382Z","iopub.status.idle":"2026-09-18T14:14:46.290638Z","shell.execute_reply.started":"2026-09-18T14:14:46.290516Z","shell.execute_reply":"2026-09-18T14:14:46.290529Z"}},"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-18T14:14:46.291817Z","iopub.status.idle":"2026-09-18T14:14:46.292092Z","shell.execute_reply.started":"2026-09-18T14:14:46.291954Z","shell.execute_reply":"2026-09-18T14:14:46.291967Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport shutil\nimport tensorflow as tf\n\n# 1. แตกไฟล์ train.zip จาก Directory ของ Kaggle\n# (test1.zip ของ Kaggle ไม่มี Label ไว้ให้ จึงไม่สามารถนำมาทำ Classification Report ได้ เราจะใช้ข้อมูลจาก train.zip มาแบ่งแทน)\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\", \"r\") as z:\n    z.extractall(\".\")\n\n# 2. จัดโครงสร้างโฟลเดอร์ใหม่ เพื่อให้ Keras อ่านและแยกคลาส (Class) ได้อัตโนมัติ\nbase_dir = './dataset_dogs_vs_cats'\ntrain_dir = os.path.join(base_dir, 'train')\n\n# สร้างโฟลเดอร์แยกระหว่างแมวและหมา\nos.makedirs(os.path.join(train_dir, 'cats'), exist_ok=True)\nos.makedirs(os.path.join(train_dir, 'dogs'), exist_ok=True)\n\n# 3. ย้ายไฟล์รูปภาพไปไว้ในโฟลเดอร์ที่สร้างไว้ตามชื่อไฟล์\nextracted_train_folder = './train'\nfor filename in os.listdir(extracted_train_folder):\n    src = os.path.join(extracted_train_folder, filename)\n    if filename.startswith('cat'):\n        dst = os.path.join(train_dir, 'cats', filename)\n        shutil.move(src, dst)\n    elif filename.startswith('dog'):\n        dst = os.path.join(train_dir, 'dogs', filename)\n        shutil.move(src, dst)\n\nprint(\"จัดเตรียมไฟล์เสร็จสมบูรณ์!\")\n\n# 4. กำหนด Path ที่ถูกต้องให้ตัวแปร TRAIN_DIR\nTRAIN_DIR = train_dir","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:30:22.819637Z","iopub.execute_input":"2026-09-18T14:30:22.820072Z","iopub.status.idle":"2026-09-18T14:30:29.802933Z","shell.execute_reply.started":"2026-09-18T14:30:22.820037Z","shell.execute_reply":"2026-09-18T14:30:29.801593Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 1. สร้าง Dataset Pipeline ---\nimport tensorflow as tf\n\nIMG_SIZE = (224, 224) # ขนาดภาพที่เหมาะกับ Pre-trained Models ส่วนใหญ่\nBATCH_SIZE = 32\n\nprint(\">> กำลังโหลดข้อมูล Training...\")\n# แบ่งข้อมูล 80% สำหรับเทรน\ntrain_dataset = tf.keras.utils.image_dataset_from_directory(\n    TRAIN_DIR,\n    validation_split=0.2,\n    subset=\"training\",\n    seed=123,\n    image_size=IMG_SIZE,\n    batch_size=BATCH_SIZE\n)\n\nprint(\"\\n>> กำลังโหลดข้อมูล Test...\")\n# ดึงอีก 20% ที่เหลือมาใช้เป็นชุดทดสอบ (Test Set) เพื่อวัดผล\ntest_dataset = tf.keras.utils.image_dataset_from_directory(\n    TRAIN_DIR,\n    validation_split=0.2,\n    subset=\"validation\",\n    seed=123,\n    image_size=IMG_SIZE,\n    batch_size=BATCH_SIZE,\n    shuffle=False # ห้ามสลับลำดับ เพื่อให้วัดผลได้แม่นยำ\n)\n\n# ดึงชื่อคลาส (['cats', 'dogs'])\nclass_names = train_dataset.class_names\nprint(f\"\\nพบกลุ่มคลาส: {class_names}\")\n\n# ปรับปรุงประสิทธิภาพ Data Pipeline ด้วย AUTOTUNE\nAUTOTUNE = tf.data.AUTOTUNE\ntrain_dataset = train_dataset.cache().prefetch(buffer_size=AUTOTUNE)\ntest_dataset = test_dataset.cache().prefetch(buffer_size=AUTOTUNE)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:33:08.983719Z","iopub.execute_input":"2026-09-18T14:33:08.984594Z","iopub.status.idle":"2026-09-18T14:33:11.590602Z","shell.execute_reply.started":"2026-09-18T14:33:08.984561Z","shell.execute_reply":"2026-09-18T14:33:11.589680Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 2. นำเข้าโมเดลและสร้างฟังก์ชัน ---\nfrom tensorflow.keras.applications import EfficientNetB0, ResNet50V2, InceptionV3\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout, Input\nfrom tensorflow.keras.models import Model\n\ndef create_model(base_model_class, preprocess_input=None):\n    # 1. รับขนาด Input 224x224 แบบ 3 สี (RGB)\n    inputs = Input(shape=(224, 224, 3))\n    \n    # 2. ปรับแต่งรูปภาพ (Data Augmentation) ช่วยลดอาการท่องจำ (Overfitting)\n    x = tf.keras.layers.RandomFlip('horizontal')(inputs)\n    x = tf.keras.layers.RandomRotation(0.1)(x)\n    \n    # 3. การเตรียมข้อมูล (Preprocessing)\n    # โมเดลแต่ละตัวต้องการการปรับค่าสีภาพก่อนเข้าโมเดลต่างกัน\n    if preprocess_input is not None:\n        x = preprocess_input(x)\n        \n    # 4. เรียกใช้ Pre-trained Model (โหลดความรู้จาก ImageNet)\n    base_model = base_model_class(input_shape=(224, 224, 3), include_top=False, weights='imagenet')\n    base_model.trainable = False # ล็อคความรู้เดิมไว้ไม่ให้เพี้ยน\n    \n    x = base_model(x, training=False)\n    \n    # 5. ใส่ Layer สรุปผลสำหรับงานแยกหมาแมว (Classification Head)\n    x = GlobalAveragePooling2D()(x)\n    x = Dropout(0.2)(x) \n    # ใช้ sigmoid เพราะมีแค่ 2 คลาส (0 หรือ 1)\n    outputs = Dense(1, activation='sigmoid')(x) \n    \n    model = Model(inputs, outputs)\n    \n    # Compile โมเดล\n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n        loss='binary_crossentropy', # ฟังก์ชัน Loss สำหรับ 2 คลาส\n        metrics=['accuracy']\n    )\n    \n    return model\n\n# สร้าง 3 โมเดลเตรียมไว้\nmodels = {\n    'EfficientNetB0': create_model(EfficientNetB0), # EfficientNet จัดการ Preprocess ในตัว\n    'ResNet50V2': create_model(ResNet50V2, tf.keras.applications.resnet_v2.preprocess_input),\n    'InceptionV3': create_model(InceptionV3, tf.keras.applications.inception_v3.preprocess_input)\n}\nprint(\"เตรียมโมเดลทั้ง 3 เสร็จสิ้น!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:33:11.592243Z","iopub.execute_input":"2026-09-18T14:33:11.592801Z","iopub.status.idle":"2026-09-18T14:33:20.840381Z","shell.execute_reply.started":"2026-09-18T14:33:11.592757Z","shell.execute_reply":"2026-09-18T14:33:20.839387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# --- 3. เทรนและประเมินผล ---\nfrom sklearn.metrics import classification_report\nimport numpy as np\n\n# สามารถเพิ่มจำนวน Epoch ได้หากต้องการความแม่นยำสูงขึ้น (แนะนำ 3-5 สำหรับการรันเร็วๆ)\nEPOCHS = 3 \n\n# ดึง Label ของชุดทดสอบ (Test Set) มารอไว้ก่อน \n# (จำเป็นต้องดึงออกมาเพื่อเปรียบเทียบใน Classification Report)\ny_true = []\nfor images, labels in test_dataset:\n    y_true.extend(labels.numpy())\ny_true = np.array(y_true)\n\n# วนลูปเพื่อเทรนทีละโมเดล\nfor name, model in models.items():\n    print(f\"\\n=============================================\")\n    print(f\"กำลังเทรนและประเมินผลโมเดล: {name}\")\n    print(f\"=============================================\")\n    \n    # สั่งเทรนโมเดล\n    history = model.fit(\n        train_dataset,\n        epochs=EPOCHS,\n        validation_data=test_dataset\n    )\n    \n    print(f\"\\n[ สร้าง Classification Report สำหรับ {name} ]\")\n    # สั่งให้โมเดลทำนายรูปใน Test Set\n    y_pred_probs = model.predict(test_dataset)\n    \n    # แปลงค่าโอกาส (0.0 - 1.0) ให้ออกมาเป็นคลาส 0 หรือ 1 (โดยใช้เกณฑ์ที่ > 0.5)\n    y_pred_classes = (y_pred_probs > 0.5).astype(int)\n    \n    # ปริ้นท์รายงาน\n    report = classification_report(\n        y_true, \n        y_pred_classes, \n        target_names=class_names, \n        digits=4 # แสดงทศนิยม 4 ตำแหน่ง\n    )\n    print(report)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-18T14:33:20.842470Z","iopub.execute_input":"2026-09-18T14:33:20.842892Z","iopub.status.idle":"2026-09-18T14:43:27.043466Z","shell.execute_reply.started":"2026-09-18T14:33:20.842863Z","shell.execute_reply":"2026-09-18T14:43:27.042461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}