{"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"},{"sourceId":10709558,"sourceType":"datasetVersion","datasetId":6637520},{"sourceId":254270,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":217403,"modelId":239119}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-02-10T04:47:35.996544Z","iopub.execute_input":"2025-02-10T04:47:35.996890Z","iopub.status.idle":"2025-02-10T04:47:36.320446Z","shell.execute_reply.started":"2025-02-10T04:47:35.996862Z","shell.execute_reply":"2025-02-10T04:47:36.319621Z"},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T04:47:37.662225Z","iopub.execute_input":"2025-02-10T04:47:37.662605Z","iopub.status.idle":"2025-02-10T04:47:50.596543Z","shell.execute_reply.started":"2025-02-10T04:47:37.662580Z","shell.execute_reply":"2025-02-10T04:47:50.595534Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"!ls train","metadata":{"execution":{"iopub.status.busy":"2024-01-08T06:57:18.293035Z","iopub.execute_input":"2024-01-08T06:57:18.293457Z","iopub.status.idle":"2024-01-08T06:57:19.311078Z","shell.execute_reply.started":"2024-01-08T06:57:18.293422Z","shell.execute_reply":"2024-01-08T06:57:19.309969Z"}}},{"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":"2025-02-10T04:48:00.856370Z","iopub.execute_input":"2025-02-10T04:48:00.856689Z","iopub.status.idle":"2025-02-10T04:48:02.188030Z","shell.execute_reply.started":"2025-02-10T04:48:00.856663Z","shell.execute_reply":"2025-02-10T04:48:02.187134Z"},"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":"2025-02-10T04:48:05.317655Z","iopub.execute_input":"2025-02-10T04:48:05.318095Z","iopub.status.idle":"2025-02-10T04:48:06.349398Z","shell.execute_reply.started":"2025-02-10T04:48:05.318050Z","shell.execute_reply":"2025-02-10T04:48:06.348069Z"},"trusted":true},"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":"2025-02-10T04:48:08.890851Z","iopub.execute_input":"2025-02-10T04:48:08.891176Z","iopub.status.idle":"2025-02-10T04:48:20.433418Z","shell.execute_reply.started":"2025-02-10T04:48:08.891150Z","shell.execute_reply":"2025-02-10T04:48:20.432676Z"},"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":"\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":{"execution":{"iopub.status.busy":"2025-02-10T04:48:25.096282Z","iopub.execute_input":"2025-02-10T04:48:25.097188Z","iopub.status.idle":"2025-02-10T04:48:25.101251Z","shell.execute_reply.started":"2025-02-10T04:48:25.097157Z","shell.execute_reply":"2025-02-10T04:48:25.100348Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats1/'\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":{"execution":{"iopub.status.busy":"2025-02-10T04:49:40.983220Z","iopub.execute_input":"2025-02-10T04:49:40.983951Z","iopub.status.idle":"2025-02-10T04:49:40.989013Z","shell.execute_reply.started":"2025-02-10T04:49:40.983921Z","shell.execute_reply":"2025-02-10T04:49:40.988111Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-02-10T04:50:09.094610Z","iopub.execute_input":"2025-02-10T04:50:09.095233Z","iopub.status.idle":"2025-02-10T04:50:12.684761Z","shell.execute_reply.started":"2025-02-10T04:50:09.095196Z","shell.execute_reply":"2025-02-10T04:50:12.683624Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-10T04:54:19.777290Z","iopub.execute_input":"2025-02-10T04:54:19.778106Z","iopub.status.idle":"2025-02-10T04:54:20.808244Z","shell.execute_reply.started":"2025-02-10T04:54:19.778055Z","shell.execute_reply":"2025-02-10T04:54:20.807350Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-10T04:54:30.266120Z","iopub.execute_input":"2025-02-10T04:54:30.266914Z","iopub.status.idle":"2025-02-10T04:54:31.297185Z","shell.execute_reply.started":"2025-02-10T04:54:30.266882Z","shell.execute_reply":"2025-02-10T04:54:31.296302Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-10T04:54:36.635076Z","iopub.execute_input":"2025-02-10T04:54:36.635458Z","iopub.status.idle":"2025-02-10T04:54:46.995300Z","shell.execute_reply.started":"2025-02-10T04:54:36.635424Z","shell.execute_reply":"2025-02-10T04:54:46.994206Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-10T04:54:51.387698Z","iopub.execute_input":"2025-02-10T04:54:51.388408Z","iopub.status.idle":"2025-02-10T04:54:51.404380Z","shell.execute_reply.started":"2025-02-10T04:54:51.388375Z","shell.execute_reply":"2025-02-10T04:54:51.403490Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, CSVLogger","metadata":{"execution":{"iopub.status.busy":"2025-02-10T08:13:33.034172Z","iopub.execute_input":"2025-02-10T08:13:33.035038Z","iopub.status.idle":"2025-02-10T08:13:33.041471Z","shell.execute_reply.started":"2025-02-10T08:13:33.034991Z","shell.execute_reply":"2025-02-10T08:13:33.040099Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# สร้าง Data Generators\ndatagen = ImageDataGenerator(\n    rescale=1.0/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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T04:55:00.153284Z","iopub.execute_input":"2025-02-10T04:55:00.153627Z","iopub.status.idle":"2025-02-10T04:55:00.158201Z","shell.execute_reply.started":"2025-02-10T04:55:00.153599Z","shell.execute_reply":"2025-02-10T04:55:00.157382Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats1/train/',\n    class_mode='binary', batch_size=64, target_size=(224, 224)\n)\ntest_it = datagen.flow_from_directory(\n    'dataset_dogs_vs_cats1/test/',\n    class_mode='binary', batch_size=64, target_size=(224, 224)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T04:55:02.945680Z","iopub.execute_input":"2025-02-10T04:55:02.946042Z","iopub.status.idle":"2025-02-10T04:55:03.751578Z","shell.execute_reply.started":"2025-02-10T04:55:02.946016Z","shell.execute_reply":"2025-02-10T04:55:03.750649Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## DenseNet169","metadata":{}},{"cell_type":"code","source":"from keras.applications import DenseNet169\nfrom keras.models import Model\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.optimizers import Adam","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:06:56.383387Z","iopub.execute_input":"2025-02-10T06:06:56.383773Z","iopub.status.idle":"2025-02-10T06:06:56.389501Z","shell.execute_reply.started":"2025-02-10T06:06:56.383734Z","shell.execute_reply":"2025-02-10T06:06:56.388567Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# โหลด DenseNet169 pre-trained model\nbase_model = DenseNet169(\n    weights='imagenet',\n    include_top=False,  # ไม่เอาเลเยอร์ Top เดิม (fully connected layers)\n    input_shape=(224, 224, 3)  # ขนาด Input\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:09:19.442583Z","iopub.execute_input":"2025-02-10T06:09:19.443434Z","iopub.status.idle":"2025-02-10T06:09:23.669560Z","shell.execute_reply.started":"2025-02-10T06:09:19.443402Z","shell.execute_reply":"2025-02-10T06:09:23.668774Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# เพิ่ม GlobalAveragePooling2D และ Dense layers\nx = base_model.output\nx = GlobalAveragePooling2D()(x)  # ลดขนาดให้เหลือ 1D\nx = Dense(128, activation='relu')(x)  # Fully connected layer\noutput = Dense(1, activation='sigmoid')(x)  # สำหรับ Binary classification\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:11:19.373561Z","iopub.execute_input":"2025-02-10T06:11:19.374224Z","iopub.status.idle":"2025-02-10T06:11:19.403413Z","shell.execute_reply.started":"2025-02-10T06:11:19.374192Z","shell.execute_reply":"2025-02-10T06:11:19.402684Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"densenet169_model = Model(inputs=base_model.input, outputs=output)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:11:36.479255Z","iopub.execute_input":"2025-02-10T06:11:36.479609Z","iopub.status.idle":"2025-02-10T06:11:36.514995Z","shell.execute_reply.started":"2025-02-10T06:11:36.479580Z","shell.execute_reply":"2025-02-10T06:11:36.514339Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Freeze เลเยอร์ของ base_model\nfor layer in base_model.layers:\n    layer.trainable = False","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:11:49.427096Z","iopub.execute_input":"2025-02-10T06:11:49.427823Z","iopub.status.idle":"2025-02-10T06:11:49.445361Z","shell.execute_reply.started":"2025-02-10T06:11:49.427791Z","shell.execute_reply":"2025-02-10T06:11:49.444387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile โมเดล\ndensenet169_model.compile(optimizer=Adam(learning_rate=0.001), \n                       loss='binary_crossentropy', \n                       metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:12:01.797899Z","iopub.execute_input":"2025-02-10T06:12:01.798576Z","iopub.status.idle":"2025-02-10T06:12:01.821077Z","shell.execute_reply.started":"2025-02-10T06:12:01.798544Z","shell.execute_reply":"2025-02-10T06:12:01.820131Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"densenet169_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:12:14.175210Z","iopub.execute_input":"2025-02-10T06:12:14.175879Z","iopub.status.idle":"2025-02-10T06:12:15.573336Z","shell.execute_reply.started":"2025-02-10T06:12:14.175848Z","shell.execute_reply":"2025-02-10T06:12:15.572389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"csv_logger_densenet169 = CSVLogger(\"training_densenet169_log.csv\", append=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:18:24.639351Z","iopub.execute_input":"2025-02-10T06:18:24.640284Z","iopub.status.idle":"2025-02-10T06:18:24.644373Z","shell.execute_reply.started":"2025-02-10T06:18:24.640242Z","shell.execute_reply":"2025-02-10T06:18:24.643545Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(\n    monitor=\"val_loss\", patience=5, restore_best_weights=True, verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:14:03.467784Z","iopub.execute_input":"2025-02-10T08:14:03.468705Z","iopub.status.idle":"2025-02-10T08:14:03.473337Z","shell.execute_reply.started":"2025-02-10T08:14:03.468657Z","shell.execute_reply":"2025-02-10T08:14:03.472060Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train\nhistory_densenet169 = densenet169_model.fit(\n    train_it,\n    validation_data=test_it,\n    epochs=10,\n    verbose=1,\n    callbacks=[PlotLossesKeras(), csv_logger_densenet169, early_stopping]\n)\n\n# Evaluate\n_, acc = densenet169_model.evaluate(test_it, verbose=1)\nprint('DenseNet121 Accuracy: %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T06:19:42.635987Z","iopub.execute_input":"2025-02-10T06:19:42.636604Z","iopub.status.idle":"2025-02-10T07:13:21.640663Z","shell.execute_reply.started":"2025-02-10T06:19:42.636570Z","shell.execute_reply":"2025-02-10T07:13:21.639771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save Model\ndensenet169_model.save('densenet169_model.hdf5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:16:57.525456Z","iopub.execute_input":"2025-02-10T07:16:57.526374Z","iopub.status.idle":"2025-02-10T07:16:58.472301Z","shell.execute_reply.started":"2025-02-10T07:16:57.526341Z","shell.execute_reply":"2025-02-10T07:16:58.471568Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## แสดงค่าใน training_densenet169_log","metadata":{}},{"cell_type":"code","source":"# import pandas as pd\n# import csv\n# # อ่านข้อมูลจาก CSV\n# epochs, accuracy, loss, val_accuracy, val_loss = [], [], [], [], []\n# with open('/kaggle/input/training-densenet169-log/training_densenet169_log.csv', 'r') as file:\n#     reader = csv.DictReader(file)\n#     for row in reader:\n#         epochs.append(int(row['epoch']))\n#         accuracy.append(float(row['accuracy']))\n#         loss.append(float(row['loss']))\n#         val_accuracy.append(float(row['val_accuracy']))\n#         val_loss.append(float(row['val_loss']))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:45:31.914817Z","iopub.execute_input":"2025-02-10T07:45:31.915452Z","iopub.status.idle":"2025-02-10T07:45:31.924934Z","shell.execute_reply.started":"2025-02-10T07:45:31.915420Z","shell.execute_reply":"2025-02-10T07:45:31.924172Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # แสดงข้อมูลในแต่ละ epoch\n# print(f\"{'Epoch':<5} {'Accuracy':<10} {'Loss':<10} {'Val_Accuracy':<15} {'Val_Loss':<10}\")\n# print(\"=\" * 50)\n# for i in range(len(epochs)):\n#     print(f\"{epochs[i]:<5} {accuracy[i]:<10.6f} {loss[i]:<10.6f} {val_accuracy[i]:<15.6f} {val_loss[i]:<10.6f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:47:37.433720Z","iopub.execute_input":"2025-02-10T07:47:37.434131Z","iopub.status.idle":"2025-02-10T07:47:37.439782Z","shell.execute_reply.started":"2025-02-10T07:47:37.434100Z","shell.execute_reply":"2025-02-10T07:47:37.438918Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# import pandas as pd\n\n# # โหลด log จากไฟล์ CSV\n# log_df = pd.read_csv('/kaggle/input/training-densenet169-log/training_densenet169_log.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:35:11.884626Z","iopub.execute_input":"2025-02-10T07:35:11.885004Z","iopub.status.idle":"2025-02-10T07:35:11.894862Z","shell.execute_reply.started":"2025-02-10T07:35:11.884976Z","shell.execute_reply":"2025-02-10T07:35:11.894047Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Plot Training and Validation Loss\n# plt.figure(figsize=(10, 6))\n# plt.plot(log_df['epoch'], log_df['loss'], label='Train Loss')\n# plt.plot(log_df['epoch'], log_df['val_loss'], label='Validation Loss')\n# plt.title('Training and Validation Loss')\n# plt.xlabel('Epochs')\n# plt.ylabel('Loss')\n# plt.legend()\n# plt.grid()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:35:13.679164Z","iopub.execute_input":"2025-02-10T07:35:13.679621Z","iopub.status.idle":"2025-02-10T07:35:13.926379Z","shell.execute_reply.started":"2025-02-10T07:35:13.679581Z","shell.execute_reply":"2025-02-10T07:35:13.925578Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # Plot Training and Validation Accuracy\n# plt.figure(figsize=(10, 6))\n# plt.plot(log_df['epoch'], log_df['accuracy'], label='Train Accuracy')\n# plt.plot(log_df['epoch'], log_df['val_accuracy'], label='Validation Accuracy')\n# plt.title('Training and Validation Accuracy')\n# plt.xlabel('Epochs')\n# plt.ylabel('Accuracy')\n# plt.legend()\n# plt.grid()\n# plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T07:35:20.070690Z","iopub.execute_input":"2025-02-10T07:35:20.071081Z","iopub.status.idle":"2025-02-10T07:35:20.303936Z","shell.execute_reply.started":"2025-02-10T07:35:20.071051Z","shell.execute_reply":"2025-02-10T07:35:20.302985Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## DenseNet121","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import DenseNet121\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Flatten, Dense\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:15:18.652275Z","iopub.execute_input":"2025-02-10T08:15:18.653009Z","iopub.status.idle":"2025-02-10T08:15:18.657327Z","shell.execute_reply.started":"2025-02-10T08:15:18.652974Z","shell.execute_reply":"2025-02-10T08:15:18.656397Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# โหลด DenseNet121\nbase_model = DenseNet121(\n    weights='imagenet',\n    include_top=False,  # ไม่ใช้ Fully Connected Layer เดิม\n    input_shape=(224, 224, 3)\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:15:19.809914Z","iopub.execute_input":"2025-02-10T08:15:19.810574Z","iopub.status.idle":"2025-02-10T08:15:22.628236Z","shell.execute_reply.started":"2025-02-10T08:15:19.810543Z","shell.execute_reply":"2025-02-10T08:15:22.627506Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# เพิ่มชั้น Classifier\nx = Flatten()(base_model.output)\nx = Dense(128, activation='relu', kernel_initializer='he_uniform')(x)\noutput = Dense(1, activation='sigmoid')(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:15:35.492617Z","iopub.execute_input":"2025-02-10T08:15:35.492944Z","iopub.status.idle":"2025-02-10T08:15:35.522189Z","shell.execute_reply.started":"2025-02-10T08:15:35.492919Z","shell.execute_reply":"2025-02-10T08:15:35.521422Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# สร้างโมเดลใหม่\nmodel_densenet = Model(inputs=base_model.input, outputs=output)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:15:37.111009Z","iopub.execute_input":"2025-02-10T08:15:37.111787Z","iopub.status.idle":"2025-02-10T08:15:37.137794Z","shell.execute_reply.started":"2025-02-10T08:15:37.111753Z","shell.execute_reply":"2025-02-10T08:15:37.137177Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile\nopt = SGD(learning_rate=0.0001, momentum=0.9)\nmodel_densenet.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:15:38.839379Z","iopub.execute_input":"2025-02-10T08:15:38.840352Z","iopub.status.idle":"2025-02-10T08:15:38.859946Z","shell.execute_reply.started":"2025-02-10T08:15:38.840305Z","shell.execute_reply":"2025-02-10T08:15:38.859083Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# แสดงโครงสร้างโมเดล\nmodel_densenet.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:16:26.034740Z","iopub.execute_input":"2025-02-10T08:16:26.035117Z","iopub.status.idle":"2025-02-10T08:16:27.069211Z","shell.execute_reply.started":"2025-02-10T08:16:26.035089Z","shell.execute_reply":"2025-02-10T08:16:27.068285Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"csv_logger_densenet121 = CSVLogger(\"training_densenet121_log.csv\", append=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:17:19.285417Z","iopub.execute_input":"2025-02-10T08:17:19.285807Z","iopub.status.idle":"2025-02-10T08:17:19.290159Z","shell.execute_reply.started":"2025-02-10T08:17:19.285779Z","shell.execute_reply":"2025-02-10T08:17:19.289295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(\n    monitor=\"val_loss\", patience=5, restore_best_weights=True, verbose=1\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:17:22.317466Z","iopub.execute_input":"2025-02-10T08:17:22.318253Z","iopub.status.idle":"2025-02-10T08:17:22.322465Z","shell.execute_reply.started":"2025-02-10T08:17:22.318219Z","shell.execute_reply":"2025-02-10T08:17:22.321470Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train\nhistory_densenet = model_densenet.fit(train_it,\n                                      validation_data=test_it,\n                                      epochs=1, verbose=1,\n                                     callbacks=[PlotLossesKeras(), csv_logger_densenet121, early_stopping]\n                                     )\n\n# Evaluate\n_, acc = model_densenet.evaluate(test_it, verbose=1)\nprint('DenseNet121 Accuracy: %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-10T08:17:26.107965Z","iopub.execute_input":"2025-02-10T08:17:26.108543Z","iopub.status.idle":"2025-02-10T08:24:40.534840Z","shell.execute_reply.started":"2025-02-10T08:17:26.108512Z","shell.execute_reply":"2025-02-10T08:24:40.534061Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save Model\nmodel_densenet.save('densenet121_model.hdf5')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-09T15:39:30.516242Z","iopub.execute_input":"2025-02-09T15:39:30.516577Z","iopub.status.idle":"2025-02-09T15:39:31.521485Z","shell.execute_reply.started":"2025-02-09T15:39:30.516550Z","shell.execute_reply":"2025-02-09T15:39:31.520770Z"}},"outputs":[],"execution_count":null}]}