{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2026-09-11T14:29:10.099214Z","iopub.execute_input":"2026-09-11T14:29:10.099508Z","iopub.status.idle":"2026-09-11T14:29:10.432456Z","shell.execute_reply.started":"2026-09-11T14:29:10.099476Z","shell.execute_reply":"2026-09-11T14:29:10.431444Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:10.434145Z","iopub.execute_input":"2026-09-11T14:29:10.434626Z","iopub.status.idle":"2026-09-11T14:29:11.489800Z","shell.execute_reply.started":"2026-09-11T14:29:10.434599Z","shell.execute_reply":"2026-09-11T14:29:11.488628Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:11.491384Z","iopub.execute_input":"2026-09-11T14:29:11.491769Z","iopub.status.idle":"2026-09-11T14:29:12.507260Z","shell.execute_reply.started":"2026-09-11T14:29:11.491736Z","shell.execute_reply":"2026-09-11T14:29:12.504284Z"}},"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-11T14:29:12.509494Z","iopub.execute_input":"2026-09-11T14:29:12.510553Z","iopub.status.idle":"2026-09-11T14:29:24.362203Z","shell.execute_reply.started":"2026-09-11T14:29:12.510502Z","shell.execute_reply":"2026-09-11T14:29:24.361111Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:24.363449Z","iopub.execute_input":"2026-09-11T14:29:24.365297Z","iopub.status.idle":"2026-09-11T14:29:25.358659Z","shell.execute_reply.started":"2026-09-11T14:29:24.365269Z","shell.execute_reply":"2026-09-11T14:29:25.357432Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:25.360357Z","iopub.execute_input":"2026-09-11T14:29:25.361312Z","iopub.status.idle":"2026-09-11T14:29:26.345075Z","shell.execute_reply.started":"2026-09-11T14:29:25.361274Z","shell.execute_reply":"2026-09-11T14:29:26.344203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:26.347914Z","iopub.execute_input":"2026-09-11T14:29:26.348281Z","iopub.status.idle":"2026-09-11T14:29:27.384335Z","shell.execute_reply.started":"2026-09-11T14:29:26.348256Z","shell.execute_reply":"2026-09-11T14:29:27.383467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:27.385611Z","iopub.execute_input":"2026-09-11T14:29:27.385905Z","iopub.status.idle":"2026-09-11T14:29:28.432941Z","shell.execute_reply.started":"2026-09-11T14:29:27.385882Z","shell.execute_reply":"2026-09-11T14:29:28.432036Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:28.435695Z","iopub.execute_input":"2026-09-11T14:29:28.436354Z","iopub.status.idle":"2026-09-11T14:29:29.511027Z","shell.execute_reply.started":"2026-09-11T14:29:28.436322Z","shell.execute_reply":"2026-09-11T14:29:29.509802Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:29.512681Z","iopub.execute_input":"2026-09-11T14:29:29.512990Z","iopub.status.idle":"2026-09-11T14:29:29.517746Z","shell.execute_reply.started":"2026-09-11T14:29:29.512966Z","shell.execute_reply":"2026-09-11T14:29:29.516590Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:29.518797Z","iopub.execute_input":"2026-09-11T14:29:29.519073Z","iopub.status.idle":"2026-09-11T14:29:29.532012Z","shell.execute_reply.started":"2026-09-11T14:29:29.519050Z","shell.execute_reply":"2026-09-11T14:29:29.531174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:29.533419Z","iopub.execute_input":"2026-09-11T14:29:29.533848Z","iopub.status.idle":"2026-09-11T14:29:30.537160Z","shell.execute_reply.started":"2026-09-11T14:29:29.533813Z","shell.execute_reply":"2026-09-11T14:29:30.535937Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:30.538946Z","iopub.execute_input":"2026-09-11T14:29:30.539319Z","iopub.status.idle":"2026-09-11T14:29:31.607962Z","shell.execute_reply.started":"2026-09-11T14:29:30.539285Z","shell.execute_reply":"2026-09-11T14:29:31.607045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:31.609293Z","iopub.execute_input":"2026-09-11T14:29:31.609629Z","iopub.status.idle":"2026-09-11T14:29:32.618784Z","shell.execute_reply.started":"2026-09-11T14:29:31.609602Z","shell.execute_reply":"2026-09-11T14:29:32.617845Z"}},"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-11T14:29:32.620192Z","iopub.execute_input":"2026-09-11T14:29:32.620528Z","iopub.status.idle":"2026-09-11T14:29:33.653080Z","shell.execute_reply.started":"2026-09-11T14:29:32.620502Z","shell.execute_reply":"2026-09-11T14:29:33.652176Z"},"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-11T14:29:33.654440Z","iopub.execute_input":"2026-09-11T14:29:33.655379Z","iopub.status.idle":"2026-09-11T14:29:34.637003Z","shell.execute_reply.started":"2026-09-11T14:29:33.655353Z","shell.execute_reply":"2026-09-11T14:29:34.636029Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:34.638532Z","iopub.execute_input":"2026-09-11T14:29:34.638896Z","iopub.status.idle":"2026-09-11T14:29:35.648711Z","shell.execute_reply.started":"2026-09-11T14:29:34.638863Z","shell.execute_reply":"2026-09-11T14:29:35.647696Z"}},"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-11T14:29:35.650444Z","iopub.execute_input":"2026-09-11T14:29:35.650859Z","iopub.status.idle":"2026-09-11T14:29:48.657228Z","shell.execute_reply.started":"2026-09-11T14:29:35.650824Z","shell.execute_reply":"2026-09-11T14:29:48.656296Z"}},"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-11T14:29:48.658303Z","iopub.execute_input":"2026-09-11T14:29:48.658931Z","iopub.status.idle":"2026-09-11T14:29:48.663527Z","shell.execute_reply.started":"2026-09-11T14:29:48.658903Z","shell.execute_reply":"2026-09-11T14:29:48.662503Z"},"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-11T14:29:48.664766Z","iopub.execute_input":"2026-09-11T14:29:48.665058Z","iopub.status.idle":"2026-09-11T14:29:48.682572Z","shell.execute_reply.started":"2026-09-11T14:29:48.665034Z","shell.execute_reply":"2026-09-11T14:29:48.681614Z"},"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-11T14:29:48.683803Z","iopub.execute_input":"2026-09-11T14:29:48.684369Z","iopub.status.idle":"2026-09-11T14:29:48.695094Z","shell.execute_reply.started":"2026-09-11T14:29:48.684345Z","shell.execute_reply":"2026-09-11T14:29:48.694090Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:48.701702Z","iopub.execute_input":"2026-09-11T14:29:48.701990Z","iopub.status.idle":"2026-09-11T14:29:49.707549Z","shell.execute_reply.started":"2026-09-11T14:29:48.701967Z","shell.execute_reply":"2026-09-11T14:29:49.706606Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:49.708979Z","iopub.execute_input":"2026-09-11T14:29:49.709306Z","iopub.status.idle":"2026-09-11T14:29:50.702500Z","shell.execute_reply.started":"2026-09-11T14:29:49.709281Z","shell.execute_reply":"2026-09-11T14:29:50.701523Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:50.703952Z","iopub.execute_input":"2026-09-11T14:29:50.704278Z","iopub.status.idle":"2026-09-11T14:29:51.691360Z","shell.execute_reply.started":"2026-09-11T14:29:50.704253Z","shell.execute_reply":"2026-09-11T14:29:51.690360Z"}},"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-11T14:29:51.692836Z","iopub.execute_input":"2026-09-11T14:29:51.693146Z","iopub.status.idle":"2026-09-11T14:29:52.703137Z","shell.execute_reply.started":"2026-09-11T14:29:51.693121Z","shell.execute_reply":"2026-09-11T14:29:52.702203Z"}},"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-11T14:29:52.704710Z","iopub.execute_input":"2026-09-11T14:29:52.705070Z","iopub.status.idle":"2026-09-11T14:29:54.710650Z","shell.execute_reply.started":"2026-09-11T14:29:52.705036Z","shell.execute_reply":"2026-09-11T14:29:54.709609Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:29:54.711965Z","iopub.execute_input":"2026-09-11T14:29:54.712299Z","iopub.status.idle":"2026-09-11T14:29:54.717121Z","shell.execute_reply.started":"2026-09-11T14:29:54.712276Z","shell.execute_reply":"2026-09-11T14:29:54.716169Z"}},"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-11T14:29:54.718307Z","iopub.execute_input":"2026-09-11T14:29:54.718688Z","iopub.status.idle":"2026-09-11T14:29:56.882488Z","shell.execute_reply.started":"2026-09-11T14:29:54.718657Z","shell.execute_reply":"2026-09-11T14:29:56.881185Z"},"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-11T14:29:56.884165Z","iopub.execute_input":"2026-09-11T14:29:56.884593Z","iopub.status.idle":"2026-09-11T14:29:58.925483Z","shell.execute_reply.started":"2026-09-11T14:29:56.884540Z","shell.execute_reply":"2026-09-11T14:29:58.924442Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-11T14:29:58.927297Z","iopub.execute_input":"2026-09-11T14:29:58.927729Z","iopub.status.idle":"2026-09-11T14:30:10.582819Z","shell.execute_reply.started":"2026-09-11T14:29:58.927693Z","shell.execute_reply":"2026-09-11T14:30:10.581441Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-11T14:30:10.584470Z","iopub.execute_input":"2026-09-11T14:30:10.585399Z","iopub.status.idle":"2026-09-11T14:30:10.602799Z","shell.execute_reply.started":"2026-09-11T14:30:10.585369Z","shell.execute_reply":"2026-09-11T14:30:10.602104Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:00.079640Z","iopub.execute_input":"2026-09-11T15:01:00.080039Z","iopub.status.idle":"2026-09-11T15:01:00.084370Z","shell.execute_reply.started":"2026-09-11T15:01:00.080014Z","shell.execute_reply":"2026-09-11T15:01:00.083495Z"}},"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-11T15:01:00.528458Z","iopub.execute_input":"2026-09-11T15:01:00.529264Z","iopub.status.idle":"2026-09-11T15:01:00.534097Z","shell.execute_reply.started":"2026-09-11T15:01:00.529231Z","shell.execute_reply":"2026-09-11T15:01:00.533251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:02.848003Z","iopub.execute_input":"2026-09-11T15:01:02.848335Z","iopub.status.idle":"2026-09-11T15:01:02.858420Z","shell.execute_reply.started":"2026-09-11T15:01:02.848309Z","shell.execute_reply":"2026-09-11T15:01:02.857434Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32,\n                 (3, 3),\n                 activation='relu',\n                 input_shape=(200, 200, 3)\n                )\n         )\n\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:03.238714Z","iopub.execute_input":"2026-09-11T15:01:03.239363Z","iopub.status.idle":"2026-09-11T15:01:03.300706Z","shell.execute_reply.started":"2026-09-11T15:01:03.239331Z","shell.execute_reply":"2026-09-11T15:01:03.299933Z"}},"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-11T15:01:05.044238Z","iopub.execute_input":"2026-09-11T15:01:05.045039Z","iopub.status.idle":"2026-09-11T15:01:05.108335Z","shell.execute_reply.started":"2026-09-11T15:01:05.045002Z","shell.execute_reply":"2026-09-11T15:01:05.107386Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:05.310333Z","iopub.execute_input":"2026-09-11T15:01:05.311259Z","iopub.status.idle":"2026-09-11T15:01:05.316998Z","shell.execute_reply.started":"2026-09-11T15:01:05.311227Z","shell.execute_reply":"2026-09-11T15:01:05.315961Z"}},"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-11T15:01:07.139320Z","iopub.execute_input":"2026-09-11T15:01:07.139654Z","iopub.status.idle":"2026-09-11T15:01:07.205970Z","shell.execute_reply.started":"2026-09-11T15:01:07.139629Z","shell.execute_reply":"2026-09-11T15:01:07.205037Z"}},"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-11T15:01:07.379761Z","iopub.execute_input":"2026-09-11T15:01:07.380604Z","iopub.status.idle":"2026-09-11T15:01:07.386763Z","shell.execute_reply.started":"2026-09-11T15:01:07.380520Z","shell.execute_reply":"2026-09-11T15:01:07.385871Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model, not recommend to call this function\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:09.032351Z","iopub.execute_input":"2026-09-11T15:01:09.032739Z","iopub.status.idle":"2026-09-11T15:01:09.038362Z","shell.execute_reply.started":"2026-09-11T15:01:09.032709Z","shell.execute_reply":"2026-09-11T15:01:09.037505Z"}},"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-11T15:01:09.527352Z","iopub.execute_input":"2026-09-11T15:01:09.527703Z","iopub.status.idle":"2026-09-11T15:01:09.594045Z","shell.execute_reply.started":"2026-09-11T15:01:09.527675Z","shell.execute_reply":"2026-09-11T15:01:09.593063Z"}},"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-11T15:01:11.172509Z","iopub.execute_input":"2026-09-11T15:01:11.173683Z","iopub.status.idle":"2026-09-11T15:01:11.179856Z","shell.execute_reply.started":"2026-09-11T15:01:11.173649Z","shell.execute_reply":"2026-09-11T15:01:11.178711Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:11.508352Z","iopub.execute_input":"2026-09-11T15:01:11.509017Z","iopub.status.idle":"2026-09-11T15:01:12.507240Z","shell.execute_reply.started":"2026-09-11T15:01:11.508988Z","shell.execute_reply":"2026-09-11T15:01:12.506316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Hyperparameter => changable\nIMAGE_SIZE = (200, 200)\nBATCH_SIZE = 64\nEPOCHS = 20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:13.222098Z","iopub.execute_input":"2026-09-11T15:01:13.222852Z","iopub.status.idle":"2026-09-11T15:01:13.227455Z","shell.execute_reply.started":"2026-09-11T15:01:13.222819Z","shell.execute_reply":"2026-09-11T15:01:13.226441Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIZE, \n        target_size=IMAGE_SIZE\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:13.612966Z","iopub.execute_input":"2026-09-11T15:01:13.613280Z","iopub.status.idle":"2026-09-11T15:01:14.100211Z","shell.execute_reply.started":"2026-09-11T15:01:13.613256Z","shell.execute_reply":"2026-09-11T15:01:14.099302Z"}},"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-11T15:01:15.602357Z","iopub.execute_input":"2026-09-11T15:01:15.602775Z","iopub.status.idle":"2026-09-11T15:01:15.611028Z","shell.execute_reply.started":"2026-09-11T15:01:15.602743Z","shell.execute_reply":"2026-09-11T15:01:15.610200Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIZE,\n        target_size=IMAGE_SIZE\n)\ntype(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:15.983243Z","iopub.execute_input":"2026-09-11T15:01:15.984106Z","iopub.status.idle":"2026-09-11T15:01:16.204367Z","shell.execute_reply.started":"2026-09-11T15:01:15.984063Z","shell.execute_reply":"2026-09-11T15:01:16.203346Z"}},"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-11T15:01:17.698241Z","iopub.execute_input":"2026-09-11T15:01:17.698546Z","iopub.status.idle":"2026-09-11T15:01:17.704813Z","shell.execute_reply.started":"2026-09-11T15:01:17.698523Z","shell.execute_reply":"2026-09-11T15:01:17.703698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit(\n    train_it,\n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=EPOCHS,\n    verbose=2,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:01:18.780363Z","iopub.execute_input":"2026-09-11T15:01:18.781399Z","iopub.status.idle":"2026-09-11T15:15:59.342359Z","shell.execute_reply.started":"2026-09-11T15:01:18.781367Z","shell.execute_reply":"2026-09-11T15:15:59.341597Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:15:59.343972Z","iopub.execute_input":"2026-09-11T15:15:59.344723Z","iopub.status.idle":"2026-09-11T15:15:59.713427Z","shell.execute_reply.started":"2026-09-11T15:15:59.344696Z","shell.execute_reply":"2026-09-11T15:15:59.712733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:15:59.714471Z","iopub.execute_input":"2026-09-11T15:15:59.714790Z","iopub.status.idle":"2026-09-11T15:16:11.039076Z","shell.execute_reply.started":"2026-09-11T15:15:59.714768Z","shell.execute_reply":"2026-09-11T15:16:11.038101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:11.041592Z","iopub.execute_input":"2026-09-11T15:16:11.042318Z","iopub.status.idle":"2026-09-11T15:16:12.129198Z","shell.execute_reply.started":"2026-09-11T15:16:11.042293Z","shell.execute_reply":"2026-09-11T15:16:12.128168Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.130885Z","iopub.execute_input":"2026-09-11T15:16:12.131232Z","iopub.status.idle":"2026-09-11T15:16:12.138613Z","shell.execute_reply.started":"2026-09-11T15:16:12.131206Z","shell.execute_reply":"2026-09-11T15:16:12.137565Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.140192Z","iopub.execute_input":"2026-09-11T15:16:12.141188Z","iopub.status.idle":"2026-09-11T15:16:12.176781Z","shell.execute_reply.started":"2026-09-11T15:16:12.141156Z","shell.execute_reply":"2026-09-11T15:16:12.176055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.177933Z","iopub.execute_input":"2026-09-11T15:16:12.178219Z","iopub.status.idle":"2026-09-11T15:16:12.185502Z","shell.execute_reply.started":"2026-09-11T15:16:12.178196Z","shell.execute_reply":"2026-09-11T15:16:12.184605Z"}},"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-11T15:16:12.186757Z","iopub.execute_input":"2026-09-11T15:16:12.187372Z","iopub.status.idle":"2026-09-11T15:16:12.194952Z","shell.execute_reply.started":"2026-09-11T15:16:12.187349Z","shell.execute_reply":"2026-09-11T15:16:12.194108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.196244Z","iopub.execute_input":"2026-09-11T15:16:12.196561Z","iopub.status.idle":"2026-09-11T15:16:12.216806Z","shell.execute_reply.started":"2026-09-11T15:16:12.196512Z","shell.execute_reply":"2026-09-11T15:16:12.216056Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.220335Z","iopub.execute_input":"2026-09-11T15:16:12.220781Z","iopub.status.idle":"2026-09-11T15:16:12.227211Z","shell.execute_reply.started":"2026-09-11T15:16:12.220753Z","shell.execute_reply":"2026-09-11T15:16:12.226276Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.228276Z","iopub.execute_input":"2026-09-11T15:16:12.228481Z","iopub.status.idle":"2026-09-11T15:16:12.238404Z","shell.execute_reply.started":"2026-09-11T15:16:12.228463Z","shell.execute_reply":"2026-09-11T15:16:12.237414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.239791Z","iopub.execute_input":"2026-09-11T15:16:12.240422Z","iopub.status.idle":"2026-09-11T15:16:12.248802Z","shell.execute_reply.started":"2026-09-11T15:16:12.240397Z","shell.execute_reply":"2026-09-11T15:16:12.247916Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (200, 200)\n\n# datagen = ImageDataGenerator(rescale=1.0/255.0,\n#                             horizontal_flip=True,)\n# print(IMAGE_SIZE)\n# # prepare iterators\n# train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n#     class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# val_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n#     class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\n# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen_test = ImageDataGenerator(rescale=1./255,\n                                 vertical_flip=True)\n\n# Create the data generator using the DataFrame\ntest_it = datagen_test.flow_from_dataframe(\n    dataframe=df,\n    x_col='filename',\n    y_col=None,            # No labels for testing, so set to None\n    target_size=IMAGE_SIZE,\n    batch_size=64,\n    class_mode=None,       # Since there are no labels\n    # shuffle=True,         # Usually testing data should not be shuffled\n    shuffle=False,\n)\n\ntype(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.250224Z","iopub.execute_input":"2026-09-11T15:16:12.250648Z","iopub.status.idle":"2026-09-11T15:16:12.338592Z","shell.execute_reply.started":"2026-09-11T15:16:12.250626Z","shell.execute_reply":"2026-09-11T15:16:12.337619Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\ndef plot_exmaple(images, labels):\n    # Assuming images shape is (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a 1D array for easy iteration\n\n    for i, ax in enumerate(axes):\n        if i < len(images):\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))  # Fixed: set_title instead of title\n            ax.axis(\"off\")  # Turn off axis ticks/labels for clarity\n        else:\n            ax.axis(\"off\")  # Hide unused subplots if images < 64\n\n    plt.tight_layout()\n    plt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:12.339902Z","iopub.execute_input":"2026-09-11T15:16:12.340263Z","iopub.status.idle":"2026-09-11T15:16:12.346148Z","shell.execute_reply.started":"2026-09-11T15:16:12.340232Z","shell.execute_reply":"2026-09-11T15:16:12.345209Z"}},"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-11T15:16:12.347374Z","iopub.execute_input":"2026-09-11T15:16:12.347709Z","iopub.status.idle":"2026-09-11T15:16:17.567288Z","shell.execute_reply.started":"2026-09-11T15:16:12.347684Z","shell.execute_reply":"2026-09-11T15:16:17.566069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_images, val_labels = val_it.__next__()\nval_images.shape\nplot_exmaple(val_images, val_labels)\nval_labels[:8]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:17.568964Z","iopub.execute_input":"2026-09-11T15:16:17.569235Z","iopub.status.idle":"2026-09-11T15:16:22.524498Z","shell.execute_reply.started":"2026-09-11T15:16:17.569213Z","shell.execute_reply":"2026-09-11T15:16:22.523616Z"}},"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-11T15:16:22.525838Z","iopub.execute_input":"2026-09-11T15:16:22.526192Z","iopub.status.idle":"2026-09-11T15:16:22.533797Z","shell.execute_reply.started":"2026-09-11T15:16:22.526162Z","shell.execute_reply":"2026-09-11T15:16:22.532761Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()  # หรือ next(test_it)\n\n# สร้าง list เลขดัชนีตามจำนวนภาพที่มี\nindices = list(range(len(test_images)))\n\nplot_exmaple_test(test_images, indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:22.535130Z","iopub.execute_input":"2026-09-11T15:16:22.535444Z","iopub.status.idle":"2026-09-11T15:16:27.326484Z","shell.execute_reply.started":"2026-09-11T15:16:22.535417Z","shell.execute_reply":"2026-09-11T15:16:27.324656Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict\npreds = model_1.predict(test_it, verbose=1)\ntype(preds), preds.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:27.327805Z","iopub.execute_input":"2026-09-11T15:16:27.328119Z","iopub.status.idle":"2026-09-11T15:16:47.822404Z","shell.execute_reply.started":"2026-09-11T15:16:27.328093Z","shell.execute_reply":"2026-09-11T15:16:47.821475Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:47.823887Z","iopub.execute_input":"2026-09-11T15:16:47.824859Z","iopub.status.idle":"2026-09-11T15:16:47.830786Z","shell.execute_reply.started":"2026-09-11T15:16:47.824823Z","shell.execute_reply":"2026-09-11T15:16:47.829888Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\n\n\n# 1. สุ่ม index มา 10 ตัวจากชุดข้อมูล\nsample_indices = np.random.choice(len(test_images), size=10, replace=False)\nsample_images = test_images[sample_indices]\n\n# 2. Predict \npredictions = model_1.predict(sample_images)\npredicted_classes = np.argmax(predictions, axis=1)  # ดึง class ที่ได้คะแนนสูงสุด\n\n# 3. แสดงผล 10 ภาพ (ปรับเป็น grid 2x5)\nfig, axes = plt.subplots(2, 5, figsize=(15, 6))\naxes = axes.flatten()\n\nfor i, ax in enumerate(axes):\n    ax.imshow(sample_images[i])\n    # แสดง Index เดิม และ Class ที่ทายได้\n    ax.set_title(f\"Idx: {sample_indices[i]}\\nPred: {predicted_classes[i]}\")\n    ax.axis(\"off\")\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:47.831910Z","iopub.execute_input":"2026-09-11T15:16:47.832862Z","iopub.status.idle":"2026-09-11T15:16:49.587360Z","shell.execute_reply.started":"2026-09-11T15:16:47.832837Z","shell.execute_reply":"2026-09-11T15:16:49.586217Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# end of 2026-09-06\nstop here","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T15:16:49.588654Z","iopub.execute_input":"2026-09-11T15:16:49.589241Z","iopub.status.idle":"2026-09-11T15:16:49.594625Z","shell.execute_reply.started":"2026-09-11T15:16:49.589214Z","shell.execute_reply":"2026-09-11T15:16:49.593523Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.905405Z","iopub.status.idle":"2026-09-11T14:46:44.905972Z","shell.execute_reply.started":"2026-09-11T14:46:44.905710Z","shell.execute_reply":"2026-09-11T14:46:44.905734Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.907373Z","iopub.status.idle":"2026-09-11T14:46:44.907768Z","shell.execute_reply.started":"2026-09-11T14:46:44.907589Z","shell.execute_reply":"2026-09-11T14:46:44.907616Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model = VGG16(include_top=False, input_shape=(224, 224, 3))\n# mark loaded layers as not trainable\n# for layer in model.layers:\n#     layer.trainable = False\n\n# print(model.layers[-1].output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.909276Z","iopub.status.idle":"2026-09-11T14:46:44.909667Z","shell.execute_reply.started":"2026-09-11T14:46:44.909421Z","shell.execute_reply":"2026-09-11T14:46:44.909455Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_feature_extractor = VGG16(include_top=False, input_shape=(224, 224, 3))\n# model_16_feature_extractor.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.911627Z","iopub.status.idle":"2026-09-11T14:46:44.911982Z","shell.execute_reply.started":"2026-09-11T14:46:44.911825Z","shell.execute_reply":"2026-09-11T14:46:44.911849Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model_16_feature_extractor.layers):\n# \t\tprint(index, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.912919Z","iopub.status.idle":"2026-09-11T14:46:44.913245Z","shell.execute_reply.started":"2026-09-11T14:46:44.913090Z","shell.execute_reply":"2026-09-11T14:46:44.913108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\n# model_16_top = VGG16(include_top=True, input_shape=(224, 224, 3))\n# model_16_top.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.914855Z","iopub.status.idle":"2026-09-11T14:46:44.915180Z","shell.execute_reply.started":"2026-09-11T14:46:44.915036Z","shell.execute_reply":"2026-09-11T14:46:44.915050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.916962Z","iopub.status.idle":"2026-09-11T14:46:44.917358Z","shell.execute_reply.started":"2026-09-11T14:46:44.917210Z","shell.execute_reply":"2026-09-11T14:46:44.917225Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.918989Z","iopub.status.idle":"2026-09-11T14:46:44.919382Z","shell.execute_reply.started":"2026-09-11T14:46:44.919233Z","shell.execute_reply":"2026-09-11T14:46:44.919248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     print(index, layer.name, layer.trainable)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.920665Z","iopub.status.idle":"2026-09-11T14:46:44.920998Z","shell.execute_reply.started":"2026-09-11T14:46:44.920841Z","shell.execute_reply":"2026-09-11T14:46:44.920860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers[-7:]):\n#     layer.trainable = True\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.922534Z","iopub.status.idle":"2026-09-11T14:46:44.923012Z","shell.execute_reply.started":"2026-09-11T14:46:44.922790Z","shell.execute_reply":"2026-09-11T14:46:44.922812Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(vgg16_model.layers):\n#     if index >= 15:\n#         layer.trainable = True\n\n# for index, layer in enumerate(vgg16_model.layers):\n#     print(index, layer.name, layer.trainable)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.924942Z","iopub.status.idle":"2026-09-11T14:46:44.925336Z","shell.execute_reply.started":"2026-09-11T14:46:44.925155Z","shell.execute_reply":"2026-09-11T14:46:44.925183Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"id(vgg16_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.926611Z","iopub.status.idle":"2026-09-11T14:46:44.926960Z","shell.execute_reply.started":"2026-09-11T14:46:44.926807Z","shell.execute_reply":"2026-09-11T14:46:44.926825Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nprint(id(vgg16_model))\nvgg16_model.reset_states()\nvgg16_model_history = vgg16_model.fit(\n    train_it, \n    steps_per_epoch=len(train_it),\n    validation_data=val_it,\n    validation_steps=len(val_it),\n    epochs=3, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.928733Z","iopub.status.idle":"2026-09-11T14:46:44.929066Z","shell.execute_reply.started":"2026-09-11T14:46:44.928909Z","shell.execute_reply":"2026-09-11T14:46:44.928928Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(vgg16_model_history)\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('Val: > %.3f' % (acc * 100.0))\n\n# evaluate model\n_, acc = vgg16_model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('Test: > %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.930497Z","iopub.status.idle":"2026-09-11T14:46:44.930944Z","shell.execute_reply.started":"2026-09-11T14:46:44.930732Z","shell.execute_reply":"2026-09-11T14:46:44.930751Z"}},"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":"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-11T14:46:44.932381Z","iopub.status.idle":"2026-09-11T14:46:44.932739Z","shell.execute_reply.started":"2026-09-11T14:46:44.932522Z","shell.execute_reply":"2026-09-11T14:46:44.932534Z"}},"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-11T14:46:44.934280Z","iopub.status.idle":"2026-09-11T14:46:44.934680Z","shell.execute_reply.started":"2026-09-11T14:46:44.934459Z","shell.execute_reply":"2026-09-11T14:46:44.934477Z"},"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-11T14:46:44.935954Z","iopub.status.idle":"2026-09-11T14:46:44.936286Z","shell.execute_reply.started":"2026-09-11T14:46:44.936131Z","shell.execute_reply":"2026-09-11T14:46:44.936150Z"}},"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-11T14:46:44.937927Z","iopub.status.idle":"2026-09-11T14:46:44.938366Z","shell.execute_reply.started":"2026-09-11T14:46:44.938150Z","shell.execute_reply":"2026-09-11T14:46:44.938170Z"}},"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-11T14:46:44.940184Z","iopub.status.idle":"2026-09-11T14:46:44.940628Z","shell.execute_reply.started":"2026-09-11T14:46:44.940384Z","shell.execute_reply":"2026-09-11T14:46:44.940403Z"}},"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-11T14:46:44.942637Z","iopub.status.idle":"2026-09-11T14:46:44.942991Z","shell.execute_reply.started":"2026-09-11T14:46:44.942830Z","shell.execute_reply":"2026-09-11T14:46:44.942849Z"}},"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-11T14:46:44.944244Z","iopub.status.idle":"2026-09-11T14:46:44.944624Z","shell.execute_reply.started":"2026-09-11T14:46:44.944423Z","shell.execute_reply":"2026-09-11T14:46:44.944443Z"}},"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-11T14:46:44.946257Z","iopub.status.idle":"2026-09-11T14:46:44.946707Z","shell.execute_reply.started":"2026-09-11T14:46:44.946459Z","shell.execute_reply":"2026-09-11T14:46:44.946478Z"}},"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-11T14:46:44.948424Z","iopub.status.idle":"2026-09-11T14:46:44.948871Z","shell.execute_reply.started":"2026-09-11T14:46:44.948653Z","shell.execute_reply":"2026-09-11T14:46:44.948673Z"}},"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-11T14:46:44.950182Z","iopub.status.idle":"2026-09-11T14:46:44.950634Z","shell.execute_reply.started":"2026-09-11T14:46:44.950387Z","shell.execute_reply":"2026-09-11T14:46:44.950407Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T14:46:44.952773Z","iopub.status.idle":"2026-09-11T14:46:44.953198Z","shell.execute_reply.started":"2026-09-11T14:46:44.952979Z","shell.execute_reply":"2026-09-11T14:46:44.952999Z"}},"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-11T14:46:44.954452Z","iopub.status.idle":"2026-09-11T14:46:44.955189Z","shell.execute_reply.started":"2026-09-11T14:46:44.954941Z","shell.execute_reply":"2026-09-11T14:46:44.954963Z"}},"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-11T14:46:44.956363Z","iopub.status.idle":"2026-09-11T14:46:44.956813Z","shell.execute_reply.started":"2026-09-11T14:46:44.956596Z","shell.execute_reply":"2026-09-11T14:46:44.956616Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}