{"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":"gpu","dataSources":[{"sourceType":"competition","sourceId":3362}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2026-09-08T08:41:00.791967Z","iopub.execute_input":"2026-09-08T08:41:00.7927Z","iopub.status.idle":"2026-09-08T08:41:01.103315Z","shell.execute_reply.started":"2026-09-08T08:41:00.792646Z","shell.execute_reply":"2026-09-08T08:41:01.102438Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:01.831485Z","iopub.execute_input":"2026-09-08T08:41:01.832425Z","iopub.status.idle":"2026-09-08T08:41:02.82822Z","shell.execute_reply.started":"2026-09-08T08:41:01.832392Z","shell.execute_reply":"2026-09-08T08:41:02.827097Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"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-08T08:41:05.491553Z","iopub.execute_input":"2026-09-08T08:41:05.491896Z","iopub.status.idle":"2026-09-08T08:41:15.613072Z","shell.execute_reply.started":"2026-09-08T08:41:05.491868Z","shell.execute_reply":"2026-09-08T08:41:15.611998Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:15.614664Z","iopub.execute_input":"2026-09-08T08:41:15.614994Z","iopub.status.idle":"2026-09-08T08:41:16.580166Z","shell.execute_reply.started":"2026-09-08T08:41:15.614969Z","shell.execute_reply":"2026-09-08T08:41:16.579237Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:18.565694Z","iopub.execute_input":"2026-09-08T08:41:18.566078Z","iopub.status.idle":"2026-09-08T08:41:19.543356Z","shell.execute_reply.started":"2026-09-08T08:41:18.566046Z","shell.execute_reply":"2026-09-08T08:41:19.542389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:20.446419Z","iopub.execute_input":"2026-09-08T08:41:20.447246Z","iopub.status.idle":"2026-09-08T08:41:21.452487Z","shell.execute_reply.started":"2026-09-08T08:41:20.447209Z","shell.execute_reply":"2026-09-08T08:41:21.451522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:23.171406Z","iopub.execute_input":"2026-09-08T08:41:23.17237Z","iopub.status.idle":"2026-09-08T08:41:24.236563Z","shell.execute_reply.started":"2026-09-08T08:41:23.172333Z","shell.execute_reply":"2026-09-08T08:41:24.235037Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:24.239065Z","iopub.execute_input":"2026-09-08T08:41:24.239467Z","iopub.status.idle":"2026-09-08T08:41:24.24428Z","shell.execute_reply.started":"2026-09-08T08:41:24.239428Z","shell.execute_reply":"2026-09-08T08:41:24.243187Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog 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 + '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-08T08:41:24.245443Z","iopub.execute_input":"2026-09-08T08:41:24.24565Z","iopub.status.idle":"2026-09-08T08:41:25.336368Z","shell.execute_reply.started":"2026-09-08T08:41:24.245631Z","shell.execute_reply":"2026-09-08T08:41:25.335254Z"},"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-08T08:41:28.633279Z","iopub.execute_input":"2026-09-08T08:41:28.634168Z","iopub.status.idle":"2026-09-08T08:41:29.57629Z","shell.execute_reply.started":"2026-09-08T08:41:28.634135Z","shell.execute_reply":"2026-09-08T08:41:29.575442Z"},"trusted":true},"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-08T08:41:47.245559Z","iopub.execute_input":"2026-09-08T08:41:47.246675Z","iopub.status.idle":"2026-09-08T08:41:47.251747Z","shell.execute_reply.started":"2026-09-08T08:41:47.246637Z","shell.execute_reply":"2026-09-08T08:41:47.250722Z"}},"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-08T08:41:49.850497Z","iopub.execute_input":"2026-09-08T08:41:49.851426Z","iopub.status.idle":"2026-09-08T08:41:49.855619Z","shell.execute_reply.started":"2026-09-08T08:41:49.851392Z","shell.execute_reply":"2026-09-08T08:41:49.854582Z"},"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-08T08:41:54.54751Z","iopub.execute_input":"2026-09-08T08:41:54.548427Z","iopub.status.idle":"2026-09-08T08:41:54.552703Z","shell.execute_reply.started":"2026-09-08T08:41:54.548392Z","shell.execute_reply":"2026-09-08T08:41:54.55153Z"},"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-08T08:41:55.984406Z","iopub.execute_input":"2026-09-08T08:41:55.985356Z","iopub.status.idle":"2026-09-08T08:41:55.991349Z","shell.execute_reply.started":"2026-09-08T08:41:55.98532Z","shell.execute_reply":"2026-09-08T08:41:55.990285Z"},"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-08T08:41:57.923301Z","iopub.execute_input":"2026-09-08T08:41:57.923609Z","iopub.status.idle":"2026-09-08T08:41:58.923438Z","shell.execute_reply.started":"2026-09-08T08:41:57.923586Z","shell.execute_reply":"2026-09-08T08:41:58.92213Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:41:58.925587Z","iopub.execute_input":"2026-09-08T08:41:58.925928Z","iopub.status.idle":"2026-09-08T08:41:59.918218Z","shell.execute_reply.started":"2026-09-08T08:41:58.925902Z","shell.execute_reply":"2026-09-08T08:41:59.917203Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:03.326635Z","iopub.execute_input":"2026-09-08T08:42:03.327439Z","iopub.status.idle":"2026-09-08T08:42:04.310393Z","shell.execute_reply.started":"2026-09-08T08:42:03.327402Z","shell.execute_reply":"2026-09-08T08:42:04.309141Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:04.312673Z","iopub.execute_input":"2026-09-08T08:42:04.313291Z","iopub.status.idle":"2026-09-08T08:42:05.292229Z","shell.execute_reply.started":"2026-09-08T08:42:04.313261Z","shell.execute_reply":"2026-09-08T08:42:05.291264Z"}},"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-08T08:42:06.80301Z","iopub.execute_input":"2026-09-08T08:42:06.803545Z","iopub.status.idle":"2026-09-08T08:42:08.82696Z","shell.execute_reply.started":"2026-09-08T08:42:06.80351Z","shell.execute_reply":"2026-09-08T08:42:08.825778Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:11.279502Z","iopub.execute_input":"2026-09-08T08:42:11.280272Z","iopub.status.idle":"2026-09-08T08:42:11.285289Z","shell.execute_reply.started":"2026-09-08T08:42:11.280239Z","shell.execute_reply":"2026-09-08T08:42:11.2844Z"}},"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-08T08:42:11.55339Z","iopub.execute_input":"2026-09-08T08:42:11.554181Z","iopub.status.idle":"2026-09-08T08:42:13.635278Z","shell.execute_reply.started":"2026-09-08T08:42:11.554149Z","shell.execute_reply":"2026-09-08T08:42:13.634184Z"},"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-08T08:42:13.637041Z","iopub.execute_input":"2026-09-08T08:42:13.637361Z","iopub.status.idle":"2026-09-08T08:42:15.67235Z","shell.execute_reply.started":"2026-09-08T08:42:13.637334Z","shell.execute_reply":"2026-09-08T08:42:15.671088Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2026-09-08T08:42:16.61697Z","iopub.execute_input":"2026-09-08T08:42:16.617863Z","iopub.status.idle":"2026-09-08T08:42:26.60028Z","shell.execute_reply.started":"2026-09-08T08:42:16.617825Z","shell.execute_reply":"2026-09-08T08:42:26.598805Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2026-09-08T08:42:26.602647Z","iopub.execute_input":"2026-09-08T08:42:26.602934Z","iopub.status.idle":"2026-09-08T08:42:26.617414Z","shell.execute_reply.started":"2026-09-08T08:42:26.602911Z","shell.execute_reply":"2026-09-08T08:42:26.616528Z"},"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-08T08:42:30.786837Z","iopub.execute_input":"2026-09-08T08:42:30.787647Z","iopub.status.idle":"2026-09-08T08:42:30.791671Z","shell.execute_reply.started":"2026-09-08T08:42:30.787612Z","shell.execute_reply":"2026-09-08T08:42:30.790457Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, MaxPooling2D, Flatten, Dense\n\nmodel = Sequential()\nmodel.add(Input(shape=(64, 64, 3)))   # ภาพสี ขนาด 64x64   # <-- ต้องเพิ่มบรรทัดนี้\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:31.213497Z","iopub.execute_input":"2026-09-08T08:42:31.214512Z","iopub.status.idle":"2026-09-08T08:42:32.361475Z","shell.execute_reply.started":"2026-09-08T08:42:31.214478Z","shell.execute_reply":"2026-09-08T08:42:32.360807Z"}},"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-08T08:42:35.074279Z","iopub.execute_input":"2026-09-08T08:42:35.075069Z","iopub.status.idle":"2026-09-08T08:42:35.081192Z","shell.execute_reply.started":"2026-09-08T08:42:35.075037Z","shell.execute_reply":"2026-09-08T08:42:35.080085Z"}},"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-08T08:42:38.036329Z","iopub.execute_input":"2026-09-08T08:42:38.037295Z","iopub.status.idle":"2026-09-08T08:42:38.042315Z","shell.execute_reply.started":"2026-09-08T08:42:38.037257Z","shell.execute_reply":"2026-09-08T08:42:38.041464Z"}},"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-08T08:42:40.23373Z","iopub.execute_input":"2026-09-08T08:42:40.234498Z","iopub.status.idle":"2026-09-08T08:42:40.240632Z","shell.execute_reply.started":"2026-09-08T08:42:40.234465Z","shell.execute_reply":"2026-09-08T08:42:40.23933Z"}},"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-08T08:42:42.519796Z","iopub.execute_input":"2026-09-08T08:42:42.520785Z","iopub.status.idle":"2026-09-08T08:42:42.526491Z","shell.execute_reply.started":"2026-09-08T08:42:42.520752Z","shell.execute_reply":"2026-09-08T08:42:42.525463Z"}},"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-08T08:42:44.19048Z","iopub.execute_input":"2026-09-08T08:42:44.190795Z","iopub.status.idle":"2026-09-08T08:42:44.268119Z","shell.execute_reply.started":"2026-09-08T08:42:44.19077Z","shell.execute_reply":"2026-09-08T08:42:44.267165Z"}},"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-08T08:42:46.367803Z","iopub.execute_input":"2026-09-08T08:42:46.368616Z","iopub.status.idle":"2026-09-08T08:42:46.37438Z","shell.execute_reply.started":"2026-09-08T08:42:46.368583Z","shell.execute_reply":"2026-09-08T08:42:46.373418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls dataset_dogs_vs_cats/train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:48.165541Z","iopub.execute_input":"2026-09-08T08:42:48.166537Z","iopub.status.idle":"2026-09-08T08:42:49.159725Z","shell.execute_reply.started":"2026-09-08T08:42:48.166502Z","shell.execute_reply":"2026-09-08T08:42:49.158737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Hyperparameter => changeble\nIMAGE_SIZE = (200, 200)\nBATCH_SIZE = 64\nEPOCHS =20","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:49.16147Z","iopub.execute_input":"2026-09-08T08:42:49.161783Z","iopub.status.idle":"2026-09-08T08:42:49.166379Z","shell.execute_reply.started":"2026-09-08T08:42:49.161758Z","shell.execute_reply":"2026-09-08T08:42:49.165537Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary',\n    batch_size=BATCH_SIZE, \n    target_size=(IMAGE_SIZE))\ntype(train_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:52.422448Z","iopub.execute_input":"2026-09-08T08:42:52.422779Z","iopub.status.idle":"2026-09-08T08:42:52.909225Z","shell.execute_reply.started":"2026-09-08T08:42:52.422752Z","shell.execute_reply":"2026-09-08T08:42:52.908167Z"}},"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-08T08:42:53.90467Z","iopub.execute_input":"2026-09-08T08:42:53.905587Z","iopub.status.idle":"2026-09-08T08:42:53.912445Z","shell.execute_reply.started":"2026-09-08T08:42:53.905556Z","shell.execute_reply":"2026-09-08T08:42:53.911236Z"}},"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))\ntype(val_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:54.821911Z","iopub.execute_input":"2026-09-08T08:42:54.822297Z","iopub.status.idle":"2026-09-08T08:42:54.999457Z","shell.execute_reply.started":"2026-09-08T08:42:54.822267Z","shell.execute_reply":"2026-09-08T08:42:54.998455Z"}},"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-08T08:42:57.064808Z","iopub.execute_input":"2026-09-08T08:42:57.06516Z","iopub.status.idle":"2026-09-08T08:42:57.071554Z","shell.execute_reply.started":"2026-09-08T08:42:57.065134Z","shell.execute_reply":"2026-09-08T08:42:57.07067Z"}},"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, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T08:42:58.045247Z","iopub.execute_input":"2026-09-08T08:42:58.045582Z","iopub.status.idle":"2026-09-08T08:57:18.300615Z","shell.execute_reply.started":"2026-09-08T08:42:58.045556Z","shell.execute_reply":"2026-09-08T08:57:18.299899Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:23.366729Z","iopub.execute_input":"2026-09-08T09:08:23.367591Z","iopub.status.idle":"2026-09-08T09:08:23.650615Z","shell.execute_reply.started":"2026-09-08T09:08:23.367548Z","shell.execute_reply":"2026-09-08T09:08:23.649598Z"}},"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-08T09:08:26.476653Z","iopub.execute_input":"2026-09-08T09:08:26.477607Z","iopub.status.idle":"2026-09-08T09:08:36.750637Z","shell.execute_reply.started":"2026-09-08T09:08:26.477575Z","shell.execute_reply":"2026-09-08T09:08:36.749564Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:38.679818Z","iopub.execute_input":"2026-09-08T09:08:38.68063Z","iopub.status.idle":"2026-09-08T09:08:39.686769Z","shell.execute_reply.started":"2026-09-08T09:08:38.680597Z","shell.execute_reply":"2026-09-08T09:08:39.685752Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:42.054147Z","iopub.execute_input":"2026-09-08T09:08:42.054503Z","iopub.status.idle":"2026-09-08T09:08:42.061409Z","shell.execute_reply.started":"2026-09-08T09:08:42.054476Z","shell.execute_reply":"2026-09-08T09:08:42.060661Z"}},"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-08T09:08:43.533967Z","iopub.execute_input":"2026-09-08T09:08:43.534304Z","iopub.status.idle":"2026-09-08T09:08:43.56991Z","shell.execute_reply.started":"2026-09-08T09:08:43.534279Z","shell.execute_reply":"2026-09-08T09:08:43.569117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.columns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:46.63106Z","iopub.execute_input":"2026-09-08T09:08:46.631383Z","iopub.status.idle":"2026-09-08T09:08:46.639006Z","shell.execute_reply.started":"2026-09-08T09:08:46.63136Z","shell.execute_reply":"2026-09-08T09:08:46.638053Z"}},"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-08T09:08:47.144498Z","iopub.execute_input":"2026-09-08T09:08:47.144866Z","iopub.status.idle":"2026-09-08T09:08:47.151166Z","shell.execute_reply.started":"2026-09-08T09:08:47.144837Z","shell.execute_reply":"2026-09-08T09:08:47.150356Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:49.80707Z","iopub.execute_input":"2026-09-08T09:08:49.807899Z","iopub.status.idle":"2026-09-08T09:08:49.839765Z","shell.execute_reply.started":"2026-09-08T09:08:49.807864Z","shell.execute_reply":"2026-09-08T09:08:49.838741Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:50.25835Z","iopub.execute_input":"2026-09-08T09:08:50.259229Z","iopub.status.idle":"2026-09-08T09:08:50.267048Z","shell.execute_reply.started":"2026-09-08T09:08:50.259191Z","shell.execute_reply":"2026-09-08T09:08:50.265865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:52.176439Z","iopub.execute_input":"2026-09-08T09:08:52.17745Z","iopub.status.idle":"2026-09-08T09:08:52.188288Z","shell.execute_reply.started":"2026-09-08T09:08:52.177414Z","shell.execute_reply":"2026-09-08T09:08:52.187174Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:52.585048Z","iopub.execute_input":"2026-09-08T09:08:52.58577Z","iopub.status.idle":"2026-09-08T09:08:52.592645Z","shell.execute_reply.started":"2026-09-08T09:08:52.585727Z","shell.execute_reply":"2026-09-08T09:08:52.591703Z"}},"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-08T09:08:55.060114Z","iopub.execute_input":"2026-09-08T09:08:55.061042Z","iopub.status.idle":"2026-09-08T09:08:55.146294Z","shell.execute_reply.started":"2026-09-08T09:08:55.061009Z","shell.execute_reply":"2026-09-08T09:08:55.145443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_exmaple(images, labels):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        # if i < images.shape[0]:\n            ax.imshow(images[i])\n            ax.set_title(str(labels[i]))\n            ax.axis('off')  # Turn off axis ticks/labels for clarity\n         # ax.axis('on')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:08:57.100906Z","iopub.execute_input":"2026-09-08T09:08:57.101648Z","iopub.status.idle":"2026-09-08T09:08:57.107158Z","shell.execute_reply.started":"2026-09-08T09:08:57.101598Z","shell.execute_reply":"2026-09-08T09:08:57.106177Z"}},"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-08T09:08:59.034998Z","iopub.execute_input":"2026-09-08T09:08:59.035945Z","iopub.status.idle":"2026-09-08T09:09:04.582181Z","shell.execute_reply.started":"2026-09-08T09:08:59.035892Z","shell.execute_reply":"2026-09-08T09:09:04.581124Z"}},"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-08T09:09:04.584031Z","iopub.execute_input":"2026-09-08T09:09:04.584347Z","iopub.status.idle":"2026-09-08T09:09:09.985412Z","shell.execute_reply.started":"2026-09-08T09:09:04.584319Z","shell.execute_reply":"2026-09-08T09:09:09.984354Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        # if i < images.shape[0]:\n            ax.imshow(images[i])\n            # ax.set_title(str(labels[i]))\n            ax.axis('off')  # Turn off axis ticks/labels for clarity\n         # ax.axis('on')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:09:15.33647Z","iopub.execute_input":"2026-09-08T09:09:15.336934Z","iopub.status.idle":"2026-09-08T09:09:15.342482Z","shell.execute_reply.started":"2026-09-08T09:09:15.336899Z","shell.execute_reply":"2026-09-08T09:09:15.341576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape\nplot_exmaple_test(test_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:09:16.519336Z","iopub.execute_input":"2026-09-08T09:09:16.520057Z","iopub.status.idle":"2026-09-08T09:09:20.296192Z","shell.execute_reply.started":"2026-09-08T09:09:16.520023Z","shell.execute_reply":"2026-09-08T09:09:20.294644Z"}},"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-08T09:09:25.318637Z","iopub.execute_input":"2026-09-08T09:09:25.319469Z","iopub.status.idle":"2026-09-08T09:09:45.996334Z","shell.execute_reply.started":"2026-09-08T09:09:25.319432Z","shell.execute_reply":"2026-09-08T09:09:45.995533Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"preds[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:09:45.99756Z","iopub.execute_input":"2026-09-08T09:09:45.997933Z","iopub.status.idle":"2026-09-08T09:09:46.005815Z","shell.execute_reply.started":"2026-09-08T09:09:45.997908Z","shell.execute_reply":"2026-09-08T09:09:46.004879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def plot_exmaple_test(images, indices):\n    # Assuming test_images is a numpy array with shape (64, height, width, channels)\n    fig, axes = plt.subplots(8, 8, figsize=(16, 16))\n    axes = axes.flatten()  # Flatten the 8x8 grid into a list for easy iteration\n    \n    for i, ax in enumerate(axes):\n        # Ensure there are enough images in the batch before plotting\n        # if i < images.shape[0]:\n            ax.imshow(images[i])\n            # ax.set_title(str(labels[i]))\n            ax.axis('off')  # Turn off axis ticks/labels for clarity\n         # ax.axis('on')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:09:51.44908Z","iopub.execute_input":"2026-09-08T09:09:51.450018Z","iopub.status.idle":"2026-09-08T09:09:51.455266Z","shell.execute_reply.started":"2026-09-08T09:09:51.449986Z","shell.execute_reply":"2026-09-08T09:09:51.454164Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\nindices = list(range(len(test_images)))\n\nplot_exmaple_test(test_images, indices)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:09:54.490575Z","iopub.execute_input":"2026-09-08T09:09:54.491014Z","iopub.status.idle":"2026-09-08T09:09:58.431724Z","shell.execute_reply.started":"2026-09-08T09:09:54.490985Z","shell.execute_reply":"2026-09-08T09:09:58.430172Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\n\nmodel = Sequential()\nmodel.add(Input(shape=(200, 200, 3)))\n\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D((2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])\nprint(model.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:10:03.777792Z","iopub.execute_input":"2026-09-08T09:10:03.778668Z","iopub.status.idle":"2026-09-08T09:10:03.930844Z","shell.execute_reply.started":"2026-09-08T09:10:03.778637Z","shell.execute_reply":"2026-09-08T09:10:03.929746Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\n\nearly_stop = EarlyStopping(monitor='val_accuracy', patience=5, restore_best_weights=True)\ncheckpoint = ModelCheckpoint('best_model.h5', monitor='val_accuracy', save_best_only=True)\n\nhistory = model.fit(\n    train_it,\n    validation_data=val_it,\n    epochs=30,\n    callbacks=[early_stop, checkpoint]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:13:52.860477Z","iopub.execute_input":"2026-09-08T09:13:52.861284Z","iopub.status.idle":"2026-09-08T09:19:07.686668Z","shell.execute_reply.started":"2026-09-08T09:13:52.86125Z","shell.execute_reply":"2026-09-08T09:19:07.685737Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# ดึงข้อมูล batch จาก test generator (ไม่มี label)\ntest_images = test_it.__next__()\n\n# สุ่มเลือก index 10 รูปจาก batch\nnum_samples = 10\nindices = np.random.choice(len(test_images), num_samples, replace=False)\n\n# Predict\npredictions = model.predict(test_images[indices])\npredicted_classes = (predictions > 0.5).astype(int).flatten()\n\n# class_indices จาก train_it: {'cats': 0, 'dogs': 1}\nclass_labels = {v: k for k, v in train_it.class_indices.items()}\n\nfig, axes = plt.subplots(2, 5, figsize=(15, 6))\naxes = axes.flatten()\n\nfor i, idx in enumerate(indices):\n    ax = axes[i]\n    ax.imshow(test_images[idx])\n    pred_label = predicted_classes[i]\n    confidence = predictions[i][0]\n    \n    title = f\"Pred: {class_labels[pred_label]} ({confidence:.2f})\"\n    ax.set_title(title, fontsize=10)\n    ax.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-08T09:20:15.361516Z","iopub.execute_input":"2026-09-08T09:20:15.361893Z","iopub.status.idle":"2026-09-08T09:20:16.8233Z","shell.execute_reply.started":"2026-09-08T09:20:15.361863Z","shell.execute_reply":"2026-09-08T09:20:16.820064Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(train_it.class_indices)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#09-06-2026\nstop","metadata":{"trusted":true},"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-06T02:57:53.719609Z","iopub.execute_input":"2026-09-06T02:57:53.719902Z","iopub.status.idle":"2026-09-06T02:57:53.726874Z","shell.execute_reply.started":"2026-09-06T02:57:53.719877Z","shell.execute_reply":"2026-09-06T02:57:53.725752Z"}},"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-06T02:57:58.955713Z","iopub.execute_input":"2026-09-06T02:57:58.956616Z","iopub.status.idle":"2026-09-06T02:57:58.960422Z","shell.execute_reply.started":"2026-09-06T02:57:58.956583Z","shell.execute_reply":"2026-09-06T02:57:58.95943Z"}},"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-06T02:57:59.389192Z","iopub.execute_input":"2026-09-06T02:57:59.389605Z","iopub.status.idle":"2026-09-06T02:57:59.394162Z","shell.execute_reply.started":"2026-09-06T02:57:59.389554Z","shell.execute_reply":"2026-09-06T02:57:59.393022Z"}},"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-06T02:58:01.154401Z","iopub.execute_input":"2026-09-06T02:58:01.155304Z","iopub.status.idle":"2026-09-06T02:58:01.1593Z","shell.execute_reply.started":"2026-09-06T02:58:01.155268Z","shell.execute_reply":"2026-09-06T02:58:01.15819Z"}},"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-06T02:58:01.362636Z","iopub.execute_input":"2026-09-06T02:58:01.363501Z","iopub.status.idle":"2026-09-06T02:58:01.368815Z","shell.execute_reply.started":"2026-09-06T02:58:01.36347Z","shell.execute_reply":"2026-09-06T02:58:01.367788Z"}},"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-06T02:58:02.245229Z","iopub.execute_input":"2026-09-06T02:58:02.246241Z","iopub.status.idle":"2026-09-06T02:58:03.035666Z","shell.execute_reply.started":"2026-09-06T02:58:02.246203Z","shell.execute_reply":"2026-09-06T02:58:03.034811Z"}},"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-06T02:58:06.202271Z","iopub.execute_input":"2026-09-06T02:58:06.20315Z","iopub.status.idle":"2026-09-06T02:58:06.2072Z","shell.execute_reply.started":"2026-09-06T02:58:06.203117Z","shell.execute_reply":"2026-09-06T02:58:06.2062Z"}},"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-06T02:58:06.3593Z","iopub.execute_input":"2026-09-06T02:58:06.359595Z","iopub.status.idle":"2026-09-06T02:58:06.363947Z","shell.execute_reply.started":"2026-09-06T02:58:06.35957Z","shell.execute_reply":"2026-09-06T02:58:06.363189Z"}},"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-06T02:58:09.917833Z","iopub.execute_input":"2026-09-06T02:58:09.918205Z","iopub.status.idle":"2026-09-06T02:58:09.924011Z","shell.execute_reply.started":"2026-09-06T02:58:09.918175Z","shell.execute_reply":"2026-09-06T02:58:09.923041Z"}},"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-06T02:58:11.686672Z","iopub.execute_input":"2026-09-06T02:58:11.687368Z","iopub.status.idle":"2026-09-06T03:01:53.350445Z","shell.execute_reply.started":"2026-09-06T02:58:11.687334Z","shell.execute_reply":"2026-09-06T03:01:53.349482Z"}},"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-06T03:01:53.351861Z","iopub.execute_input":"2026-09-06T03:01:53.352181Z","iopub.status.idle":"2026-09-06T03:02:44.386809Z","shell.execute_reply.started":"2026-09-06T03:01:53.352154Z","shell.execute_reply":"2026-09-06T03:02:44.385642Z"}},"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-06T03:07:37.30795Z","iopub.execute_input":"2026-09-06T03:07:37.308844Z","iopub.status.idle":"2026-09-06T03:07:37.31611Z","shell.execute_reply.started":"2026-09-06T03:07:37.308811Z","shell.execute_reply":"2026-09-06T03:07:37.314957Z"}},"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-06T03:07:39.336836Z","iopub.execute_input":"2026-09-06T03:07:39.33779Z","iopub.status.idle":"2026-09-06T03:07:42.374474Z","shell.execute_reply.started":"2026-09-06T03:07:39.337754Z","shell.execute_reply":"2026-09-06T03:07:42.372899Z"},"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-06T03:07:44.335057Z","iopub.execute_input":"2026-09-06T03:07:44.335369Z","iopub.status.idle":"2026-09-06T03:07:44.341527Z","shell.execute_reply.started":"2026-09-06T03:07:44.335346Z","shell.execute_reply":"2026-09-06T03:07:44.340547Z"}},"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-06T03:07:46.067611Z","iopub.execute_input":"2026-09-06T03:07:46.067928Z","iopub.status.idle":"2026-09-06T03:07:46.074169Z","shell.execute_reply.started":"2026-09-06T03:07:46.067902Z","shell.execute_reply":"2026-09-06T03:07:46.073142Z"}},"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-06T04:34:29.321023Z","iopub.execute_input":"2026-09-06T04:34:29.321398Z","iopub.status.idle":"2026-09-06T04:34:30.340457Z","shell.execute_reply.started":"2026-09-06T04:34:29.321362Z","shell.execute_reply":"2026-09-06T04:34:30.339231Z"}},"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-06T03:07:56.59913Z","iopub.execute_input":"2026-09-06T03:07:56.600014Z","iopub.status.idle":"2026-09-06T03:07:56.606899Z","shell.execute_reply.started":"2026-09-06T03:07:56.599961Z","shell.execute_reply":"2026-09-06T03:07:56.605852Z"}},"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-06T03:08:04.61035Z","iopub.execute_input":"2026-09-06T03:08:04.610658Z","iopub.status.idle":"2026-09-06T03:08:04.614957Z","shell.execute_reply.started":"2026-09-06T03:08:04.610633Z","shell.execute_reply":"2026-09-06T03:08:04.614072Z"}},"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-06T03:08:04.798584Z","iopub.execute_input":"2026-09-06T03:08:04.799394Z","iopub.status.idle":"2026-09-06T03:08:04.803059Z","shell.execute_reply.started":"2026-09-06T03:08:04.799358Z","shell.execute_reply":"2026-09-06T03:08:04.802252Z"}},"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-06T03:08:05.159736Z","iopub.execute_input":"2026-09-06T03:08:05.160459Z","iopub.status.idle":"2026-09-06T03:08:05.164123Z","shell.execute_reply.started":"2026-09-06T03:08:05.160431Z","shell.execute_reply":"2026-09-06T03:08:05.163264Z"}},"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-06T03:08:06.964685Z","iopub.execute_input":"2026-09-06T03:08:06.965513Z","iopub.status.idle":"2026-09-06T03:08:08.317536Z","shell.execute_reply.started":"2026-09-06T03:08:06.965479Z","shell.execute_reply":"2026-09-06T03:08:08.316057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true},"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}