{"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-06T03:16:47.378946Z","iopub.execute_input":"2026-09-06T03:16:47.37984Z","iopub.status.idle":"2026-09-06T03:16:47.38884Z","shell.execute_reply.started":"2026-09-06T03:16:47.379792Z","shell.execute_reply":"2026-09-06T03:16:47.387714Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:17:20.952934Z","iopub.execute_input":"2026-09-11T08:17:20.953214Z","iopub.status.idle":"2026-09-11T08:17:22.022798Z","shell.execute_reply.started":"2026-09-11T08:17:20.95319Z","shell.execute_reply":"2026-09-11T08:17:22.021657Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!uname --all","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:17:24.103643Z","iopub.execute_input":"2026-09-11T08:17:24.104744Z","iopub.status.idle":"2026-09-11T08:17:25.094484Z","shell.execute_reply.started":"2026-09-11T08:17:24.10471Z","shell.execute_reply":"2026-09-11T08:17:25.093615Z"}},"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-11T08:17:31.973603Z","iopub.execute_input":"2026-09-11T08:17:31.974405Z","iopub.status.idle":"2026-09-11T08:17:41.607555Z","shell.execute_reply.started":"2026-09-11T08:17:31.974368Z","shell.execute_reply":"2026-09-11T08:17:41.606469Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:18:07.920653Z","iopub.execute_input":"2026-09-11T08:18:07.9213Z","iopub.status.idle":"2026-09-11T08:18:08.909883Z","shell.execute_reply.started":"2026-09-11T08:18:07.921269Z","shell.execute_reply":"2026-09-11T08:18:08.908797Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:18:10.485057Z","iopub.execute_input":"2026-09-11T08:18:10.485717Z","iopub.status.idle":"2026-09-11T08:18:11.451892Z","shell.execute_reply.started":"2026-09-11T08:18:10.485685Z","shell.execute_reply":"2026-09-11T08:18:11.450944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:25.278618Z","iopub.execute_input":"2026-09-11T08:20:25.279726Z","iopub.status.idle":"2026-09-11T08:20:26.300443Z","shell.execute_reply.started":"2026-09-11T08:20:25.279688Z","shell.execute_reply":"2026-09-11T08:20:26.299619Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:41.091435Z","iopub.execute_input":"2026-09-11T08:20:41.09224Z","iopub.status.idle":"2026-09-11T08:20:42.095405Z","shell.execute_reply.started":"2026-09-11T08:20:41.092206Z","shell.execute_reply":"2026-09-11T08:20:42.094359Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:43.106753Z","iopub.execute_input":"2026-09-11T08:20:43.10772Z","iopub.status.idle":"2026-09-11T08:20:44.149532Z","shell.execute_reply.started":"2026-09-11T08:20:43.107683Z","shell.execute_reply":"2026-09-11T08:20:44.148594Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:44.867183Z","iopub.execute_input":"2026-09-11T08:20:44.867662Z","iopub.status.idle":"2026-09-11T08:20:44.872022Z","shell.execute_reply.started":"2026-09-11T08:20:44.867628Z","shell.execute_reply":"2026-09-11T08:20:44.871029Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:46.026006Z","iopub.execute_input":"2026-09-11T08:20:46.02678Z","iopub.status.idle":"2026-09-11T08:20:46.033282Z","shell.execute_reply.started":"2026-09-11T08:20:46.026747Z","shell.execute_reply":"2026-09-11T08:20:46.032451Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:47.367611Z","iopub.execute_input":"2026-09-11T08:20:47.368406Z","iopub.status.idle":"2026-09-11T08:20:48.331828Z","shell.execute_reply.started":"2026-09-11T08:20:47.368373Z","shell.execute_reply":"2026-09-11T08:20:48.330858Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U train | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:48.92776Z","iopub.execute_input":"2026-09-11T08:20:48.928058Z","iopub.status.idle":"2026-09-11T08:20:49.960536Z","shell.execute_reply.started":"2026-09-11T08:20:48.928035Z","shell.execute_reply":"2026-09-11T08:20:49.959599Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -U test1 | head -n 10","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:20:51.066991Z","iopub.execute_input":"2026-09-11T08:20:51.0678Z","iopub.status.idle":"2026-09-11T08:20:52.063981Z","shell.execute_reply.started":"2026-09-11T08:20:51.067765Z","shell.execute_reply":"2026-09-11T08:20:52.062783Z"}},"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-11T08:20:53.659563Z","iopub.execute_input":"2026-09-11T08:20:53.660199Z","iopub.status.idle":"2026-09-11T08:20:54.630367Z","shell.execute_reply.started":"2026-09-11T08:20:53.660166Z","shell.execute_reply":"2026-09-11T08:20:54.629552Z"},"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-11T08:20:58.851373Z","iopub.execute_input":"2026-09-11T08:20:58.85168Z","iopub.status.idle":"2026-09-11T08:20:59.793181Z","shell.execute_reply.started":"2026-09-11T08:20:58.851657Z","shell.execute_reply":"2026-09-11T08:20:59.792222Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:21:01.557447Z","iopub.execute_input":"2026-09-11T08:21:01.558405Z","iopub.status.idle":"2026-09-11T08:21:02.52697Z","shell.execute_reply.started":"2026-09-11T08:21:01.558372Z","shell.execute_reply":"2026-09-11T08:21:02.525959Z"}},"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-11T08:21:14.815949Z","iopub.execute_input":"2026-09-11T08:21:14.816436Z","iopub.status.idle":"2026-09-11T08:21:14.821826Z","shell.execute_reply.started":"2026-09-11T08:21:14.816411Z","shell.execute_reply":"2026-09-11T08:21:14.820538Z"}},"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-11T08:22:31.91403Z","iopub.execute_input":"2026-09-11T08:22:31.914859Z","iopub.status.idle":"2026-09-11T08:22:31.919991Z","shell.execute_reply.started":"2026-09-11T08:22:31.914812Z","shell.execute_reply":"2026-09-11T08:22:31.91924Z"},"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-11T08:22:34.433437Z","iopub.execute_input":"2026-09-11T08:22:34.433749Z","iopub.status.idle":"2026-09-11T08:22:34.438389Z","shell.execute_reply.started":"2026-09-11T08:22:34.433725Z","shell.execute_reply":"2026-09-11T08:22:34.437389Z"},"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-11T08:22:41.776597Z","iopub.execute_input":"2026-09-11T08:22:41.777273Z","iopub.status.idle":"2026-09-11T08:22:41.783645Z","shell.execute_reply.started":"2026-09-11T08:22:41.77724Z","shell.execute_reply":"2026-09-11T08:22:41.782641Z"},"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-11T08:24:11.347869Z","iopub.execute_input":"2026-09-11T08:24:11.348769Z","iopub.status.idle":"2026-09-11T08:24:12.321828Z","shell.execute_reply.started":"2026-09-11T08:24:11.348738Z","shell.execute_reply":"2026-09-11T08:24:12.32064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:24:13.181196Z","iopub.execute_input":"2026-09-11T08:24:13.182138Z","iopub.status.idle":"2026-09-11T08:24:14.151264Z","shell.execute_reply.started":"2026-09-11T08:24:13.182102Z","shell.execute_reply":"2026-09-11T08:24:14.150256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:24:16.332909Z","iopub.execute_input":"2026-09-11T08:24:16.333239Z","iopub.status.idle":"2026-09-11T08:24:17.311707Z","shell.execute_reply.started":"2026-09-11T08:24:16.333214Z","shell.execute_reply":"2026-09-11T08:24:17.310406Z"}},"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-11T08:24:39.429266Z","iopub.execute_input":"2026-09-11T08:24:39.429601Z","iopub.status.idle":"2026-09-11T08:24:40.396913Z","shell.execute_reply.started":"2026-09-11T08:24:39.429563Z","shell.execute_reply":"2026-09-11T08:24:40.395994Z"}},"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-11T08:24:41.946449Z","iopub.execute_input":"2026-09-11T08:24:41.947433Z","iopub.status.idle":"2026-09-11T08:24:43.952009Z","shell.execute_reply.started":"2026-09-11T08:24:41.947397Z","shell.execute_reply":"2026-09-11T08:24:43.951167Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:24:48.816647Z","iopub.execute_input":"2026-09-11T08:24:48.817549Z","iopub.status.idle":"2026-09-11T08:24:48.823493Z","shell.execute_reply.started":"2026-09-11T08:24:48.817515Z","shell.execute_reply":"2026-09-11T08:24:48.821888Z"}},"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-11T08:24:51.236931Z","iopub.execute_input":"2026-09-11T08:24:51.237339Z","iopub.status.idle":"2026-09-11T08:24:53.321159Z","shell.execute_reply.started":"2026-09-11T08:24:51.237302Z","shell.execute_reply":"2026-09-11T08:24:53.320214Z"},"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-11T08:25:00.217939Z","iopub.execute_input":"2026-09-11T08:25:00.218871Z","iopub.status.idle":"2026-09-11T08:25:02.207482Z","shell.execute_reply.started":"2026-09-11T08:25:00.218835Z","shell.execute_reply":"2026-09-11T08:25:02.206254Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-11T08:25:02.209943Z","iopub.execute_input":"2026-09-11T08:25:02.210428Z","iopub.status.idle":"2026-09-11T08:25:12.296377Z","shell.execute_reply.started":"2026-09-11T08:25:02.2104Z","shell.execute_reply":"2026-09-11T08:25:12.295317Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-11T08:25:12.298117Z","iopub.execute_input":"2026-09-11T08:25:12.298414Z","iopub.status.idle":"2026-09-11T08:25:12.313387Z","shell.execute_reply.started":"2026-09-11T08:25:12.298389Z","shell.execute_reply":"2026-09-11T08:25:12.312726Z"},"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-02-16T07:02:33.08589Z","iopub.execute_input":"2026-02-16T07:02:33.086131Z","iopub.status.idle":"2026-02-16T07:02:33.094167Z","shell.execute_reply.started":"2026-02-16T07:02:33.086111Z","shell.execute_reply":"2026-02-16T07:02:33.09349Z"}},"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-11T08:26:58.239303Z","iopub.execute_input":"2026-09-11T08:26:58.240146Z","iopub.status.idle":"2026-09-11T08:26:58.245117Z","shell.execute_reply.started":"2026-09-11T08:26:58.240109Z","shell.execute_reply":"2026-09-11T08:26:58.244188Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential()\ntype(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:27:00.41837Z","iopub.execute_input":"2026-09-11T08:27:00.41915Z","iopub.status.idle":"2026-09-11T08:27:01.894207Z","shell.execute_reply.started":"2026-09-11T08:27:00.419119Z","shell.execute_reply":"2026-09-11T08:27:01.893421Z"}},"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-11T08:27:03.292708Z","iopub.execute_input":"2026-09-11T08:27:03.293726Z","iopub.status.idle":"2026-09-11T08:27:03.419075Z","shell.execute_reply.started":"2026-09-11T08:27:03.293692Z","shell.execute_reply":"2026-09-11T08:27:03.418075Z"}},"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-11T08:27:07.43535Z","iopub.execute_input":"2026-09-11T08:27:07.436218Z","iopub.status.idle":"2026-09-11T08:27:07.500109Z","shell.execute_reply.started":"2026-09-11T08:27:07.436183Z","shell.execute_reply":"2026-09-11T08:27:07.499228Z"}},"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-11T08:27:09.518881Z","iopub.execute_input":"2026-09-11T08:27:09.519672Z","iopub.status.idle":"2026-09-11T08:27:09.52509Z","shell.execute_reply.started":"2026-09-11T08:27:09.519637Z","shell.execute_reply":"2026-09-11T08:27:09.524141Z"}},"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-11T08:27:17.293016Z","iopub.execute_input":"2026-09-11T08:27:17.293767Z","iopub.status.idle":"2026-09-11T08:27:17.366932Z","shell.execute_reply.started":"2026-09-11T08:27:17.293734Z","shell.execute_reply":"2026-09-11T08:27:17.366054Z"}},"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-11T08:27:19.676408Z","iopub.execute_input":"2026-09-11T08:27:19.677214Z","iopub.status.idle":"2026-09-11T08:27:19.682806Z","shell.execute_reply.started":"2026-09-11T08:27:19.677182Z","shell.execute_reply":"2026-09-11T08:27:19.681924Z"}},"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-11T08:27:21.66621Z","iopub.execute_input":"2026-09-11T08:27:21.666954Z","iopub.status.idle":"2026-09-11T08:27:21.673235Z","shell.execute_reply.started":"2026-09-11T08:27:21.666921Z","shell.execute_reply":"2026-09-11T08:27:21.672144Z"}},"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-11T08:27:22.693271Z","iopub.execute_input":"2026-09-11T08:27:22.693553Z","iopub.status.idle":"2026-09-11T08:27:22.754483Z","shell.execute_reply.started":"2026-09-11T08:27:22.693532Z","shell.execute_reply":"2026-09-11T08:27:22.753802Z"}},"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-11T08:27:25.037639Z","iopub.execute_input":"2026-09-11T08:27:25.038382Z","iopub.status.idle":"2026-09-11T08:27:25.045349Z","shell.execute_reply.started":"2026-09-11T08:27:25.038342Z","shell.execute_reply":"2026-09-11T08:27:25.044298Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:27:25.999225Z","iopub.execute_input":"2026-09-11T08:27:26.000112Z","iopub.status.idle":"2026-09-11T08:27:26.98889Z","shell.execute_reply.started":"2026-09-11T08:27:26.000075Z","shell.execute_reply":"2026-09-11T08:27:26.987541Z"}},"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-11T08:30:44.458961Z","iopub.execute_input":"2026-09-11T08:30:44.459568Z","iopub.status.idle":"2026-09-11T08:30:44.463942Z","shell.execute_reply.started":"2026-09-11T08:30:44.459536Z","shell.execute_reply":"2026-09-11T08:30:44.462895Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary',\n        batch_size=BATCH_SIE, \n        target_size=IMAGE_SIZE\n)\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:30:46.653352Z","iopub.execute_input":"2026-09-11T08:30:46.654286Z","iopub.status.idle":"2026-09-11T08:30:47.235807Z","shell.execute_reply.started":"2026-09-11T08:30:46.65425Z","shell.execute_reply":"2026-09-11T08:30:47.235033Z"}},"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-11T08:30:48.73615Z","iopub.execute_input":"2026-09-11T08:30:48.736451Z","iopub.status.idle":"2026-09-11T08:30:48.743387Z","shell.execute_reply.started":"2026-09-11T08:30:48.736427Z","shell.execute_reply":"2026-09-11T08:30:48.742296Z"}},"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-11T08:30:49.610956Z","iopub.execute_input":"2026-09-11T08:30:49.611625Z","iopub.status.idle":"2026-09-11T08:30:49.880274Z","shell.execute_reply.started":"2026-09-11T08:30:49.611594Z","shell.execute_reply":"2026-09-11T08:30:49.879596Z"}},"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-11T08:30:52.389727Z","iopub.execute_input":"2026-09-11T08:30:52.390495Z","iopub.status.idle":"2026-09-11T08:30:52.397027Z","shell.execute_reply.started":"2026-09-11T08:30:52.390462Z","shell.execute_reply":"2026-09-11T08:30:52.396001Z"}},"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-11T08:33:22.000793Z","iopub.execute_input":"2026-09-11T08:33:22.001642Z","iopub.status.idle":"2026-09-11T08:47:34.542367Z","shell.execute_reply.started":"2026-09-11T08:33:22.00156Z","shell.execute_reply":"2026-09-11T08:47:34.541618Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:48:01.257132Z","iopub.execute_input":"2026-09-11T08:48:01.257454Z","iopub.status.idle":"2026-09-11T08:48:01.555433Z","shell.execute_reply.started":"2026-09-11T08:48:01.257427Z","shell.execute_reply":"2026-09-11T08:48:01.554744Z"}},"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-11T08:48:04.666653Z","iopub.execute_input":"2026-09-11T08:48:04.667501Z","iopub.status.idle":"2026-09-11T08:48:16.274355Z","shell.execute_reply.started":"2026-09-11T08:48:04.667463Z","shell.execute_reply":"2026-09-11T08:48:16.273623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:01.819083Z","iopub.execute_input":"2026-09-11T08:49:01.819855Z","iopub.status.idle":"2026-09-11T08:49:02.830104Z","shell.execute_reply.started":"2026-09-11T08:49:01.819822Z","shell.execute_reply":"2026-09-11T08:49:02.829055Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:03.720726Z","iopub.execute_input":"2026-09-11T08:49:03.721298Z","iopub.status.idle":"2026-09-11T08:49:03.728555Z","shell.execute_reply.started":"2026-09-11T08:49:03.721264Z","shell.execute_reply":"2026-09-11T08:49:03.727373Z"}},"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-11T08:49:06.453241Z","iopub.execute_input":"2026-09-11T08:49:06.454151Z","iopub.status.idle":"2026-09-11T08:49:06.495452Z","shell.execute_reply.started":"2026-09-11T08:49:06.454111Z","shell.execute_reply":"2026-09-11T08:49:06.494498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:09.971471Z","iopub.execute_input":"2026-09-11T08:49:09.972409Z","iopub.status.idle":"2026-09-11T08:49:09.980009Z","shell.execute_reply.started":"2026-09-11T08:49:09.972375Z","shell.execute_reply":"2026-09-11T08:49:09.97882Z"}},"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-11T08:49:11.495729Z","iopub.execute_input":"2026-09-11T08:49:11.496719Z","iopub.status.idle":"2026-09-11T08:49:11.505097Z","shell.execute_reply.started":"2026-09-11T08:49:11.496674Z","shell.execute_reply":"2026-09-11T08:49:11.504173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:12.707895Z","iopub.execute_input":"2026-09-11T08:49:12.708441Z","iopub.status.idle":"2026-09-11T08:49:12.747625Z","shell.execute_reply.started":"2026-09-11T08:49:12.708395Z","shell.execute_reply":"2026-09-11T08:49:12.746448Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:16.967342Z","iopub.execute_input":"2026-09-11T08:49:16.968041Z","iopub.status.idle":"2026-09-11T08:49:16.974992Z","shell.execute_reply.started":"2026-09-11T08:49:16.968008Z","shell.execute_reply":"2026-09-11T08:49:16.973869Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:18.054763Z","iopub.execute_input":"2026-09-11T08:49:18.055362Z","iopub.status.idle":"2026-09-11T08:49:18.069884Z","shell.execute_reply.started":"2026-09-11T08:49:18.055331Z","shell.execute_reply":"2026-09-11T08:49:18.068864Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:49:19.735014Z","iopub.execute_input":"2026-09-11T08:49:19.735928Z","iopub.status.idle":"2026-09-11T08:49:19.744097Z","shell.execute_reply.started":"2026-09-11T08:49:19.735885Z","shell.execute_reply":"2026-09-11T08:49:19.743163Z"}},"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-11T08:49:20.907926Z","iopub.execute_input":"2026-09-11T08:49:20.908237Z","iopub.status.idle":"2026-09-11T08:49:20.991629Z","shell.execute_reply.started":"2026-09-11T08:49:20.908215Z","shell.execute_reply":"2026-09-11T08:49:20.990894Z"}},"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-11T08:49:24.903151Z","iopub.execute_input":"2026-09-11T08:49:24.903472Z","iopub.status.idle":"2026-09-11T08:49:24.910404Z","shell.execute_reply.started":"2026-09-11T08:49:24.903446Z","shell.execute_reply":"2026-09-11T08:49:24.909346Z"}},"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-11T08:49:29.416388Z","iopub.execute_input":"2026-09-11T08:49:29.416736Z","iopub.status.idle":"2026-09-11T08:49:34.362097Z","shell.execute_reply.started":"2026-09-11T08:49:29.416709Z","shell.execute_reply":"2026-09-11T08:49:34.360513Z"}},"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-11T08:49:46.435082Z","iopub.execute_input":"2026-09-11T08:49:46.435878Z","iopub.status.idle":"2026-09-11T08:49:51.44219Z","shell.execute_reply.started":"2026-09-11T08:49:46.435844Z","shell.execute_reply":"2026-09-11T08:49:51.441052Z"}},"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-11T08:50:27.669979Z","iopub.execute_input":"2026-09-11T08:50:27.670349Z","iopub.status.idle":"2026-09-11T08:50:27.676551Z","shell.execute_reply.started":"2026-09-11T08:50:27.670321Z","shell.execute_reply":"2026-09-11T08:50:27.675475Z"}},"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-11T08:50:30.382298Z","iopub.execute_input":"2026-09-11T08:50:30.383078Z","iopub.status.idle":"2026-09-11T08:50:35.0953Z","shell.execute_reply.started":"2026-09-11T08:50:30.383043Z","shell.execute_reply":"2026-09-11T08:50:35.091665Z"}},"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-11T08:50:51.768681Z","iopub.execute_input":"2026-09-11T08:50:51.769424Z","iopub.status.idle":"2026-09-11T08:51:13.107224Z","shell.execute_reply.started":"2026-09-11T08:50:51.769392Z","shell.execute_reply":"2026-09-11T08:51:13.106162Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:52:48.571048Z","iopub.execute_input":"2026-09-11T08:52:48.572111Z","iopub.status.idle":"2026-09-11T08:52:48.579461Z","shell.execute_reply.started":"2026-09-11T08:52:48.572065Z","shell.execute_reply":"2026-09-11T08:52:48.578515Z"}},"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-11T08:53:25.110891Z","iopub.execute_input":"2026-09-11T08:53:25.111264Z","iopub.status.idle":"2026-09-11T08:53:26.389322Z","shell.execute_reply.started":"2026-09-11T08:53:25.111237Z","shell.execute_reply":"2026-09-11T08:53:26.388456Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T08:54:10.762671Z","iopub.execute_input":"2026-09-11T08:54:10.762996Z","iopub.status.idle":"2026-09-11T08:54:10.767604Z","shell.execute_reply.started":"2026-09-11T08:54:10.762972Z","shell.execute_reply":"2026-09-11T08:54:10.766381Z"}},"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=(200, 200, 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-11T09:10:13.986285Z","iopub.execute_input":"2026-09-11T09:10:13.986624Z","iopub.status.idle":"2026-09-11T09:10:13.9937Z","shell.execute_reply.started":"2026-09-11T09:10:13.986599Z","shell.execute_reply":"2026-09-11T09:10:13.992745Z"}},"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-02-16T07:06:10.528649Z","iopub.execute_input":"2026-02-16T07:06:10.529339Z","iopub.status.idle":"2026-02-16T07:06:10.532994Z","shell.execute_reply.started":"2026-02-16T07:06:10.529306Z","shell.execute_reply":"2026-02-16T07:06:10.532148Z"}},"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-02-16T07:06:18.061672Z","iopub.execute_input":"2026-02-16T07:06:18.062335Z","iopub.status.idle":"2026-02-16T07:06:18.065876Z","shell.execute_reply.started":"2026-02-16T07:06:18.062302Z","shell.execute_reply":"2026-02-16T07:06:18.064909Z"}},"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-02-16T07:03:43.521957Z","iopub.execute_input":"2026-02-16T07:03:43.522229Z","iopub.status.idle":"2026-02-16T07:03:43.525953Z","shell.execute_reply.started":"2026-02-16T07:03:43.522206Z","shell.execute_reply":"2026-02-16T07:03:43.525102Z"}},"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-02-16T07:03:43.527034Z","iopub.execute_input":"2026-02-16T07:03:43.527566Z","iopub.status.idle":"2026-02-16T07:03:43.533544Z","shell.execute_reply.started":"2026-02-16T07:03:43.527544Z","shell.execute_reply":"2026-02-16T07:03:43.532816Z"}},"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-11T09:10:25.025842Z","iopub.execute_input":"2026-09-11T09:10:25.02653Z","iopub.status.idle":"2026-09-11T09:10:25.414392Z","shell.execute_reply.started":"2026-09-11T09:10:25.026496Z","shell.execute_reply":"2026-09-11T09:10:25.413339Z"}},"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-02-16T07:03:43.910675Z","iopub.execute_input":"2026-02-16T07:03:43.910954Z","iopub.status.idle":"2026-02-16T07:03:43.914695Z","shell.execute_reply.started":"2026-02-16T07:03:43.91093Z","shell.execute_reply":"2026-02-16T07:03:43.913724Z"}},"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-02-16T07:03:43.915763Z","iopub.execute_input":"2026-02-16T07:03:43.916044Z","iopub.status.idle":"2026-02-16T07:03:43.92276Z","shell.execute_reply.started":"2026-02-16T07:03:43.916014Z","shell.execute_reply":"2026-02-16T07:03:43.921957Z"}},"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-02-16T07:03:43.923787Z","iopub.execute_input":"2026-02-16T07:03:43.924063Z","iopub.status.idle":"2026-02-16T07:03:43.930359Z","shell.execute_reply.started":"2026-02-16T07:03:43.924041Z","shell.execute_reply":"2026-02-16T07:03:43.9295Z"}},"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-02-16T07:05:42.844519Z","iopub.execute_input":"2026-02-16T07:05:42.845298Z","iopub.status.idle":"2026-02-16T07:05:42.849027Z","shell.execute_reply.started":"2026-02-16T07:05:42.845261Z","shell.execute_reply":"2026-02-16T07:05:42.848238Z"}},"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-11T09:10:45.275374Z","iopub.execute_input":"2026-09-11T09:10:45.276228Z","iopub.status.idle":"2026-09-11T09:10:45.281486Z","shell.execute_reply.started":"2026-09-11T09:10:45.276194Z","shell.execute_reply":"2026-09-11T09:10:45.280644Z"}},"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-11T09:10:46.468897Z","iopub.execute_input":"2026-09-11T09:10:46.469559Z","iopub.status.idle":"2026-09-11T09:15:14.509037Z","shell.execute_reply.started":"2026-09-11T09:10:46.469526Z","shell.execute_reply":"2026-09-11T09:15:14.508251Z"}},"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-11T09:16:37.921155Z","iopub.execute_input":"2026-09-11T09:16:37.921889Z","iopub.status.idle":"2026-09-11T09:17:18.772827Z","shell.execute_reply.started":"2026-09-11T09:16:37.921861Z","shell.execute_reply":"2026-09-11T09:17:18.771736Z"}},"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(\n        include_top=False,\n        input_shape=(299, 299, 3)\n    )\n\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n\n    class1 = Dense(\n        1024,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    )(flat1)\n\n    class2 = Dense(\n        512,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    )(class1)\n\n    class3 = Dense(\n        256,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    )(class2)\n\n    class4 = Dense(\n        128,\n        activation='relu',\n        kernel_initializer='he_uniform'\n    )(class3)\n\n    output = Dense(1, activation='sigmoid')(class4)\n\n    # define new model\n    model = Model(\n        inputs=model.inputs,\n        outputs=output\n    )\n\n    # compile model\n    opt = SGD(lr=0.001, momentum=0.9)\n\n    model.compile(\n        optimizer=opt,\n        loss='binary_crossentropy',\n        metrics=['accuracy']\n    )\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T09:23:34.00513Z","iopub.execute_input":"2026-09-11T09:23:34.006126Z","iopub.status.idle":"2026-09-11T09:23:34.013699Z","shell.execute_reply.started":"2026-09-11T09:23:34.00609Z","shell.execute_reply":"2026-09-11T09:23:34.012636Z"}},"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-11T09:23:37.61424Z","iopub.execute_input":"2026-09-11T09:23:37.614554Z","iopub.status.idle":"2026-09-11T09:23:39.793075Z","shell.execute_reply.started":"2026-09-11T09:23:37.614529Z","shell.execute_reply":"2026-09-11T09:23:39.792141Z"},"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-11T09:23:40.865643Z","iopub.execute_input":"2026-09-11T09:23:40.866401Z","iopub.status.idle":"2026-09-11T09:23:40.872776Z","shell.execute_reply.started":"2026-09-11T09:23:40.866369Z","shell.execute_reply":"2026-09-11T09:23:40.871825Z"}},"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-11T09:23:42.202711Z","iopub.execute_input":"2026-09-11T09:23:42.203548Z","iopub.status.idle":"2026-09-11T09:23:42.209234Z","shell.execute_reply.started":"2026-09-11T09:23:42.203514Z","shell.execute_reply":"2026-09-11T09:23:42.208406Z"}},"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":"","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-11T09:27:39.687782Z","iopub.execute_input":"2026-09-11T09:27:39.688771Z","iopub.status.idle":"2026-09-11T09:27:39.696421Z","shell.execute_reply.started":"2026-09-11T09:27:39.688736Z","shell.execute_reply":"2026-09-11T09:27:39.695365Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true},"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},"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-11T09:27:43.334403Z","iopub.execute_input":"2026-09-11T09:27:43.335307Z","iopub.status.idle":"2026-09-11T09:28:04.338561Z","shell.execute_reply.started":"2026-09-11T09:27:43.335274Z","shell.execute_reply":"2026-09-11T09:28:04.33783Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-11T09:29:19.421695Z","iopub.execute_input":"2026-09-11T09:29:19.422557Z","iopub.status.idle":"2026-09-11T09:29:19.519915Z","shell.execute_reply.started":"2026-09-11T09:29:19.422525Z","shell.execute_reply":"2026-09-11T09:29:19.51905Z"}},"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-11T09:29:20.551924Z","iopub.execute_input":"2026-09-11T09:29:20.552234Z","iopub.status.idle":"2026-09-11T09:29:20.558737Z","shell.execute_reply.started":"2026-09-11T09:29:20.552209Z","shell.execute_reply":"2026-09-11T09:29:20.557634Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}