{"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","execution":{"iopub.status.busy":"2025-02-14T15:05:25.038724Z","iopub.execute_input":"2025-02-14T15:05:25.039191Z","iopub.status.idle":"2025-02-14T15:05:25.044703Z","shell.execute_reply.started":"2025-02-14T15:05:25.039164Z","shell.execute_reply":"2025-02-14T15:05:25.044094Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:28.781558Z","iopub.execute_input":"2025-02-14T15:05:28.782178Z","iopub.status.idle":"2025-02-14T15:05:29.791759Z","shell.execute_reply.started":"2025-02-14T15:05:28.782148Z","shell.execute_reply":"2025-02-14T15:05:29.790639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))\n\nimport zipfile\n\nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:29.793787Z","iopub.execute_input":"2025-02-14T15:05:29.794089Z","iopub.status.idle":"2025-02-14T15:05:39.200007Z","shell.execute_reply.started":"2025-02-14T15:05:29.794065Z","shell.execute_reply":"2025-02-14T15:05:39.199262Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:39.201Z","iopub.execute_input":"2025-02-14T15:05:39.201252Z","iopub.status.idle":"2025-02-14T15:05:40.202287Z","shell.execute_reply.started":"2025-02-14T15:05:39.20123Z","shell.execute_reply":"2025-02-14T15:05:40.201407Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:40.204731Z","iopub.execute_input":"2025-02-14T15:05:40.205035Z","iopub.status.idle":"2025-02-14T15:05:41.234009Z","shell.execute_reply.started":"2025-02-14T15:05:40.20501Z","shell.execute_reply":"2025-02-14T15:05:41.233169Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:41.235167Z","iopub.execute_input":"2025-02-14T15:05:41.235419Z","iopub.status.idle":"2025-02-14T15:05:42.292289Z","shell.execute_reply.started":"2025-02-14T15:05:41.235396Z","shell.execute_reply":"2025-02-14T15:05:42.291459Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:42.293439Z","iopub.execute_input":"2025-02-14T15:05:42.29369Z","iopub.status.idle":"2025-02-14T15:05:43.388932Z","shell.execute_reply.started":"2025-02-14T15:05:42.293665Z","shell.execute_reply":"2025-02-14T15:05:43.388095Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:43.390283Z","iopub.execute_input":"2025-02-14T15:05:43.39057Z","iopub.status.idle":"2025-02-14T15:05:44.538024Z","shell.execute_reply.started":"2025-02-14T15:05:43.390541Z","shell.execute_reply":"2025-02-14T15:05:44.536818Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\n# define location of dataset\nfolder = 'train/'\n# plot first few images\nfor i in range(9):\n\t# define subplot\n\tpyplot.subplot(330 + 1 + i)\n\t# define filename\n\tfilename = folder + 'dog.' + str(i) + '.jpg'\n\t# load image pixels\n\timage = imread(filename)\n\t# plot raw pixel data\n\tpyplot.imshow(image)\n# show the figure\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:44.539873Z","iopub.execute_input":"2025-02-14T15:05:44.540342Z","iopub.status.idle":"2025-02-14T15:05:45.587621Z","shell.execute_reply.started":"2025-02-14T15:05:44.540282Z","shell.execute_reply":"2025-02-14T15:05:45.586729Z"},"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-14T15:05:45.589946Z","iopub.execute_input":"2025-02-14T15:05:45.590201Z","iopub.status.idle":"2025-02-14T15:05:46.528753Z","shell.execute_reply.started":"2025-02-14T15:05:45.590178Z","shell.execute_reply":"2025-02-14T15:05:46.527946Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow\nprint(tensorflow.__version__)\n\nimport keras\nprint(keras.__version__)\n\nimport tensorflow.keras\nprint(tensorflow.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:46.529942Z","iopub.execute_input":"2025-02-14T15:05:46.530269Z","iopub.status.idle":"2025-02-14T15:05:49.314402Z","shell.execute_reply.started":"2025-02-14T15:05:46.530238Z","shell.execute_reply":"2025-02-14T15:05:49.313229Z"}},"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-14T15:05:49.315774Z","iopub.execute_input":"2025-02-14T15:05:49.316649Z","iopub.status.idle":"2025-02-14T15:05:49.323823Z","shell.execute_reply.started":"2025-02-14T15:05:49.316604Z","shell.execute_reply":"2025-02-14T15:05:49.322112Z"},"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-14T15:05:49.326577Z","iopub.execute_input":"2025-02-14T15:05:49.326999Z","iopub.status.idle":"2025-02-14T15:05:49.346118Z","shell.execute_reply.started":"2025-02-14T15:05:49.326961Z","shell.execute_reply":"2025-02-14T15:05:49.344438Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/'] #test==>validation\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir       \n        makedirs(newdir, exist_ok=True)\n        print(newdir)","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:49.347136Z","iopub.execute_input":"2025-02-14T15:05:49.347343Z","iopub.status.idle":"2025-02-14T15:05:49.355488Z","shell.execute_reply.started":"2025-02-14T15:05:49.347324Z","shell.execute_reply":"2025-02-14T15:05:49.354666Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train/dogs/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:49.356392Z","iopub.execute_input":"2025-02-14T15:05:49.35669Z","iopub.status.idle":"2025-02-14T15:05:50.509244Z","shell.execute_reply.started":"2025-02-14T15:05:49.356668Z","shell.execute_reply":"2025-02-14T15:05:50.508173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:50.510582Z","iopub.execute_input":"2025-02-14T15:05:50.510852Z","iopub.status.idle":"2025-02-14T15:05:51.524853Z","shell.execute_reply.started":"2025-02-14T15:05:50.510829Z","shell.execute_reply":"2025-02-14T15:05:51.52357Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:51.526614Z","iopub.execute_input":"2025-02-14T15:05:51.526998Z","iopub.status.idle":"2025-02-14T15:05:52.583097Z","shell.execute_reply.started":"2025-02-14T15:05:51.526964Z","shell.execute_reply":"2025-02-14T15:05:52.582057Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:52.584778Z","iopub.execute_input":"2025-02-14T15:05:52.585141Z","iopub.status.idle":"2025-02-14T15:05:53.588374Z","shell.execute_reply.started":"2025-02-14T15:05:52.585108Z","shell.execute_reply":"2025-02-14T15:05:53.587522Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# seed random number generator\nseed(1337)\n# define ratio of pictures to use for validation\nval_ratio = 0.25 #changable\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\n\nfor file in listdir(src_directory):\n\tsrc = src_directory + '/' + file\n\tdst_dir = 'train/'\n\tif random() < val_ratio:\n\t\tdst_dir = 'test/'\n\tif file.startswith('cat'):\n\t\tdst = dataset_home + dst_dir + 'cats/'  + file\n\t\tcopyfile(src, dst)\n\telif file.startswith('dog'):\n\t\tdst = dataset_home + dst_dir + 'dogs/'  + file\n\t\tcopyfile(src, dst)","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:53.589663Z","iopub.execute_input":"2025-02-14T15:05:53.589935Z","iopub.status.idle":"2025-02-14T15:05:56.982774Z","shell.execute_reply.started":"2025-02-14T15:05:53.589906Z","shell.execute_reply":"2025-02-14T15:05:56.981793Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:05:56.984123Z","iopub.execute_input":"2025-02-14T15:05:56.984818Z","iopub.status.idle":"2025-02-14T15:05:56.989724Z","shell.execute_reply.started":"2025-02-14T15:05:56.984783Z","shell.execute_reply":"2025-02-14T15:05:56.988755Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:56.990975Z","iopub.execute_input":"2025-02-14T15:05:56.991539Z","iopub.status.idle":"2025-02-14T15:05:59.152083Z","shell.execute_reply.started":"2025-02-14T15:05:56.991507Z","shell.execute_reply":"2025-02-14T15:05:59.151014Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#validation set\n!ls -l dataset_dogs_vs_cats/test/dogs | wc -l\n!ls -l dataset_dogs_vs_cats/test/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:05:59.153501Z","iopub.execute_input":"2025-02-14T15:05:59.153759Z","iopub.status.idle":"2025-02-14T15:06:01.285305Z","shell.execute_reply.started":"2025-02-14T15:05:59.153736Z","shell.execute_reply":"2025-02-14T15:06:01.283942Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:06:01.289996Z","iopub.execute_input":"2025-02-14T15:06:01.290292Z","iopub.status.idle":"2025-02-14T15:06:09.529386Z","shell.execute_reply.started":"2025-02-14T15:06:01.290266Z","shell.execute_reply":"2025-02-14T15:06:09.528097Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-14T15:06:09.530778Z","iopub.execute_input":"2025-02-14T15:06:09.531078Z","iopub.status.idle":"2025-02-14T15:06:09.541824Z","shell.execute_reply.started":"2025-02-14T15:06:09.531053Z","shell.execute_reply":"2025-02-14T15:06:09.540904Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Prepare Final Dataset","metadata":{}},{"cell_type":"markdown","source":"# Start tutorial\n# Develop a Baseline CNN Model","metadata":{}},{"cell_type":"code","source":"# https://keras.io/api/applications/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:09.543101Z","iopub.execute_input":"2025-02-14T15:06:09.54345Z","iopub.status.idle":"2025-02-14T15:06:09.54867Z","shell.execute_reply.started":"2025-02-14T15:06:09.543419Z","shell.execute_reply":"2025-02-14T15:06:09.548017Z"}},"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-14T15:06:09.549622Z","iopub.execute_input":"2025-02-14T15:06:09.549899Z","iopub.status.idle":"2025-02-14T15:06:09.55929Z","shell.execute_reply.started":"2025-02-14T15:06:09.549878Z","shell.execute_reply":"2025-02-14T15:06:09.558514Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define cnn model\ndef define_model_1():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(128, activation='relu', kernel_initializer='he_uniform'))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:09.560125Z","iopub.execute_input":"2025-02-14T15:06:09.560346Z","iopub.status.idle":"2025-02-14T15:06:09.568775Z","shell.execute_reply.started":"2025-02-14T15:06:09.560318Z","shell.execute_reply":"2025-02-14T15:06:09.567997Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n\t# plot loss\n\tpyplot.subplot(211)\n\tpyplot.title('Cross Entropy Loss')\n\tpyplot.plot(history.history['loss'], color='blue', label='train')\n\tpyplot.plot(history.history['val_loss'], color='orange', label='test')\n\t# plot accuracy\n\tpyplot.subplot(212)\n\tpyplot.title('Classification Accuracy')\n\tpyplot.plot(history.history['accuracy'], color='blue', label='train')\n\tpyplot.plot(history.history['val_accuracy'], color='orange', label='test')\n\t# save plot to file\n\tfilename = sys.argv[0].split('/')[-1]\n\tpyplot.savefig(filename + '_plot.png')\n    pyplot.show()\n\tpyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:09.569723Z","iopub.execute_input":"2025-02-14T15:06:09.569958Z","iopub.status.idle":"2025-02-14T15:06:09.581467Z","shell.execute_reply.started":"2025-02-14T15:06:09.569938Z","shell.execute_reply":"2025-02-14T15:06:09.580346Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run the test harness for evaluating a model\ndef run_test_harness():\n\t# define model\n\tmodel = define_model()\n\t# create data generator\n\tdatagen = ImageDataGenerator(rescale=1.0/255.0)\n\t# prepare iterators\n\ttrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\ttest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\t\tclass_mode='binary', batch_size=64, target_size=(200, 200))\n\t# fit model\n\thistory = model.fit_generator(train_it, steps_per_epoch=len(train_it),\n\t\tvalidation_data=test_it, validation_steps=len(test_it), epochs=20, verbose=0)\n\t# evaluate model\n\t_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=0)\n\tprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:26.47453Z","iopub.execute_input":"2025-02-14T15:06:26.474898Z","iopub.status.idle":"2025-02-14T15:06:26.480815Z","shell.execute_reply.started":"2025-02-14T15:06:26.474855Z","shell.execute_reply":"2025-02-14T15:06:26.479879Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_1 = define_model_1()\nprint(model_1.summary())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:28.010505Z","iopub.execute_input":"2025-02-14T15:06:28.011126Z","iopub.status.idle":"2025-02-14T15:06:28.763254Z","shell.execute_reply.started":"2025-02-14T15:06:28.011094Z","shell.execute_reply":"2025-02-14T15:06:28.762414Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1.0/255.0)\n\n# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))\n\nval_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n    class_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:31.036583Z","iopub.execute_input":"2025-02-14T15:06:31.037381Z","iopub.status.idle":"2025-02-14T15:06:31.706905Z","shell.execute_reply.started":"2025-02-14T15:06:31.037348Z","shell.execute_reply":"2025-02-14T15:06:31.706212Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(train_it), len(train_it.classes), train_it.classes[:10]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:31.70846Z","iopub.execute_input":"2025-02-14T15:06:31.709072Z","iopub.status.idle":"2025-02-14T15:06:31.714768Z","shell.execute_reply.started":"2025-02-14T15:06:31.709036Z","shell.execute_reply":"2025-02-14T15:06:31.71399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"len(val_it), len(val_it.classes), val_it.classes[-10:]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:31.903164Z","iopub.execute_input":"2025-02-14T15:06:31.903432Z","iopub.status.idle":"2025-02-14T15:06:31.909356Z","shell.execute_reply.started":"2025-02-14T15:06:31.903408Z","shell.execute_reply":"2025-02-14T15:06:31.908393Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fit model\nmodel_1.reset_states()\nhistory_1 = model_1.fit_generator(\n    train_it, steps_per_epoch=len(train_it),\n    validation_data=train_it,\n    validation_steps=len(val_it),\n    epochs=10, verbose=1,\n    \n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:06:34.707415Z","iopub.execute_input":"2025-02-14T15:06:34.70774Z","iopub.status.idle":"2025-02-14T15:13:53.989752Z","shell.execute_reply.started":"2025-02-14T15:06:34.707712Z","shell.execute_reply":"2025-02-14T15:13:53.988854Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# ดึงข้อมูลจาก val_it (dataset validation)\nbatch_x, batch_y = next(val_it)  # ดึง batch แรกจาก validation set\n\n# ค้นหาตำแหน่งของรูปที่เป็น \"แมว\" (class 0) และ \"สุนัข\" (class 1)\ncat_indices = np.where(batch_y == 0)[0]  # ตำแหน่งของแมว\ndog_indices = np.where(batch_y == 1)[0]  # ตำแหน่งของสุนัข\n\n# สุ่มเลือกแมว 5 รูป และสุนัข 5 รูป\nnp.random.shuffle(cat_indices)\nnp.random.shuffle(dog_indices)\n\nselected_indices = np.concatenate([cat_indices[:5], dog_indices[:5]])\n\n# ดึงรูปที่เลือกมาและพยากรณ์\nselected_images = batch_x[selected_indices]\ntrue_labels = batch_y[selected_indices]\npredictions = model_1.predict(selected_images)\n\n# แสดงผลลัพธ์\nplt.figure(figsize=(12, 6))\nfor i, idx in enumerate(selected_indices):\n    plt.subplot(2, 5, i+1)\n    plt.imshow(selected_images[i])  # แสดงภาพ\n    plt.axis(\"off\")\n    \n    # คำตอบจริง และผลพยากรณ์\n    true_label = \"Cat\" if true_labels[i] == 0 else \"Dog\"\n    pred_label = \"Dog\" if predictions[i] > 0.5 else \"Cat\"\n    plt.title(f\"True: {true_label}\\nPred: {pred_label}\", fontsize=10)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-14T15:24:53.822417Z","iopub.execute_input":"2025-02-14T15:24:53.823337Z","iopub.status.idle":"2025-02-14T15:24:55.1327Z","shell.execute_reply.started":"2025-02-14T15:24:53.823302Z","shell.execute_reply":"2025-02-14T15:24:55.131412Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_1.evaluate_generator(val_it, steps=len(val_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom glob import glob\n\n# Define the image folder path\nimage_folder = '/kaggle/working/test1'\n\n# List all .jpg files in the directory (adjust the pattern if needed)\nimage_files = glob(os.path.join(image_folder, '*.jpg'))\n\n# Check if images were found\nif not image_files:\n    print(\"No images found. Please verify the directory and file extensions.\")\n    \n# Create a DataFrame with the file paths\ndf = pd.DataFrame({'filename': image_files})\n\n# If your use-case doesn't require labels (for example, during testing), you can leave out the label column.\n# Otherwise, if you need a dummy label, you can add one:\n# df['class'] = 'dummy_label'\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[:10]","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Prediction\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Initialize your ImageDataGenerator (modify parameters as needed)\ndatagen = ImageDataGenerator(rescale=1./255)\n\n# Create the data generator using the DataFrame\ntest_it = datagen.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=(200, 200),\n    batch_size=64,\n    class_mode=None,       # Since there are no labels\n    shuffle=True          # Usually testing data should not be shuffled\n)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Transfer Learning\n# 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":{"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":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Image Augmentatioin\n\nfrom 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    fill_mode='reflect',\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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images, labels = train_it.__next__()\nprint(images.shape, labels.shape)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ndef plot_images_with_labels(images, labels, train_log, set_label, save=False):\n    \"\"\"\n    Plots a grid of images with their corresponding labels and saves the figure.\n    \n    Args:\n    - images (list or np.array): List of images to be displayed.\n    - labels (np.array): Array of one-hot encoded labels.\n    - train_log (str): The directory or log name to save the plot.\n    - set_label (str): The specific set label (e.g., \"train\", \"validation\", etc.).\n    - config (dict): Configuration dictionary containing image dimensions.\n    \n    Returns:\n    - None: Displays and saves the plot.\n    \"\"\"\n    # Convert one-hot encoded labels to class indices\n    class_indices = labels\n\n    # Create subplots\n    fig, axes = plt.subplots(3, 4, figsize=(14, 10), dpi=120)\n    axes = axes.flatten()\n\n    for img, label_idx, ax in zip(images, class_indices, axes):\n        # Undo any preprocessing (like rescaling for pre-trained models)\n        if np.max(img) == 1:\n            img = img * 255\n\n        # Display the image\n        img_shape = (224, 224, 3)\n        ax.imshow(img.astype(\"uint8\"))\n        # ax.imshow(img)\n\n        # Set the title to the corresponding class label\n        ax.set_title(f\"Label: {label_idx}\", fontsize=18)\n        ax.axis('on')\n\n    # Set the overall title for the figure\n    plot_title = f\"{train_log}-{set_label}\"\n    plt.suptitle(plot_title, fontsize=18)\n\n    # Show the plot\n    plt.show()\n\n    # Save the figure\n    if save:\n        plot_file = os.path.join(train_log, f\"{plot_title}.png\")\n        fig.savefig(plot_file, dpi=120)\n        print(f'Saved {plot_file}')\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for index, layer in enumerate(model.layers):\n    print(index, layer.output.shape)","metadata":{"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":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.layers[-1].output","metadata":{"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)\n# 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},"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=10, verbose=1,\n                    callbacks=[PlotLossesKeras()])\n# evaluate model\n_, acc = model.evaluate_generator(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\nsummarize_diagnostics(history)\n\nbest_model = 'vgg16_model.hdf5'\nmy_model.save(best_model)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"best_model = load_model(best_model)\nbest_model.evaluate(test_it, verbose=1)","metadata":{"trusted":true},"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\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# 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\n\n# 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])\n\n# entry point, run the example\nrun_example()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}