{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:13.843942Z","iopub.execute_input":"2025-02-10T15:10:13.844675Z","iopub.status.idle":"2025-02-10T15:10:14.145661Z","shell.execute_reply.started":"2025-02-10T15:10:13.844637Z","shell.execute_reply":"2025-02-10T15:10:14.144912Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:14.147237Z","iopub.execute_input":"2025-02-10T15:10:14.148083Z","iopub.status.idle":"2025-02-10T15:10:23.015304Z","shell.execute_reply.started":"2025-02-10T15:10:14.148051Z","shell.execute_reply":"2025-02-10T15:10:23.014587Z"}},"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":"2025-02-10T15:10:23.016241Z","iopub.execute_input":"2025-02-10T15:10:23.016502Z","iopub.status.idle":"2025-02-10T15:10:24.012600Z","shell.execute_reply.started":"2025-02-10T15:10:23.016479Z","shell.execute_reply":"2025-02-10T15:10:24.011663Z"}},"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":"2025-02-10T15:10:24.014525Z","iopub.execute_input":"2025-02-10T15:10:24.014787Z","iopub.status.idle":"2025-02-10T15:10:24.862622Z","shell.execute_reply.started":"2025-02-10T15:10:24.014766Z","shell.execute_reply":"2025-02-10T15:10:24.861836Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:24.863833Z","iopub.execute_input":"2025-02-10T15:10:24.864107Z","iopub.status.idle":"2025-02-10T15:10:27.627067Z","shell.execute_reply.started":"2025-02-10T15:10:24.864081Z","shell.execute_reply":"2025-02-10T15:10:27.625839Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:27.628569Z","iopub.execute_input":"2025-02-10T15:10:27.629421Z","iopub.status.idle":"2025-02-10T15:10:27.639278Z","shell.execute_reply.started":"2025-02-10T15:10:27.629331Z","shell.execute_reply":"2025-02-10T15:10:27.635966Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:27.641572Z","iopub.execute_input":"2025-02-10T15:10:27.642158Z","iopub.status.idle":"2025-02-10T15:10:27.653253Z","shell.execute_reply.started":"2025-02-10T15:10:27.642116Z","shell.execute_reply":"2025-02-10T15:10:27.649495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 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":"2025-02-10T15:10:27.655244Z","iopub.execute_input":"2025-02-10T15:10:27.655875Z","iopub.status.idle":"2025-02-10T15:10:30.873089Z","shell.execute_reply.started":"2025-02-10T15:10:27.655835Z","shell.execute_reply":"2025-02-10T15:10:30.872344Z"}},"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":"2025-02-10T15:10:30.874500Z","iopub.execute_input":"2025-02-10T15:10:30.874743Z","iopub.status.idle":"2025-02-10T15:10:31.950755Z","shell.execute_reply.started":"2025-02-10T15:10:30.874722Z","shell.execute_reply":"2025-02-10T15:10:31.949880Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:31.953424Z","iopub.execute_input":"2025-02-10T15:10:31.953685Z","iopub.status.idle":"2025-02-10T15:10:33.044313Z","shell.execute_reply.started":"2025-02-10T15:10:31.953662Z","shell.execute_reply":"2025-02-10T15:10:33.043413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:33.046173Z","iopub.execute_input":"2025-02-10T15:10:33.046614Z","iopub.status.idle":"2025-02-10T15:10:41.417649Z","shell.execute_reply.started":"2025-02-10T15:10:33.046570Z","shell.execute_reply":"2025-02-10T15:10:41.416475Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:41.419454Z","iopub.execute_input":"2025-02-10T15:10:41.419799Z","iopub.status.idle":"2025-02-10T15:10:41.430861Z","shell.execute_reply.started":"2025-02-10T15:10:41.419767Z","shell.execute_reply":"2025-02-10T15:10:41.429938Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom keras.callbacks import LearningRateScheduler","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:10:41.432062Z","iopub.execute_input":"2025-02-10T15:10:41.432623Z","iopub.status.idle":"2025-02-10T15:10:41.437042Z","shell.execute_reply.started":"2025-02-10T15:10:41.432592Z","shell.execute_reply":"2025-02-10T15:10:41.436201Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# EfficientNetB0 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 import EfficientNetV2L \nfrom keras.models import Model\nfrom keras.layers import GlobalAveragePooling2D, Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD, Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import Callback\nfrom keras.callbacks import ReduceLROnPlateau\n\n# define cnn model\ndef define_model():\n    # Load VGG16 model\n    model = EfficientNetV2L(include_top=False, input_shape=(480, 480, 3)) \n    for layer in model.layers:\n        layer.trainable = False\n    # Add new classifier layers\n        #flat1 = Flatten()(model.layers[-1].output)\n        #class1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n        #output = Dense(1, activation='sigmoid')(class1)\n    x = GlobalAveragePooling2D()(model.output)\n    x = Dense(128, activation='relu', kernel_initializer='he_uniform')(x)\n    output = Dense(1, activation='sigmoid')(x)\n    \n    # Define new model\n    model = Model(inputs=model.inputs, outputs=output)\n    # Compile model with Adam optimizer\n    opt = Adam(learning_rate=0.001)\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n    return model\n\n# 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    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png')\n    pyplot.close()\n\nlr_scheduler = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, verbose=1)\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ninitial_learning_rate = 0.001  # ค่าเริ่มต้นของ Learning Rate\nepochs = 30\ndef cosine_decay(epoch):\n    return initial_learning_rate * 0.5 * (1 + tf.math.cos((epoch / epochs) * 3.14159))\ncosine_scheduler = LearningRateScheduler(cosine_decay, verbose=1)\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# run the test harness for evaluating a model\ndef run_test_harness():\n    # define model\n    model = define_model()\n    # create data generator\n    datagen = ImageDataGenerator(\n        rotation_range=20,\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    # prepare iterator\n    train_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n                                           class_mode='binary', batch_size=64, target_size=(224, 224))\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(224, 224))\n    # initialize PlotLosses callback\n    plot_losses = PlotLossesKeras()\n    # fit model with PlotLosses callback\n    history = model.fit_generator(\n        train_it, \n        steps_per_epoch=len(train_it), \n        validation_data=test_it, \n        validation_steps=len(test_it), \n        epochs=20, \n        verbose=1,\n        callbacks=[lr_scheduler, PlotLossesKeras()]\n    ) \n    # evaluate model\n    _, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n    print('> %.3f' % (acc * 100.0))\n    # learning curves\n    summarize_diagnostics(history)\n    model.save_weights('model_weights.h5')\n\n# entry point, run the test harness\nrun_test_harness()\n","metadata":{"execution":{"iopub.status.busy":"2025-02-10T15:10:41.438397Z","iopub.execute_input":"2025-02-10T15:10:41.438755Z","iopub.status.idle":"2025-02-10T15:18:13.417829Z","shell.execute_reply.started":"2025-02-10T15:10:41.438726Z","shell.execute_reply":"2025-02-10T15:18:13.417103Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\n\n# สุ่มรูปภาพ 30 รูปจากชุดข้อมูลทดสอบ\ndef random_images_from_test_set(test_it, num_images=30):\n    # สุ่ม batch จากชุดข้อมูล\n    images, labels = next(test_it)\n    num_samples = len(images)\n    \n    # สุ่มเลือก index ของรูปภาพ 30 รูป\n    indices = np.random.choice(num_samples, num_images, replace=False)\n    \n    # สร้าง list สำหรับเก็บภาพและ label ที่สุ่ม\n    random_images = images[indices]\n    random_labels = labels[indices]\n    \n    return random_images, random_labels\n\n# ทำนายผลจากรูปที่สุ่ม\ndef predict_random_images(model, test_it, num_images=30):\n    random_images, random_labels = random_images_from_test_set(test_it, num_images)\n    \n    # ทำนายผล\n    predictions = model.predict(random_images)\n    \n    # แสดงผล\n    plt.figure(figsize=(15, 15))\n    for i in range(num_images):\n        plt.subplot(5, 6, i+1)  # แสดงผล 5 แถว 6 คอลัมน์\n        img = random_images[i]\n        true_label = random_labels[i]\n        pred_label = predictions[i]\n        \n        # แสดงรูป\n        plt.imshow(img)\n        \n        # แสดงผลการทำนาย\n        title = f\"True: {'Dog' if true_label == 1 else 'Cat'}\\nPred: {'Dog' if pred_label > 0.5 else 'Cat'}\"\n        plt.title(title, fontsize=10)\n        plt.axis('off')\n    \n    plt.show()\n\n# run the test harness for evaluating a model and predict on random images\ndef run_test_harness_and_predict():\n    # define model\n    model = define_model()\n    \n    # create data generator\n    datagen = ImageDataGenerator(featurewise_center=True)\n    # specify imagenet mean values for centering\n    datagen.mean = [123.68, 116.779, 103.939]\n    \n    # prepare iterator for test data\n    test_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n                                          class_mode='binary', batch_size=64, target_size=(224, 224))\n    \n    # ทำนายภาพที่สุ่ม\n    predict_random_images(model, test_it)\n\n# entry point, run the test harness and prediction\nrun_test_harness_and_predict()\n","metadata":{"execution":{"execution_failed":"2025-02-10T12:39:12.202Z"}}},{"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import load_model\n\n# โหลดโมเดลที่ถูกฝึกไว้แล้ว\nmodel = define_model()  # สร้างโมเดล\nmodel.load_weights('model_weights.h5')  # โหลดน้ำหนักของโมเดลที่ถูกฝึกแล้ว\n\n# ใช้ ImageDataGenerator พร้อม EfficientNetV2 preprocessing\ndatagen = ImageDataGenerator(preprocessing_function=tf.keras.applications.efficientnet_v2.preprocess_input)\n\n# เตรียมชุดข้อมูลทดสอบ\ntest_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats/test/',\n    class_mode='binary', \n    batch_size=64, \n    target_size=(480, 480)  # ✅ แก้ไขเป็น 480x480 ให้ตรงกับ EfficientNetV2L\n)\n\n# ฟังก์ชันสุ่มเลือกรูปภาพจากชุดทดสอบ\ndef random_images_from_test_set(test_it, num_images=30):\n    images, labels = next(test_it)  # ดึง batch แรกออกมา\n    num_samples = len(images)\n\n    if num_samples < num_images:\n        num_images = num_samples  # ป้องกันกรณีรูปใน batch ไม่พอ\n\n    indices = np.random.choice(num_samples, num_images, replace=False)\n    random_images = images[indices]\n    random_labels = labels[indices]\n\n    return random_images, random_labels\n\n# ฟังก์ชันทำนายภาพที่สุ่ม\ndef predict_random_images(model, test_it, num_images=30):\n    random_images, random_labels = random_images_from_test_set(test_it, num_images)\n\n    # ทำนายผล\n    predictions = model.predict(random_images)\n\n    # แสดงผล\n    plt.figure(figsize=(15, 15))\n    for i in range(num_images):\n        plt.subplot(5, 6, i + 1)  # 5 แถว 6 คอลัมน์\n        img = random_images[i]\n        true_label = 'Dog' if random_labels[i] == 1 else 'Cat'\n        pred_label = 'Dog' if predictions[i] > 0.5 else 'Cat'\n\n        plt.imshow(img)\n        plt.title(f\"True: {true_label}\\nPred: {pred_label}\", fontsize=10)\n        plt.axis('off')\n\n    plt.show()\n\n# เรียกใช้งาน\npredict_random_images(model, test_it)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T15:18:13.419767Z","iopub.execute_input":"2025-02-10T15:18:13.420041Z","iopub.status.idle":"2025-02-10T15:18:40.891654Z","shell.execute_reply.started":"2025-02-10T15:18:13.420018Z","shell.execute_reply":"2025-02-10T15:18:40.890756Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}