{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":28755,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import kagglehub\n\n# Download latest version\npath = kagglehub.competition_download('dogs-vs-cats')\n\nprint(\"Path to competition files:\", path)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:43:54.056141Z","iopub.execute_input":"2026-09-12T13:43:54.056737Z","iopub.status.idle":"2026-09-12T13:43:56.009174Z","shell.execute_reply.started":"2026-09-12T13:43:54.056702Z","shell.execute_reply":"2026-09-12T13:43:56.008153Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import zipfile\n\n# path นี้อ้างอิงจากผลลัพธ์ที่คุณรันได้ใน Cell ด้านบน\nzip_path = '/kaggle/input/competitions/dogs-vs-cats/train.zip'\n\n# แตกไฟล์ zip ลงในพื้นที่ทำงานปัจจุบัน (/kaggle/working/)\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall('.')\n\nprint(\"แตกไฟล์เสร็จเรียบร้อย!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:43:56.112416Z","iopub.execute_input":"2026-09-12T13:43:56.113771Z","iopub.status.idle":"2026-09-12T13:44:03.636077Z","shell.execute_reply.started":"2026-09-12T13:43:56.113731Z","shell.execute_reply":"2026-09-12T13:44:03.635088Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:03.638004Z","iopub.execute_input":"2026-09-12T13:44:03.638353Z","iopub.status.idle":"2026-09-12T13:44:04.381856Z","shell.execute_reply.started":"2026-09-12T13:44:03.638325Z","shell.execute_reply":"2026-09-12T13:44:04.380674Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot cat photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'cat.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:04.383130Z","iopub.execute_input":"2026-09-12T13:44:04.383523Z","iopub.status.idle":"2026-09-12T13:44:05.005022Z","shell.execute_reply.started":"2026-09-12T13:44:04.383485Z","shell.execute_reply":"2026-09-12T13:44:05.003804Z"}},"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\n# 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=(100, 100))\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":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:05.007015Z","iopub.execute_input":"2026-09-12T13:44:05.007414Z","iopub.status.idle":"2026-09-12T13:44:58.386155Z","shell.execute_reply.started":"2026-09-12T13:44:05.007369Z","shell.execute_reply":"2026-09-12T13:44:58.384828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')\nprint(photos.shape, labels.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:44:58.387560Z","iopub.execute_input":"2026-09-12T13:44:58.388235Z","iopub.status.idle":"2026-09-12T13:44:59.765107Z","shell.execute_reply.started":"2026-09-12T13:44:58.388203Z","shell.execute_reply":"2026-09-12T13:44:59.763723Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from os import makedirs\n\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:46:56.965951Z","iopub.execute_input":"2026-09-12T13:46:56.967017Z","iopub.status.idle":"2026-09-12T13:46:56.973993Z","shell.execute_reply.started":"2026-09-12T13:46:56.966978Z","shell.execute_reply":"2026-09-12T13:46:56.972987Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\n\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n    src = src_directory + '/' + file\n    dst_dir = 'train/'\n    if random() < val_ratio:\n        dst_dir = 'test/'\n    if file.startswith('cat'):\n        dst = dataset_home + dst_dir + 'cats/' + file\n        copyfile(src, dst)\n    elif file.startswith('dog'):\n        dst = dataset_home + dst_dir + 'dogs/' + file\n        copyfile(src, dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:48:32.531267Z","iopub.execute_input":"2026-09-12T13:48:32.533110Z","iopub.status.idle":"2026-09-12T13:48:56.323495Z","shell.execute_reply.started":"2026-09-12T13:48:32.533056Z","shell.execute_reply":"2026-09-12T13:48:56.322497Z"}},"outputs":[],"execution_count":null},{"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\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\nfor subdir in subdirs:\n\t# create label subdirectories\n\tlabeldirs = ['dogs/', 'cats/']\n\tfor labldir in labeldirs:\n\t\tnewdir = dataset_home + subdir + labldir\n\t\tmakedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.25\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:49:36.813806Z","iopub.execute_input":"2026-09-12T13:49:36.814267Z","iopub.status.idle":"2026-09-12T13:49:41.060993Z","shell.execute_reply.started":"2026-09-12T13:49:36.814237Z","shell.execute_reply":"2026-09-12T13:49:41.058948Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\n\n# 1. สร้างตัวแปร model โครงสร้างเปล่าขึ้นมาก่อน\nmodel = Sequential()\n\n# 2. จากนั้นจึงค่อย add เลเยอร์ต่างๆ เข้าไป\n# block 1\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\n# block 2\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\n# block 3\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:50:25.977448Z","iopub.execute_input":"2026-09-12T13:50:25.977923Z","iopub.status.idle":"2026-09-12T13:50:26.210879Z","shell.execute_reply.started":"2026-09-12T13:50:25.977882Z","shell.execute_reply":"2026-09-12T13:50:26.209875Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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-12T13:50:29.425739Z","iopub.execute_input":"2026-09-12T13:50:29.426126Z","iopub.status.idle":"2026-09-12T13:50:29.433576Z","shell.execute_reply.started":"2026-09-12T13:50:29.426095Z","shell.execute_reply":"2026-09-12T13:50:29.432316Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# สำหรับโมเดล\nfrom tensorflow.keras.layers import Flatten, Dense\n\n# สำหรับ Cell ถัดไปที่ใช้จัดการรูปภาพ\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:52:41.250601Z","iopub.execute_input":"2026-09-12T13:52:41.250961Z","iopub.status.idle":"2026-09-12T13:52:41.258145Z","shell.execute_reply.started":"2026-09-12T13:52:41.250933Z","shell.execute_reply":"2026-09-12T13:52:41.257121Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:52:43.888052Z","iopub.execute_input":"2026-09-12T13:52:43.889204Z","iopub.status.idle":"2026-09-12T13:52:43.893607Z","shell.execute_reply.started":"2026-09-12T13:52:43.889170Z","shell.execute_reply":"2026-09-12T13:52:43.892615Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:52:45.923720Z","iopub.execute_input":"2026-09-12T13:52:45.924543Z","iopub.status.idle":"2026-09-12T13:52:46.595459Z","shell.execute_reply.started":"2026-09-12T13:52:45.924510Z","shell.execute_reply":"2026-09-12T13:52:46.594237Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.optimizers import SGD\n\n# กำหนดวิธีการปรับปรุงน้ำหนัก (Optimizer)\nopt = SGD(learning_rate=0.001, momentum=0.9)\n\n# สั่ง Compile โมเดล (loss แบบ binary เพราะแยกแค่หมากับแมว)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:57:29.998739Z","iopub.execute_input":"2026-09-12T13:57:29.999539Z","iopub.status.idle":"2026-09-12T13:57:30.011882Z","shell.execute_reply.started":"2026-09-12T13:57:29.999505Z","shell.execute_reply":"2026-09-12T13:57:30.010867Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\n\n# 1. สร้างโครงสร้างโมเดล (ตั้งแต่ต้นจนจบ)\nmodel = Sequential()\n# block 1\nmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\nmodel.add(MaxPooling2D((2, 2)))\n# block 2\nmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\n# block 3\nmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\nmodel.add(MaxPooling2D((2, 2)))\n\n# --- ส่วนที่ขาดหายไป: แปลงเป็น 1 มิติและตัดสินใจ ---\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# 2. สั่ง Compile โมเดลใหม่\nopt = SGD(learning_rate=0.001, momentum=0.9)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\nprint(\"เตรียมโมเดลเสร็จสมบูรณ์!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:59:00.616067Z","iopub.execute_input":"2026-09-12T13:59:00.617103Z","iopub.status.idle":"2026-09-12T13:59:00.743213Z","shell.execute_reply.started":"2026-09-12T13:59:00.617068Z","shell.execute_reply":"2026-09-12T13:59:00.742191Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nhistory = model.fit(train_it, steps_per_epoch=len(train_it),\n                    validation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T13:59:05.221512Z","iopub.execute_input":"2026-09-12T13:59:05.222529Z","iopub.status.idle":"2026-09-12T14:12:32.652813Z","shell.execute_reply.started":"2026-09-12T13:59:05.222494Z","shell.execute_reply":"2026-09-12T14:12:32.649963Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:12:46.791218Z","iopub.execute_input":"2026-09-12T14:12:46.792229Z","iopub.status.idle":"2026-09-12T14:12:55.819820Z","shell.execute_reply.started":"2026-09-12T14:12:46.792192Z","shell.execute_reply":"2026-09-12T14:12:55.818200Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:12:55.820733Z","iopub.status.idle":"2026-09-12T14:12:55.821046Z","shell.execute_reply.started":"2026-09-12T14:12:55.820908Z","shell.execute_reply":"2026-09-12T14:12:55.820925Z"}},"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\n\n# define cnn model\ndef define_model():\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\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\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))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:12:57.583372Z","iopub.execute_input":"2026-09-12T14:12:57.584313Z","iopub.status.idle":"2026-09-12T14:12:57.600846Z","shell.execute_reply.started":"2026-09-12T14:12:57.584281Z","shell.execute_reply":"2026-09-12T14:12:57.599522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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-12T14:13:33.168795Z","iopub.execute_input":"2026-09-12T14:13:33.169124Z","iopub.status.idle":"2026-09-12T14:13:33.176872Z","shell.execute_reply.started":"2026-09-12T14:13:33.169098Z","shell.execute_reply":"2026-09-12T14:13:33.175647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\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-12T14:13:31.173206Z","iopub.execute_input":"2026-09-12T14:13:31.173612Z","iopub.status.idle":"2026-09-12T14:13:31.180726Z","shell.execute_reply.started":"2026-09-12T14:13:31.173582Z","shell.execute_reply":"2026-09-12T14:13:31.179477Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\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-12T14:13:26.440119Z","iopub.execute_input":"2026-09-12T14:13:26.440762Z","iopub.status.idle":"2026-09-12T14:13:26.448765Z","shell.execute_reply.started":"2026-09-12T14:13:26.440726Z","shell.execute_reply":"2026-09-12T14:13:26.447813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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(Dropout(0.2))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dropout(0.5))\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-12T14:13:22.264296Z","iopub.execute_input":"2026-09-12T14:13:22.265148Z","iopub.status.idle":"2026-09-12T14:13:22.273570Z","shell.execute_reply.started":"2026-09-12T14:13:22.265111Z","shell.execute_reply":"2026-09-12T14:13:22.272295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model with dropout 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.layers import Dropout\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model():\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(Dropout(0.2))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Dropout(0.2))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dropout(0.5))\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\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\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 iterator\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=50, 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))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:13:51.296319Z","iopub.execute_input":"2026-09-12T14:13:51.297278Z","iopub.status.idle":"2026-09-12T14:13:51.313841Z","shell.execute_reply.started":"2026-09-12T14:13:51.297244Z","shell.execute_reply":"2026-09-12T14:13:51.312481Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create data generators\ntrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n# prepare iterators\ntrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = test_datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:13:57.190977Z","iopub.execute_input":"2026-09-12T14:13:57.192092Z","iopub.status.idle":"2026-09-12T14:13:57.966546Z","shell.execute_reply.started":"2026-09-12T14:13:57.192054Z","shell.execute_reply":"2026-09-12T14:13:57.965531Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# baseline model with data augmentation 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\n\n# define cnn model\ndef define_model():\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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(128, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same'))\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\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generators\n\ttrain_datagen = ImageDataGenerator(rescale=1.0/255.0,\n\t\twidth_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)\n\ttest_datagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = train_datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = test_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=50, 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))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:13:59.117236Z","iopub.execute_input":"2026-09-12T14:13:59.117670Z","iopub.status.idle":"2026-09-12T14:13:59.136542Z","shell.execute_reply.started":"2026-09-12T14:13:59.117638Z","shell.execute_reply":"2026-09-12T14:13:59.135032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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-12T14:14:01.610018Z","iopub.execute_input":"2026-09-12T14:14:01.610327Z","iopub.status.idle":"2026-09-12T14:14:01.617981Z","shell.execute_reply.started":"2026-09-12T14:14:01.610302Z","shell.execute_reply":"2026-09-12T14:14:01.616669Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# vgg16 model used for transfer learning on the dogs and cats dataset\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():\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\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n\tpyplot.close()\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(featurewise_center=True)\n\t# specify imagenet mean values for centering\n\tdatagen.mean = [123.68, 116.779, 103.939]\n\t# prepare iterator\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(224, 224))\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=10, verbose=1)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))\n\t# learning curves\n\tsummarize_diagnostics(history)\n\n# entry point, run the test harness\nrun_test_harness()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:14:03.630278Z","iopub.execute_input":"2026-09-12T14:14:03.631101Z","iopub.status.idle":"2026-09-12T14:14:03.646144Z","shell.execute_reply.started":"2026-09-12T14:14:03.631067Z","shell.execute_reply":"2026-09-12T14:14:03.644753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# organize dataset into a useful structure\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\n# create directories\ndataset_home = 'finalize_dogs_vs_cats/'\n# create label subdirectories\nlabeldirs = ['dogs/', 'cats/']\nfor labldir in labeldirs:\n\tnewdir = dataset_home + labldir\n\tmakedirs(newdir, exist_ok=True)\n# copy training dataset images into subdirectories\nsrc_directory = 'dogs-vs-cats/train/'\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:14:09.149556Z","iopub.execute_input":"2026-09-12T14:14:09.150499Z","iopub.status.idle":"2026-09-12T14:14:09.162983Z","shell.execute_reply.started":"2026-09-12T14:14:09.150464Z","shell.execute_reply":"2026-09-12T14:14:09.161349Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# prepare iterator\ntrain_it = datagen.flow_from_directory('finalize_dogs_vs_cats/',\n\tclass_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:14:11.433362Z","iopub.execute_input":"2026-09-12T14:14:11.434444Z","iopub.status.idle":"2026-09-12T14:14:11.445708Z","shell.execute_reply.started":"2026-09-12T14:14:11.434371Z","shell.execute_reply":"2026-09-12T14:14:11.444617Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel.fit_generator(train_it, steps_per_epoch=len(train_it), epochs=10, verbose=0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:14:13.109284Z","iopub.execute_input":"2026-09-12T14:14:13.109647Z","iopub.status.idle":"2026-09-12T14:14:13.118966Z","shell.execute_reply.started":"2026-09-12T14:14:13.109619Z","shell.execute_reply":"2026-09-12T14:14:13.117347Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# save model\nmodel.save('final_model.h5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T14:14:18.701990Z","iopub.execute_input":"2026-09-12T14:14:18.702375Z","iopub.status.idle":"2026-09-12T14:14:18.938194Z","shell.execute_reply.started":"2026-09-12T14:14:18.702340Z","shell.execute_reply":"2026-09-12T14:14:18.936959Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nimport random\nimport urllib.request\nimport zipfile\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport warnings\n\n# ปิดการแจ้งเตือนย่อยๆ\nwarnings.filterwarnings('ignore')\n\n# 1. โหลดและแตกไฟล์ด้วยตัวเองเพื่อแก้ปัญหา Colab จำ Cache ไฟล์ที่เสีย\nworkspace = '/content/my_dataset'\nzip_path = os.path.join(workspace, 'kagglecatsanddogs.zip')\nsource_dir = os.path.join(workspace, 'PetImages')\nbase_dir = os.path.join(workspace, 'cats_and_dogs_filtered')\n\nos.makedirs(workspace, exist_ok=True)\n\n# เช็คว่ามีโฟลเดอร์รูปหรือยัง ถ้ายังให้ดาวน์โหลดใหม่ทั้งหมด\nif not os.path.exists(source_dir):\n    print(\"กำลังดาวน์โหลด Dataset ต้นฉบับ (ไฟล์ขนาด 824MB อาจใช้เวลา 1-2 นาที)...\")\n    urllib.request.urlretrieve('https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_5340.zip', zip_path)\n    print(\"กำลังแตกไฟล์ Zip...\")\n    with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n        zip_ref.extractall(workspace)\n    print(\"แตกไฟล์เสร็จสมบูรณ์!\")\n\n# 2. จำลองโครงสร้างโฟลเดอร์ Train/Val\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\n\nif os.path.exists(base_dir): \n    shutil.rmtree(base_dir)\n\nfor dir_path in [train_dir, validation_dir]:\n    os.makedirs(os.path.join(dir_path, 'cats'), exist_ok=True)\n    os.makedirs(os.path.join(dir_path, 'dogs'), exist_ok=True)\n\n# 3. คัดกรองไฟล์เสียและจัดโฟลเดอร์\ndef setup_dataset(class_name, src_folder_name):\n    src = os.path.join(source_dir, src_folder_name)\n    valid_images = []\n    \n    for f in os.listdir(src):\n        if not f.endswith('.jpg'): continue\n        img_path = os.path.join(src, f)\n        if os.path.getsize(img_path) == 0: continue\n        \n        try:\n            with Image.open(img_path) as img:\n                img.verify()\n            valid_images.append(f)\n        except:\n            pass\n\n    random.seed(42)\n    random.shuffle(valid_images)\n    \n    # ดึงมา Train 1,000 รูป และ Val 500 รูป ต่อคลาส\n    for img in valid_images[:1000]:\n        shutil.copyfile(os.path.join(src, img), os.path.join(train_dir, class_name, img))\n    for img in valid_images[1000:1500]:\n        shutil.copyfile(os.path.join(src, img), os.path.join(validation_dir, class_name, img))\n\nprint(\"กำลังคัดกรองรูปภาพและแบ่งโฟลเดอร์...\")\nsetup_dataset('cats', 'Cat')\nsetup_dataset('dogs', 'Dog')\nprint(\"จัดเตรียมชุดข้อมูลเสร็จสมบูรณ์!\\n\")\n\n# 4. Data Augmentation\ntrain_datagen = ImageDataGenerator(\n    rescale=1./255,\n    rotation_range=40,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    shear_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    fill_mode='nearest'\n)\n\nval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generator = train_datagen.flow_from_directory(\n    train_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)\n\nvalidation_generator = val_datagen.flow_from_directory(\n    validation_dir,\n    target_size=(150, 150),\n    batch_size=32,\n    class_mode='binary'\n)\n\n# 5. สร้าง Baseline CNN Model \nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    \n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D(2, 2),\n    \n    Flatten(),\n    Dropout(0.5),\n    Dense(512, activation='relu'),\n    Dense(1, activation='sigmoid')\n])\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), \n              metrics=['accuracy'])\n\n# 6. Callback หยุดการเทรนอัตโนมัติเมื่อ Validation Accuracy ถึง 0.85\nclass myCallback(tf.keras.callbacks.Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        # ตั้งเผื่อไว้ที่ 0.855 เพื่อความมั่นใจว่าผ่านเกณฑ์อาจารย์ชัวร์ๆ\n        if(logs.get('val_accuracy') >= 0.855):\n            print(\"\\nถึงเป้าหมาย Validation Accuracy >= 0.85 แล้ว หยุดการเทรน!\")\n            self.model.stop_training = True\n\ncallbacks = myCallback()\n\n# 7. เริ่มเทรนโมเดล\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch=2000 // 32,\n    epochs=60,\n    validation_data=validation_generator,\n    validation_steps=1000 // 32,\n    callbacks=[callbacks]\n)\n\n# 8. พลอตกราฟแสดงผลลัพธ์\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs_range = range(len(acc))\n\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.axhline(y=0.85, color='r', linestyle='--', label='Target 0.85')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-09-12T15:55:06.735348Z","iopub.execute_input":"2026-09-12T15:55:06.735778Z","iopub.status.idle":"2026-09-12T16:04:27.817988Z","shell.execute_reply.started":"2026-09-12T15:55:06.735748Z","shell.execute_reply":"2026-09-12T16:04:27.817236Z"}},"outputs":[],"execution_count":null}]}