{"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,"isSourceIdPinned":false,"sourceType":"competition"}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2025-02-20T12:36:01.681865Z","iopub.execute_input":"2025-02-20T12:36:01.682168Z","iopub.status.idle":"2025-02-20T12:36:01.978676Z","shell.execute_reply.started":"2025-02-20T12:36:01.682137Z","shell.execute_reply":"2025-02-20T12:36:01.977799Z"},"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":"2025-02-20T12:36:01.980351Z","iopub.execute_input":"2025-02-20T12:36:01.980674Z","iopub.status.idle":"2025-02-20T12:36:23.011027Z","shell.execute_reply.started":"2025-02-20T12:36:01.980648Z","shell.execute_reply":"2025-02-20T12:36:23.010322Z"},"trusted":true},"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":"2025-02-20T12:36:23.011962Z","iopub.execute_input":"2025-02-20T12:36:23.012192Z","iopub.status.idle":"2025-02-20T12:36:34.119549Z","shell.execute_reply.started":"2025-02-20T12:36:23.012171Z","shell.execute_reply":"2025-02-20T12:36:34.118791Z"}},"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-20T12:36:34.120588Z","iopub.execute_input":"2025-02-20T12:36:34.121100Z","iopub.status.idle":"2025-02-20T12:36:35.106075Z","shell.execute_reply.started":"2025-02-20T12:36:34.121073Z","shell.execute_reply":"2025-02-20T12:36:35.105239Z"},"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-20T12:36:35.107072Z","iopub.execute_input":"2025-02-20T12:36:35.107323Z","iopub.status.idle":"2025-02-20T12:36:35.977959Z","shell.execute_reply.started":"2025-02-20T12:36:35.107300Z","shell.execute_reply":"2025-02-20T12:36:35.977129Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pip install --upgrade 'numpy<1.23.0'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:36:35.979216Z","iopub.execute_input":"2025-02-20T12:36:35.979629Z","iopub.status.idle":"2025-02-20T12:36:50.104584Z","shell.execute_reply.started":"2025-02-20T12:36:35.979586Z","shell.execute_reply":"2025-02-20T12:36:50.103416Z"}},"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-20T12:36:50.108704Z","iopub.execute_input":"2025-02-20T12:36:50.109057Z","iopub.status.idle":"2025-02-20T12:36:50.113733Z","shell.execute_reply.started":"2025-02-20T12:36:50.109028Z","shell.execute_reply":"2025-02-20T12:36:50.112918Z"},"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":"2025-02-20T12:36:50.114950Z","iopub.execute_input":"2025-02-20T12:36:50.115226Z","iopub.status.idle":"2025-02-20T12:36:50.124756Z","shell.execute_reply.started":"2025-02-20T12:36:50.115202Z","shell.execute_reply":"2025-02-20T12:36:50.123889Z"},"trusted":true},"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":{"execution":{"iopub.status.busy":"2025-02-20T12:36:50.125962Z","iopub.execute_input":"2025-02-20T12:36:50.126191Z","iopub.status.idle":"2025-02-20T12:36:50.135473Z","shell.execute_reply.started":"2025-02-20T12:36:50.126171Z","shell.execute_reply":"2025-02-20T12:36:50.134548Z"},"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-20T12:36:50.136462Z","iopub.execute_input":"2025-02-20T12:36:50.136707Z","iopub.status.idle":"2025-02-20T12:36:52.436398Z","shell.execute_reply.started":"2025-02-20T12:36:50.136687Z","shell.execute_reply":"2025-02-20T12:36:52.435682Z"},"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-20T12:36:52.437407Z","iopub.execute_input":"2025-02-20T12:36:52.437631Z","iopub.status.idle":"2025-02-20T12:36:53.552719Z","shell.execute_reply.started":"2025-02-20T12:36:52.437611Z","shell.execute_reply":"2025-02-20T12:36:53.551446Z"},"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-20T12:36:53.554454Z","iopub.execute_input":"2025-02-20T12:36:53.554988Z","iopub.status.idle":"2025-02-20T12:36:54.655400Z","shell.execute_reply.started":"2025-02-20T12:36:53.554944Z","shell.execute_reply":"2025-02-20T12:36:54.654133Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:36:54.657291Z","iopub.execute_input":"2025-02-20T12:36:54.657706Z","iopub.status.idle":"2025-02-20T12:37:03.561668Z","shell.execute_reply.started":"2025-02-20T12:36:54.657667Z","shell.execute_reply":"2025-02-20T12:37:03.560515Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:03.563065Z","iopub.execute_input":"2025-02-20T12:37:03.563389Z","iopub.status.idle":"2025-02-20T12:37:03.579001Z","shell.execute_reply.started":"2025-02-20T12:37:03.563362Z","shell.execute_reply":"2025-02-20T12:37:03.578183Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"code","source":"# save the final model to file\nfrom keras.applications.vgg16 import VGG16\nfrom keras.applications.xception import Xception\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","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:03.580077Z","iopub.execute_input":"2025-02-20T12:37:03.580334Z","iopub.status.idle":"2025-02-20T12:37:03.585860Z","shell.execute_reply.started":"2025-02-20T12:37:03.580312Z","shell.execute_reply":"2025-02-20T12:37:03.585131Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"xcep_model = Xception(include_top=False, input_shape=(299, 299, 3))\nxcep_model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-01-27T04:11:23.494572Z","iopub.execute_input":"2024-01-27T04:11:23.495217Z","iopub.status.idle":"2024-01-27T04:11:26.579883Z","shell.execute_reply.started":"2024-01-27T04:11:23.495182Z","shell.execute_reply":"2024-01-27T04:11:26.578335Z"}}},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n# create data generator\ndatagen = 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# prepare iterator\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(224, 224))","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:03.586689Z","iopub.execute_input":"2025-02-20T12:37:03.586990Z","iopub.status.idle":"2025-02-20T12:37:04.218640Z","shell.execute_reply.started":"2025-02-20T12:37:03.586969Z","shell.execute_reply":"2025-02-20T12:37:04.217802Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load model\nmodel = VGG16(\n    include_top=False,\n    input_shape=(224, 224, 3)\n    )\nprint(model.summary())\n#model = Xception(include_top=False, input_shape=(299, 299, 3))\n\n","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:04.219849Z","iopub.execute_input":"2025-02-20T12:37:04.220177Z","iopub.status.idle":"2025-02-20T12:37:06.087558Z","shell.execute_reply.started":"2025-02-20T12:37:04.220146Z","shell.execute_reply":"2025-02-20T12:37:06.086601Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# mark loaded layers as not trainable\nfor index, layer in enumerate(model.layers[:15]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = False\n    \nfor index, layer in enumerate(model.layers[15:]):\n    print(index, layer.name, layer.output_shape)\n    layer.trainable = True","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:06.088719Z","iopub.execute_input":"2025-02-20T12:37:06.089016Z","iopub.status.idle":"2025-02-20T12:37:06.095654Z","shell.execute_reply.started":"2025-02-20T12:37:06.088991Z","shell.execute_reply":"2025-02-20T12:37:06.094733Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:06.096720Z","iopub.execute_input":"2025-02-20T12:37:06.097014Z","iopub.status.idle":"2025-02-20T12:37:06.967491Z","shell.execute_reply.started":"2025-02-20T12:37:06.096991Z","shell.execute_reply":"2025-02-20T12:37:06.966530Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# add new classifier layers\nflat1 = Flatten()(model.layers[-1].output)\nclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\noutput = Dense(1, activation='sigmoid')(class1)\n# define new model\nmy_model = Model(inputs=model.inputs, outputs=output)","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:06.968838Z","iopub.execute_input":"2025-02-20T12:37:06.969207Z","iopub.status.idle":"2025-02-20T12:37:07.030322Z","shell.execute_reply.started":"2025-02-20T12:37:06.969174Z","shell.execute_reply":"2025-02-20T12:37:07.029685Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# compile model\nopt = SGD(lr=0.0001, momentum=0.9)\nmy_model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\nmy_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:37:07.031582Z","iopub.execute_input":"2025-02-20T12:37:07.031921Z","iopub.status.idle":"2025-02-20T12:37:07.089607Z","shell.execute_reply.started":"2025-02-20T12:37:07.031890Z","shell.execute_reply":"2025-02-20T12:37:07.088801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmy_model.reset_states()\nhistory = my_model.fit(train_it, \n                    steps_per_epoch=len(train_it),\n                    validation_data=test_it, \n                    validation_steps=len(test_it), \n                    epochs=3, verbose=1,\n                    callbacks=[PlotLossesKeras()])","metadata":{"execution":{"iopub.status.busy":"2025-02-20T12:37:07.094428Z","iopub.execute_input":"2025-02-20T12:37:07.094669Z","iopub.status.idle":"2025-02-20T12:52:15.443274Z","shell.execute_reply.started":"2025-02-20T12:37:07.094647Z","shell.execute_reply":"2025-02-20T12:52:15.442421Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = my_model.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:52:15.444481Z","iopub.execute_input":"2025-02-20T12:52:15.444737Z","iopub.status.idle":"2025-02-20T12:53:30.577502Z","shell.execute_reply.started":"2025-02-20T12:52:15.444714Z","shell.execute_reply":"2025-02-20T12:53:30.576708Z"}},"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.tight_layout()\n    pyplot.show()\n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:30.578686Z","iopub.execute_input":"2025-02-20T12:53:30.579055Z","iopub.status.idle":"2025-02-20T12:53:30.585010Z","shell.execute_reply.started":"2025-02-20T12:53:30.579022Z","shell.execute_reply":"2025-02-20T12:53:30.584133Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:30.586052Z","iopub.execute_input":"2025-02-20T12:53:30.586293Z","iopub.status.idle":"2025-02-20T12:53:31.011694Z","shell.execute_reply.started":"2025-02-20T12:53:30.586272Z","shell.execute_reply":"2025-02-20T12:53:31.010924Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"# make a prediction for a new image.\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import load_model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.012909Z","iopub.execute_input":"2025-02-20T12:53:31.013230Z","iopub.status.idle":"2025-02-20T12:53:31.017827Z","shell.execute_reply.started":"2025-02-20T12:53:31.013198Z","shell.execute_reply":"2025-02-20T12:53:31.016949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load and prepare the image\ndef load_image(filename):\n\t# load the image\n\timg = load_img(filename, target_size=(224, 224))\n\t# convert to array\n\timg = img_to_array(img)\n\t# reshape into a single sample with 3 channels\n\timg = img.reshape(1, 224, 224, 3)\n\t# center pixel data\n\timg = img.astype('float32')\n\timg = img - [123.68, 116.779, 103.939]\n\treturn img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.018970Z","iopub.execute_input":"2025-02-20T12:53:31.019257Z","iopub.status.idle":"2025-02-20T12:53:31.035446Z","shell.execute_reply.started":"2025-02-20T12:53:31.019232Z","shell.execute_reply":"2025-02-20T12:53:31.034654Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load an image and predict the class\ndef run_example():\n\t# load the image\n\timg = load_image('sample_image.jpg')\n\t# load model\n\tmodel = load_model('final_model.h5')\n\t# predict the class\n\tresult = model.predict(img)\n\tprint(result[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.036311Z","iopub.execute_input":"2025-02-20T12:53:31.036530Z","iopub.status.idle":"2025-02-20T12:53:31.049785Z","shell.execute_reply.started":"2025-02-20T12:53:31.036510Z","shell.execute_reply":"2025-02-20T12:53:31.048988Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"load_image(filename)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.051052Z","iopub.execute_input":"2025-02-20T12:53:31.051298Z","iopub.status.idle":"2025-02-20T12:53:31.065194Z","shell.execute_reply.started":"2025-02-20T12:53:31.051264Z","shell.execute_reply":"2025-02-20T12:53:31.064383Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.preprocessing import image\nimport requests\nfrom io import BytesIO\n\nurl = 'https://machinelearningmastery.com/wp-content/uploads/2019/03/sample_image.jpg'\nresponse = requests.get(url)\nimg = image.load_img(BytesIO(response.content), target_size=(224, 224))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.066206Z","iopub.execute_input":"2025-02-20T12:53:31.066438Z","iopub.status.idle":"2025-02-20T12:53:31.149132Z","shell.execute_reply.started":"2025-02-20T12:53:31.066418Z","shell.execute_reply":"2025-02-20T12:53:31.148360Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.getcwd())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.150097Z","iopub.execute_input":"2025-02-20T12:53:31.150333Z","iopub.status.idle":"2025-02-20T12:53:31.154837Z","shell.execute_reply.started":"2025-02-20T12:53:31.150311Z","shell.execute_reply":"2025-02-20T12:53:31.153904Z"}},"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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.156070Z","iopub.execute_input":"2025-02-20T12:53:31.156411Z","iopub.status.idle":"2025-02-20T12:53:31.164877Z","shell.execute_reply.started":"2025-02-20T12:53:31.156383Z","shell.execute_reply":"2025-02-20T12:53:31.164082Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.165911Z","iopub.execute_input":"2025-02-20T12:53:31.166141Z","iopub.status.idle":"2025-02-20T12:53:31.178788Z","shell.execute_reply.started":"2025-02-20T12:53:31.166121Z","shell.execute_reply":"2025-02-20T12:53:31.177981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:31.179895Z","iopub.execute_input":"2025-02-20T12:53:31.180610Z","iopub.status.idle":"2025-02-20T12:53:32.218673Z","shell.execute_reply.started":"2025-02-20T12:53:31.180575Z","shell.execute_reply":"2025-02-20T12:53:32.217575Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:32.220128Z","iopub.execute_input":"2025-02-20T12:53:32.220443Z","iopub.status.idle":"2025-02-20T12:53:33.252578Z","shell.execute_reply.started":"2025-02-20T12:53:32.220416Z","shell.execute_reply":"2025-02-20T12:53:33.251479Z"}},"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:33.254051Z","iopub.execute_input":"2025-02-20T12:53:33.254357Z","iopub.status.idle":"2025-02-20T12:53:36.232009Z","shell.execute_reply.started":"2025-02-20T12:53:33.254331Z","shell.execute_reply":"2025-02-20T12:53:36.231219Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom keras.applications.vgg16 import preprocess_input\nfrom keras.models import load_model\n\n# ฟังก์ชันสำหรับการสุ่มรูป\ndef random_image_from_folder(folder, num_images=5):\n    # สุ่มไฟล์จากโฟลเดอร์ที่ระบุ\n    image_files = random.sample(os.listdir(folder), num_images)\n    images = []\n    for file in image_files:\n        img_path = os.path.join(folder, file)\n        img = image.load_img(img_path, target_size=(224, 224))  # Resize ภาพให้ขนาดที่ต้องการ\n        img_array = image.img_to_array(img)\n        img_array = np.expand_dims(img_array, axis=0)  # เพิ่มมิติ\n        images.append((img_array, file, img))  # เก็บทั้งภาพและชื่อไฟล์\n    return images\n\n# ฟังก์ชันทำนายรูป\ndef predict_image(model, img_array):\n    prediction = model.predict(img_array)\n    return \"Dog\" if prediction[0] > 0.5 else \"Cat\"\n\n# ฟังก์ชันสำหรับแสดงรูปพร้อมผลการทำนายและเฉลย\ndef plot_images_with_predictions(model, folder_dog, folder_cat, num_images=5):\n    # สุ่มภาพหมาและแมว\n    dog_images = random_image_from_folder(folder_dog, num_images)\n    cat_images = random_image_from_folder(folder_cat, num_images)\n\n    # สร้างกราฟ\n    plt.figure(figsize=(12, 6))  # กำหนดขนาดของกราฟ\n\n    # แสดงผลการทำนายหมา (แถวแรก)\n    for i, (img_array, img_name, img) in enumerate(dog_images):\n        plt.subplot(2, 5, i + 1)  # การจัดรูปภาพในแถวแรก\n        plt.imshow(img)  # ใช้ภาพเดิมที่ไม่ผ่านการ preprocess\n        predicted_label = predict_image(model, img_array)\n        true_label = \"Dog\"  # เนื่องจากเป็นภาพหมา\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: {true_label}\")\n        plt.axis('off')\n\n    # แสดงผลการทำนายแมว (แถวที่สอง)\n    for i, (img_array, img_name, img) in enumerate(cat_images):\n        plt.subplot(2, 5, i + 6)  # การจัดรูปภาพในแถวที่สอง\n        plt.imshow(img)  # ใช้ภาพเดิมที่ไม่ผ่านการ preprocess\n        predicted_label = predict_image(model, img_array)\n        true_label = \"Cat\"  # เนื่องจากเป็นภาพแมว\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: {true_label}\")\n        plt.axis('off')\n\n    plt.tight_layout()  # ทำให้กราฟไม่เบียดกัน\n    plt.show()\n\n# ใช้โมเดลที่คุณฝึกไว้\n# สมมุติว่าโมเดลถูกฝึกและบันทึกแล้ว\n# เปลี่ยนให้โมเดลเป็นโมเดลที่คุณใช้\nmodel = my_model  # หรือโมเดลของคุณที่ฝึกมา\n\n# โฟลเดอร์สำหรับหมาและแมว\nfolder_dog = 'dataset_dogs_vs_cats/test/dogs'\nfolder_cat = 'dataset_dogs_vs_cats/test/cats'\n\n# เรียกใช้ฟังก์ชันในการแสดงผล\nplot_images_with_predictions(model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:36.233201Z","iopub.execute_input":"2025-02-20T12:53:36.233485Z","iopub.status.idle":"2025-02-20T12:53:39.667454Z","shell.execute_reply.started":"2025-02-20T12:53:36.233462Z","shell.execute_reply":"2025-02-20T12:53:39.666549Z"}},"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'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:39.668529Z","iopub.execute_input":"2025-02-20T12:53:39.669053Z","iopub.status.idle":"2025-02-20T12:53:39.701607Z","shell.execute_reply.started":"2025-02-20T12:53:39.669026Z","shell.execute_reply":"2025-02-20T12:53:39.700793Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_SIZE = (299, 299)\n\ndatagen = ImageDataGenerator(rescale=1.0/255.0,\n                            horizontal_flip=True,)\n\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=IMAGE_SIZE )\n\nval_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                                 horizontal_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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:39.702618Z","iopub.execute_input":"2025-02-20T12:53:39.702857Z","iopub.status.idle":"2025-02-20T12:53:41.433417Z","shell.execute_reply.started":"2025-02-20T12:53:39.702835Z","shell.execute_reply":"2025-02-20T12:53:41.432786Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"InceptionV3","metadata":{}},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\nfrom keras.layers import Flatten, Dense, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import SGD\n\ndef define_model_inceptionv3():\n    # load model\n    model = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n\n    # mark loaded layers as not trainable\n    for layer in model.layers:\n        layer.trainable = False\n\n    # add new classifier layers\n    flat1 = Flatten()(model.layers[-1].output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    drop1 = Dropout(0.5)(class1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(drop1)\n    drop2 = Dropout(0.5)(class2)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(drop2)\n    drop3 = Dropout(0.5)(class3)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(drop3)\n    drop4 = Dropout(0.5)(class4)\n    \n    output = Dense(1, activation='sigmoid')(drop4)  # ใช้ drop4 แทน class4\n\n    # define new model\n    model = Model(inputs=model.inputs, outputs=output)\n\n    # compile model\n    opt = SGD(learning_rate=0.001, momentum=0.9)  # เปลี่ยน lr เป็น learning_rate\n    model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:41.434434Z","iopub.execute_input":"2025-02-20T12:53:41.434691Z","iopub.status.idle":"2025-02-20T12:53:41.441963Z","shell.execute_reply.started":"2025-02-20T12:53:41.434668Z","shell.execute_reply":"2025-02-20T12:53:41.441110Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\ndef plot_exmaple(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 < test_images.shape[0]:\n            ax.imshow(test_images[i])\n        ax.axis('off')  # Turn off axis ticks/labels for clarity\n    \n    plt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:41.442912Z","iopub.execute_input":"2025-02-20T12:53:41.443168Z","iopub.status.idle":"2025-02-20T12:53:41.463289Z","shell.execute_reply.started":"2025-02-20T12:53:41.443148Z","shell.execute_reply":"2025-02-20T12:53:41.462542Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:41.464204Z","iopub.execute_input":"2025-02-20T12:53:41.464452Z","iopub.status.idle":"2025-02-20T12:53:44.231125Z","shell.execute_reply.started":"2025-02-20T12:53:41.464431Z","shell.execute_reply":"2025-02-20T12:53:44.230224Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:44.232404Z","iopub.execute_input":"2025-02-20T12:53:44.232680Z","iopub.status.idle":"2025-02-20T12:53:44.883458Z","shell.execute_reply.started":"2025-02-20T12:53:44.232655Z","shell.execute_reply":"2025-02-20T12:53:44.878900Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:44.884593Z","iopub.execute_input":"2025-02-20T12:53:44.884948Z","iopub.status.idle":"2025-02-20T12:53:44.897883Z","shell.execute_reply.started":"2025-02-20T12:53:44.884914Z","shell.execute_reply":"2025-02-20T12:53:44.896981Z"}},"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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T12:53:44.898899Z","iopub.execute_input":"2025-02-20T12:53:44.899166Z","iopub.status.idle":"2025-02-20T13:01:44.643704Z","shell.execute_reply.started":"2025-02-20T12:53:44.899144Z","shell.execute_reply":"2025-02-20T13:01:44.642793Z"}},"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}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:01:44.645176Z","iopub.execute_input":"2025-02-20T13:01:44.645890Z","iopub.status.idle":"2025-02-20T13:01:44.652591Z","shell.execute_reply.started":"2025-02-20T13:01:44.645851Z","shell.execute_reply":"2025-02-20T13:01:44.651793Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:01:44.653524Z","iopub.execute_input":"2025-02-20T13:01:44.653762Z","iopub.status.idle":"2025-02-20T13:02:33.690763Z","shell.execute_reply.started":"2025-02-20T13:01:44.653720Z","shell.execute_reply":"2025-02-20T13:02:33.690090Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(test_it)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:33.691824Z","iopub.execute_input":"2025-02-20T13:02:33.692130Z","iopub.status.idle":"2025-02-20T13:02:33.697493Z","shell.execute_reply.started":"2025-02-20T13:02:33.692103Z","shell.execute_reply":"2025-02-20T13:02:33.696691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"next(iter(test_it))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:33.698986Z","iopub.execute_input":"2025-02-20T13:02:33.699292Z","iopub.status.idle":"2025-02-20T13:02:33.874298Z","shell.execute_reply.started":"2025-02-20T13:02:33.699263Z","shell.execute_reply":"2025-02-20T13:02:33.873555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_inceptionv3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:33.875193Z","iopub.execute_input":"2025-02-20T13:02:33.875422Z","iopub.status.idle":"2025-02-20T13:02:34.312764Z","shell.execute_reply.started":"2025-02-20T13:02:33.875402Z","shell.execute_reply":"2025-02-20T13:02:34.311906Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom keras.applications.inception_v3 import preprocess_input  # ใช้ preprocess ของ InceptionV3\nfrom keras.models import load_model\n\n# ฟังก์ชันสำหรับการสุ่มรูป\ndef random_image_from_folder(folder, num_images=5):\n    image_files = random.sample(os.listdir(folder), num_images)\n    images = []\n    for file in image_files:\n        img_path = os.path.join(folder, file)\n        img = image.load_img(img_path, target_size=(299, 299))  # ใช้ 299x299\n        img_array = image.img_to_array(img)\n        img_array = np.expand_dims(img_array, axis=0)  # เพิ่มมิติ\n        img_array = preprocess_input(img_array)  # 🔹 ใช้ preprocess_input\n        images.append((img_array, file, img))\n    return images\n\n# ฟังก์ชันทำนายรูป\ndef predict_image(model, img_array):\n    prediction = model.predict(img_array, batch_size=1)[0][0]  # 🔹 กำหนด batch_size=1\n    print(f\"Confidence Score: {prediction:.4f}\")  # 🔹 เพิ่มการพิมพ์ค่า Score\n    return \"Dog\" if prediction > 0.5 else \"Cat\"  # 🔹 ปรับ Threshold กลับไป 0.5\n\n# ฟังก์ชันสำหรับแสดงรูปพร้อมผลการทำนายและเฉลย\ndef plot_images_with_predictions(model, folder_dog, folder_cat, num_images=5):\n    dog_images = random_image_from_folder(folder_dog, num_images)\n    cat_images = random_image_from_folder(folder_cat, num_images)\n\n    plt.figure(figsize=(12, 6))\n\n    for i, (img_array, img_name, img) in enumerate(dog_images):\n        plt.subplot(2, 5, i + 1)\n        plt.imshow(img)\n        predicted_label = predict_image(model, img_array)\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: Dog\")\n        plt.axis('off')\n\n    for i, (img_array, img_name, img) in enumerate(cat_images):\n        plt.subplot(2, 5, i + 6)\n        plt.imshow(img)\n        predicted_label = predict_image(model, img_array)\n        plt.title(f\"Prediction: {predicted_label}\\nTrue: Cat\")\n        plt.axis('off')\n\n    plt.tight_layout()\n    plt.show()\n\n# โหลดโมเดลที่ฝึกไว้\nmodel = model_inceptionv3  # แทนด้วยโมเดลที่คุณฝึก\n\n# โฟลเดอร์สำหรับหมาและแมว\nfolder_dog = 'dataset_dogs_vs_cats/test/dogs'\nfolder_cat = 'dataset_dogs_vs_cats/test/cats'\n\n# เรียกใช้ฟังก์ชันในการแสดงผล\nplot_images_with_predictions(model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:34.314065Z","iopub.execute_input":"2025-02-20T13:02:34.314388Z","iopub.status.idle":"2025-02-20T13:02:38.036202Z","shell.execute_reply.started":"2025-02-20T13:02:34.314357Z","shell.execute_reply":"2025-02-20T13:02:38.035199Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Training set:\")\nprint(train_it.class_indices)\nprint(train_it.samples)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:38.037500Z","iopub.execute_input":"2025-02-20T13:02:38.037840Z","iopub.status.idle":"2025-02-20T13:02:38.042519Z","shell.execute_reply.started":"2025-02-20T13:02:38.037796Z","shell.execute_reply":"2025-02-20T13:02:38.041684Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.utils.class_weight import compute_class_weight\nimport numpy as np\n\nclass_weights = compute_class_weight('balanced', classes=np.array([0, 1]), y=train_it.classes)\nclass_weight_dict = {i: class_weights[i] for i in range(len(class_weights))}\n\nmodel_inceptionv3.fit(train_it, epochs=3, class_weight=class_weight_dict)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:02:38.043766Z","iopub.execute_input":"2025-02-20T13:02:38.044494Z","iopub.status.idle":"2025-02-20T13:07:53.860221Z","shell.execute_reply.started":"2025-02-20T13:02:38.044457Z","shell.execute_reply":"2025-02-20T13:07:53.859523Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"resnet_model","metadata":{}},{"cell_type":"code","source":"from keras.layers import GlobalAveragePooling2D\n\ndef create_model(base_model, input_shape=(224, 224, 3), num_classes=1):\n    base_model = base_model(include_top=False, input_shape=input_shape, weights='imagenet')\n\n    for layer in base_model.layers:\n        layer.trainable = False\n\n    # x = GlobalAveragePooling2D()(base_model.output)\n    # x = Dense(512, activation='relu')(x)\n    # x = Dropout(0.5)(x)\n    # x = Dense(256, activation='relu')(x)\n    # x = Dropout(0.5)(x)\n\n    flat1 = GlobalAveragePooling2D()(base_model.output)\n    class1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n    drop1 = Dropout(0.5)(class1)\n    class2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(drop1)\n    drop2 = Dropout(0.5)(class2)\n    class3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(drop2)\n    drop3 = Dropout(0.5)(class3)\n    class4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(drop3)\n    drop4 = Dropout(0.5)(class4)\n    output = Dense(num_classes, activation='sigmoid' if num_classes == 1 else 'softmax')(drop4)\n\n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:07:53.861236Z","iopub.execute_input":"2025-02-20T13:07:53.861489Z","iopub.status.idle":"2025-02-20T13:07:53.868027Z","shell.execute_reply.started":"2025-02-20T13:07:53.861466Z","shell.execute_reply":"2025-02-20T13:07:53.867221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.applications import ResNet50\nresnet_model = create_model(ResNet50, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:07:53.869118Z","iopub.execute_input":"2025-02-20T13:07:53.869716Z","iopub.status.idle":"2025-02-20T13:07:55.991106Z","shell.execute_reply.started":"2025-02-20T13:07:53.869682Z","shell.execute_reply":"2025-02-20T13:07:55.990413Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:07:55.992112Z","iopub.execute_input":"2025-02-20T13:07:55.992371Z","iopub.status.idle":"2025-02-20T13:07:56.007237Z","shell.execute_reply.started":"2025-02-20T13:07:55.992348Z","shell.execute_reply":"2025-02-20T13:07:56.006573Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nresnet_model.reset_states()\nhistory_resnet_model = resnet_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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:07:56.008134Z","iopub.execute_input":"2025-02-20T13:07:56.008363Z","iopub.status.idle":"2025-02-20T13:15:50.442098Z","shell.execute_reply.started":"2025-02-20T13:07:56.008342Z","shell.execute_reply":"2025-02-20T13:15:50.441404Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = resnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:15:50.443291Z","iopub.execute_input":"2025-02-20T13:15:50.443553Z","iopub.status.idle":"2025-02-20T13:16:39.021582Z","shell.execute_reply.started":"2025-02-20T13:15:50.443530Z","shell.execute_reply":"2025-02-20T13:16:39.020913Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_inceptionv3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:39.022654Z","iopub.execute_input":"2025-02-20T13:16:39.023016Z","iopub.status.idle":"2025-02-20T13:16:39.455552Z","shell.execute_reply.started":"2025-02-20T13:16:39.022991Z","shell.execute_reply":"2025-02-20T13:16:39.454794Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(resnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:39.456452Z","iopub.execute_input":"2025-02-20T13:16:39.456671Z","iopub.status.idle":"2025-02-20T13:16:42.519639Z","shell.execute_reply.started":"2025-02-20T13:16:39.456651Z","shell.execute_reply":"2025-02-20T13:16:42.518722Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"MobileNetV2","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import MobileNetV2\nmobilenet_model = create_model(MobileNetV2, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:42.520852Z","iopub.execute_input":"2025-02-20T13:16:42.521119Z","iopub.status.idle":"2025-02-20T13:16:43.865670Z","shell.execute_reply.started":"2025-02-20T13:16:42.521097Z","shell.execute_reply":"2025-02-20T13:16:43.864672Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:43.866886Z","iopub.execute_input":"2025-02-20T13:16:43.867528Z","iopub.status.idle":"2025-02-20T13:16:43.881279Z","shell.execute_reply.started":"2025-02-20T13:16:43.867500Z","shell.execute_reply":"2025-02-20T13:16:43.880490Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"mobilenet_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:43.882170Z","iopub.execute_input":"2025-02-20T13:16:43.882449Z","iopub.status.idle":"2025-02-20T13:16:44.585221Z","shell.execute_reply.started":"2025-02-20T13:16:43.882424Z","shell.execute_reply":"2025-02-20T13:16:44.584315Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nresnet_model.reset_states()\nhistory_mobilenet_model = mobilenet_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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:16:44.586235Z","iopub.execute_input":"2025-02-20T13:16:44.586487Z","iopub.status.idle":"2025-02-20T13:24:39.055585Z","shell.execute_reply.started":"2025-02-20T13:16:44.586463Z","shell.execute_reply":"2025-02-20T13:24:39.054883Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = mobilenet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:24:39.056678Z","iopub.execute_input":"2025-02-20T13:24:39.056992Z","iopub.status.idle":"2025-02-20T13:25:27.817859Z","shell.execute_reply.started":"2025-02-20T13:24:39.056966Z","shell.execute_reply":"2025-02-20T13:25:27.817101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_mobilenet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:25:27.819215Z","iopub.execute_input":"2025-02-20T13:25:27.819904Z","iopub.status.idle":"2025-02-20T13:25:28.272504Z","shell.execute_reply.started":"2025-02-20T13:25:27.819864Z","shell.execute_reply":"2025-02-20T13:25:28.271729Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(mobilenet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:25:28.279013Z","iopub.execute_input":"2025-02-20T13:25:28.279284Z","iopub.status.idle":"2025-02-20T13:25:31.140971Z","shell.execute_reply.started":"2025-02-20T13:25:28.279259Z","shell.execute_reply":"2025-02-20T13:25:31.140086Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"EfficientNetB0","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import EfficientNetB0\nefficientnet_model = create_model(EfficientNetB0, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:25:31.142062Z","iopub.execute_input":"2025-02-20T13:25:31.142328Z","iopub.status.idle":"2025-02-20T13:25:33.242424Z","shell.execute_reply.started":"2025-02-20T13:25:31.142304Z","shell.execute_reply":"2025-02-20T13:25:33.241445Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:25:33.243582Z","iopub.execute_input":"2025-02-20T13:25:33.243889Z","iopub.status.idle":"2025-02-20T13:25:33.257730Z","shell.execute_reply.started":"2025-02-20T13:25:33.243864Z","shell.execute_reply":"2025-02-20T13:25:33.256961Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nefficientnet_model.reset_states()\nhistory_efficientnet_model = efficientnet_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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:25:33.258924Z","iopub.execute_input":"2025-02-20T13:25:33.259455Z","iopub.status.idle":"2025-02-20T13:33:28.787493Z","shell.execute_reply.started":"2025-02-20T13:25:33.259418Z","shell.execute_reply":"2025-02-20T13:33:28.786618Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = efficientnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:33:28.788864Z","iopub.execute_input":"2025-02-20T13:33:28.789497Z","iopub.status.idle":"2025-02-20T13:34:18.191063Z","shell.execute_reply.started":"2025-02-20T13:33:28.789460Z","shell.execute_reply":"2025-02-20T13:34:18.190256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_efficientnet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:34:18.192159Z","iopub.execute_input":"2025-02-20T13:34:18.192429Z","iopub.status.idle":"2025-02-20T13:34:18.626655Z","shell.execute_reply.started":"2025-02-20T13:34:18.192406Z","shell.execute_reply":"2025-02-20T13:34:18.625788Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(efficientnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:34:18.627801Z","iopub.execute_input":"2025-02-20T13:34:18.628087Z","iopub.status.idle":"2025-02-20T13:34:21.385036Z","shell.execute_reply.started":"2025-02-20T13:34:18.628063Z","shell.execute_reply":"2025-02-20T13:34:21.384170Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"NASNetMobile","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications import NASNetMobile\nnasnet_model = create_model(NASNetMobile, input_shape=(224, 224, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:34:21.386259Z","iopub.execute_input":"2025-02-20T13:34:21.386898Z","iopub.status.idle":"2025-02-20T13:34:27.636653Z","shell.execute_reply.started":"2025-02-20T13:34:21.386864Z","shell.execute_reply":"2025-02-20T13:34:27.635939Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.optimizers import Adam\n\nmodel.compile(optimizer=Adam(learning_rate=1e-4), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:34:27.637718Z","iopub.execute_input":"2025-02-20T13:34:27.638041Z","iopub.status.idle":"2025-02-20T13:34:27.652224Z","shell.execute_reply.started":"2025-02-20T13:34:27.638018Z","shell.execute_reply":"2025-02-20T13:34:27.651510Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nnasnet_model.reset_states()\nhistory_nasnet_model = nasnet_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()])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:34:27.653300Z","iopub.execute_input":"2025-02-20T13:34:27.653867Z","iopub.status.idle":"2025-02-20T13:42:22.709159Z","shell.execute_reply.started":"2025-02-20T13:34:27.653834Z","shell.execute_reply":"2025-02-20T13:42:22.708492Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = nasnet_model.evaluate(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:42:22.710253Z","iopub.execute_input":"2025-02-20T13:42:22.710477Z","iopub.status.idle":"2025-02-20T13:43:12.338522Z","shell.execute_reply.started":"2025-02-20T13:42:22.710457Z","shell.execute_reply":"2025-02-20T13:43:12.337685Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_nasnet_model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:43:12.339622Z","iopub.execute_input":"2025-02-20T13:43:12.339899Z","iopub.status.idle":"2025-02-20T13:43:12.671222Z","shell.execute_reply.started":"2025-02-20T13:43:12.339870Z","shell.execute_reply":"2025-02-20T13:43:12.670479Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_predictions(nasnet_model, folder_dog, folder_cat)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-20T13:43:12.672295Z","iopub.execute_input":"2025-02-20T13:43:12.672527Z","iopub.status.idle":"2025-02-20T13:43:15.533431Z","shell.execute_reply.started":"2025-02-20T13:43:12.672506Z","shell.execute_reply":"2025-02-20T13:43:15.532498Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}