{"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-15T02:20:11.728185Z","iopub.execute_input":"2025-02-15T02:20:11.728595Z","iopub.status.idle":"2025-02-15T02:20:12.101146Z","shell.execute_reply.started":"2025-02-15T02:20:11.728535Z","shell.execute_reply":"2025-02-15T02:20:12.100288Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!python --version","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:12.102849Z","iopub.execute_input":"2025-02-15T02:20:12.103241Z","iopub.status.idle":"2025-02-15T02:20:13.103385Z","shell.execute_reply.started":"2025-02-15T02:20:12.103217Z","shell.execute_reply":"2025-02-15T02:20:13.102131Z"}},"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-15T02:20:13.104884Z","iopub.execute_input":"2025-02-15T02:20:13.105152Z","iopub.status.idle":"2025-02-15T02:20:26.117497Z","shell.execute_reply.started":"2025-02-15T02:20:13.105128Z","shell.execute_reply":"2025-02-15T02:20:26.116841Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:26.118583Z","iopub.execute_input":"2025-02-15T02:20:26.118812Z","iopub.status.idle":"2025-02-15T02:20:27.109871Z","shell.execute_reply.started":"2025-02-15T02:20:26.118791Z","shell.execute_reply":"2025-02-15T02:20:27.10881Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:27.113117Z","iopub.execute_input":"2025-02-15T02:20:27.113404Z","iopub.status.idle":"2025-02-15T02:20:28.114054Z","shell.execute_reply.started":"2025-02-15T02:20:27.113379Z","shell.execute_reply":"2025-02-15T02:20:28.112265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls test1/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:28.11587Z","iopub.execute_input":"2025-02-15T02:20:28.116275Z","iopub.status.idle":"2025-02-15T02:20:29.177927Z","shell.execute_reply.started":"2025-02-15T02:20:28.116237Z","shell.execute_reply":"2025-02-15T02:20:29.176942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/ | wc -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:29.17946Z","iopub.execute_input":"2025-02-15T02:20:29.179813Z","iopub.status.idle":"2025-02-15T02:20:30.257808Z","shell.execute_reply.started":"2025-02-15T02:20:29.179782Z","shell.execute_reply":"2025-02-15T02:20:30.257002Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls train/","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:30.259027Z","iopub.execute_input":"2025-02-15T02:20:30.259266Z","iopub.status.idle":"2025-02-15T02:20:31.380217Z","shell.execute_reply.started":"2025-02-15T02:20:30.259245Z","shell.execute_reply":"2025-02-15T02:20:31.379204Z"}},"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-15T02:20:31.381692Z","iopub.execute_input":"2025-02-15T02:20:31.382512Z","iopub.status.idle":"2025-02-15T02:20:32.392402Z","shell.execute_reply.started":"2025-02-15T02:20:31.382474Z","shell.execute_reply":"2025-02-15T02:20:32.391545Z"},"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-15T02:20:32.393683Z","iopub.execute_input":"2025-02-15T02:20:32.394076Z","iopub.status.idle":"2025-02-15T02:20:33.321018Z","shell.execute_reply.started":"2025-02-15T02:20:32.394043Z","shell.execute_reply":"2025-02-15T02:20:33.3203Z"},"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-15T02:20:33.322252Z","iopub.execute_input":"2025-02-15T02:20:33.322589Z","iopub.status.idle":"2025-02-15T02:20:44.13953Z","shell.execute_reply.started":"2025-02-15T02:20:33.32254Z","shell.execute_reply":"2025-02-15T02:20:44.136561Z"}},"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-15T02:20:44.141411Z","iopub.execute_input":"2025-02-15T02:20:44.142146Z","iopub.status.idle":"2025-02-15T02:20:44.151605Z","shell.execute_reply.started":"2025-02-15T02:20:44.142106Z","shell.execute_reply":"2025-02-15T02:20:44.148308Z"},"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-15T02:20:44.155672Z","iopub.execute_input":"2025-02-15T02:20:44.156084Z","iopub.status.idle":"2025-02-15T02:20:44.173901Z","shell.execute_reply.started":"2025-02-15T02:20:44.156043Z","shell.execute_reply":"2025-02-15T02:20:44.173004Z"},"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-15T02:20:44.182869Z","iopub.execute_input":"2025-02-15T02:20:44.183273Z","iopub.status.idle":"2025-02-15T02:20:44.190922Z","shell.execute_reply.started":"2025-02-15T02:20:44.183236Z","shell.execute_reply":"2025-02-15T02:20:44.189988Z"},"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-15T02:20:44.192139Z","iopub.execute_input":"2025-02-15T02:20:44.192495Z","iopub.status.idle":"2025-02-15T02:20:45.212629Z","shell.execute_reply.started":"2025-02-15T02:20:44.192464Z","shell.execute_reply":"2025-02-15T02:20:45.211516Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:45.214388Z","iopub.execute_input":"2025-02-15T02:20:45.215167Z","iopub.status.idle":"2025-02-15T02:20:46.207583Z","shell.execute_reply.started":"2025-02-15T02:20:45.215123Z","shell.execute_reply":"2025-02-15T02:20:46.206754Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/train","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:46.208913Z","iopub.execute_input":"2025-02-15T02:20:46.209201Z","iopub.status.idle":"2025-02-15T02:20:47.225246Z","shell.execute_reply.started":"2025-02-15T02:20:46.209174Z","shell.execute_reply":"2025-02-15T02:20:47.224094Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls -l dataset_dogs_vs_cats/test","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:47.226672Z","iopub.execute_input":"2025-02-15T02:20:47.226968Z","iopub.status.idle":"2025-02-15T02:20:48.237512Z","shell.execute_reply.started":"2025-02-15T02:20:47.226944Z","shell.execute_reply":"2025-02-15T02:20:48.236404Z"}},"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-15T02:20:48.239209Z","iopub.execute_input":"2025-02-15T02:20:48.239603Z","iopub.status.idle":"2025-02-15T02:20:50.778561Z","shell.execute_reply.started":"2025-02-15T02:20:48.23955Z","shell.execute_reply":"2025-02-15T02:20:50.777861Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(src)\nprint(dst)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:20:50.779494Z","iopub.execute_input":"2025-02-15T02:20:50.780033Z","iopub.status.idle":"2025-02-15T02:20:50.784167Z","shell.execute_reply.started":"2025-02-15T02:20:50.780001Z","shell.execute_reply":"2025-02-15T02:20:50.783303Z"}},"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-15T02:20:50.785054Z","iopub.execute_input":"2025-02-15T02:20:50.785276Z","iopub.status.idle":"2025-02-15T02:20:53.930475Z","shell.execute_reply.started":"2025-02-15T02:20:50.785255Z","shell.execute_reply":"2025-02-15T02:20:53.929561Z"},"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-15T02:20:53.931787Z","iopub.execute_input":"2025-02-15T02:20:53.932063Z","iopub.status.idle":"2025-02-15T02:20:55.993497Z","shell.execute_reply.started":"2025-02-15T02:20:53.932039Z","shell.execute_reply":"2025-02-15T02:20:55.99264Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip -q install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2025-02-15T02:20:55.994779Z","iopub.execute_input":"2025-02-15T02:20:55.995048Z","iopub.status.idle":"2025-02-15T02:21:05.552931Z","shell.execute_reply.started":"2025-02-15T02:20:55.995025Z","shell.execute_reply":"2025-02-15T02:21:05.551806Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2025-02-15T02:21:05.554276Z","iopub.execute_input":"2025-02-15T02:21:05.554556Z","iopub.status.idle":"2025-02-15T02:21:05.568393Z","shell.execute_reply.started":"2025-02-15T02:21:05.554532Z","shell.execute_reply":"2025-02-15T02:21:05.567751Z"},"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-15T02:21:05.569511Z","iopub.execute_input":"2025-02-15T02:21:05.569753Z","iopub.status.idle":"2025-02-15T02:21:05.579822Z","shell.execute_reply.started":"2025-02-15T02:21:05.569733Z","shell.execute_reply":"2025-02-15T02:21:05.579124Z"}},"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-15T02:21:05.580773Z","iopub.execute_input":"2025-02-15T02:21:05.58101Z","iopub.status.idle":"2025-02-15T02:21:05.590482Z","shell.execute_reply.started":"2025-02-15T02:21:05.58099Z","shell.execute_reply":"2025-02-15T02:21:05.589718Z"}},"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-15T02:21:05.591421Z","iopub.execute_input":"2025-02-15T02:21:05.591685Z","iopub.status.idle":"2025-02-15T02:21:05.60045Z","shell.execute_reply.started":"2025-02-15T02:21:05.591665Z","shell.execute_reply":"2025-02-15T02:21:05.599706Z"}},"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.show()\n    \n    # save plot to file\n    filename = sys.argv[0].split('/')[-1]\n    pyplot.savefig(filename + '_plot.png') \n    pyplot.close()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:05.601473Z","iopub.execute_input":"2025-02-15T02:21:05.601715Z","iopub.status.idle":"2025-02-15T02:21:05.61147Z","shell.execute_reply.started":"2025-02-15T02:21:05.601695Z","shell.execute_reply":"2025-02-15T02:21:05.61088Z"}},"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-15T02:21:05.612501Z","iopub.execute_input":"2025-02-15T02:21:05.613242Z","iopub.status.idle":"2025-02-15T02:21:05.626699Z","shell.execute_reply.started":"2025-02-15T02:21:05.613204Z","shell.execute_reply":"2025-02-15T02:21:05.626049Z"}},"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-15T02:21:05.627642Z","iopub.execute_input":"2025-02-15T02:21:05.627865Z","iopub.status.idle":"2025-02-15T02:21:06.837019Z","shell.execute_reply.started":"2025-02-15T02:21:05.627837Z","shell.execute_reply":"2025-02-15T02:21:06.836241Z"}},"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-15T02:21:06.838196Z","iopub.execute_input":"2025-02-15T02:21:06.83852Z","iopub.status.idle":"2025-02-15T02:21:07.525438Z","shell.execute_reply.started":"2025-02-15T02:21:06.838487Z","shell.execute_reply":"2025-02-15T02:21:07.524748Z"}},"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-15T02:21:07.526446Z","iopub.execute_input":"2025-02-15T02:21:07.526778Z","iopub.status.idle":"2025-02-15T02:21:07.5331Z","shell.execute_reply.started":"2025-02-15T02:21:07.526747Z","shell.execute_reply":"2025-02-15T02:21:07.532355Z"}},"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-15T02:21:07.534294Z","iopub.execute_input":"2025-02-15T02:21:07.534668Z","iopub.status.idle":"2025-02-15T02:21:07.542735Z","shell.execute_reply.started":"2025-02-15T02:21:07.534636Z","shell.execute_reply":"2025-02-15T02:21:07.54204Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"stop","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:07.543707Z","iopub.execute_input":"2025-02-15T02:21:07.544014Z","iopub.status.idle":"2025-02-15T02:21:08.217268Z","shell.execute_reply.started":"2025-02-15T02:21:07.543984Z","shell.execute_reply":"2025-02-15T02:21:08.215413Z"}},"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=val_it,\n    validation_steps=len(val_it),\n    epochs=1, verbose=1,\n    callbacks = [PlotLossesKeras()]\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:50.597603Z","iopub.execute_input":"2025-02-15T02:21:50.598228Z","iopub.status.idle":"2025-02-15T02:22:38.059044Z","shell.execute_reply.started":"2025-02-15T02:21:50.598199Z","shell.execute_reply":"2025-02-15T02:22:38.058364Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# learning curves\nsummarize_diagnostics(history_1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:23:40.289515Z","iopub.execute_input":"2025-02-15T02:23:40.28989Z","iopub.status.idle":"2025-02-15T02:23:40.605159Z","shell.execute_reply.started":"2025-02-15T02:23:40.289864Z","shell.execute_reply":"2025-02-15T02:23:40.604338Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:22:38.060334Z","iopub.execute_input":"2025-02-15T02:22:38.06063Z","iopub.status.idle":"2025-02-15T02:22:48.888342Z","shell.execute_reply.started":"2025-02-15T02:22:38.060564Z","shell.execute_reply":"2025-02-15T02:22:48.887432Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ls ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.222565Z","iopub.status.idle":"2025-02-15T02:21:08.223015Z","shell.execute_reply.started":"2025-02-15T02:21:08.22279Z","shell.execute_reply":"2025-02-15T02:21:08.222814Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pwd","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.224271Z","iopub.status.idle":"2025-02-15T02:21:08.22471Z","shell.execute_reply.started":"2025-02-15T02:21:08.224479Z","shell.execute_reply":"2025-02-15T02:21:08.2245Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:24:03.950148Z","iopub.execute_input":"2025-02-15T02:24:03.950893Z","iopub.status.idle":"2025-02-15T02:24:03.990761Z","shell.execute_reply.started":"2025-02-15T02:24:03.95086Z","shell.execute_reply":"2025-02-15T02:24:03.989679Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_files[:5], type(image_files), len(image_files)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:28:00.442649Z","iopub.execute_input":"2025-02-15T02:28:00.442991Z","iopub.status.idle":"2025-02-15T02:28:00.448861Z","shell.execute_reply.started":"2025-02-15T02:28:00.442966Z","shell.execute_reply":"2025-02-15T02:28:00.448038Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:24:54.733004Z","iopub.execute_input":"2025-02-15T02:24:54.733824Z","iopub.status.idle":"2025-02-15T02:24:54.753706Z","shell.execute_reply.started":"2025-02-15T02:24:54.733794Z","shell.execute_reply":"2025-02-15T02:24:54.752874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.loc[1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:25:36.175594Z","iopub.execute_input":"2025-02-15T02:25:36.175898Z","iopub.status.idle":"2025-02-15T02:25:36.182183Z","shell.execute_reply.started":"2025-02-15T02:25:36.175875Z","shell.execute_reply":"2025-02-15T02:25:36.181361Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:25:56.758013Z","iopub.execute_input":"2025-02-15T02:25:56.758364Z","iopub.status.idle":"2025-02-15T02:25:56.768981Z","shell.execute_reply.started":"2025-02-15T02:25:56.758333Z","shell.execute_reply":"2025-02-15T02:25:56.768052Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['filename']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:28:29.59427Z","iopub.execute_input":"2025-02-15T02:28:29.594977Z","iopub.status.idle":"2025-02-15T02:28:29.601489Z","shell.execute_reply.started":"2025-02-15T02:28:29.594937Z","shell.execute_reply":"2025-02-15T02:28:29.600727Z"}},"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)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:59:52.118865Z","iopub.execute_input":"2025-02-15T02:59:52.119203Z","iopub.status.idle":"2025-02-15T02:59:53.009888Z","shell.execute_reply.started":"2025-02-15T02:59:52.119174Z","shell.execute_reply":"2025-02-15T02:59:53.009006Z"}},"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()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:00:58.353465Z","iopub.execute_input":"2025-02-15T03:00:58.353819Z","iopub.status.idle":"2025-02-15T03:00:58.359372Z","shell.execute_reply.started":"2025-02-15T03:00:58.353788Z","shell.execute_reply":"2025-02-15T03:00:58.358499Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images, train_labels = train_it.__next__()\ntrain_images.shape\nplot_exmaple(train_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:02:30.027Z","iopub.execute_input":"2025-02-15T03:02:30.027809Z","iopub.status.idle":"2025-02-15T03:02:34.439784Z","shell.execute_reply.started":"2025-02-15T03:02:30.027778Z","shell.execute_reply":"2025-02-15T03:02:34.437678Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_images = test_it.__next__()\ntest_images.shape\nplot_exmaple(test_images)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:01:08.731993Z","iopub.execute_input":"2025-02-15T03:01:08.732823Z","iopub.status.idle":"2025-02-15T03:01:12.775221Z","shell.execute_reply.started":"2025-02-15T03:01:08.732794Z","shell.execute_reply":"2025-02-15T03:01:12.773779Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Create transfer learning model for VGG16\nimport sys\nfrom matplotlib import pyplot\nfrom keras.utils import to_categorical\nfrom keras.applications.vgg16 import VGG16\nfrom keras.models import Model\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nfrom keras.optimizers import SGD\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# define cnn model\ndef define_model_vgg16():\n\t# load model\n\tmodel = VGG16(include_top=False, input_shape=(224, 224, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(128, activation='relu', kernel_initializer='he_uniform')(flat1)\n\toutput = Dense(1, activation='sigmoid')(class1)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:35:36.87919Z","iopub.execute_input":"2025-02-15T02:35:36.880328Z","iopub.status.idle":"2025-02-15T02:35:36.886794Z","shell.execute_reply.started":"2025-02-15T02:35:36.880292Z","shell.execute_reply":"2025-02-15T02:35:36.885749Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vgg16_model = define_model_vgg16()\nvgg16_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:37:12.096346Z","iopub.execute_input":"2025-02-15T02:37:12.096657Z","iopub.status.idle":"2025-02-15T02:37:12.456504Z","shell.execute_reply.started":"2025-02-15T02:37:12.096632Z","shell.execute_reply":"2025-02-15T02:37:12.455502Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from keras.applications.inception_v3 import InceptionV3\n\ndef define_model_inceptionv3():\n\t# load model\n\tmodel = InceptionV3(include_top=False, input_shape=(299, 299, 3))\n\t# mark loaded layers as not trainable\n\tfor layer in model.layers:\n\t\tlayer.trainable = False\n\n\t# add new classifier layers\n\tflat1 = Flatten()(model.layers[-1].output)\n\tclass1 = Dense(1024, activation='relu', kernel_initializer='he_uniform')(flat1)\n\tclass2 = Dense(512, activation='relu', kernel_initializer='he_uniform')(class1)\n\tclass3 = Dense(256, activation='relu', kernel_initializer='he_uniform')(class2)\n\tclass4 = Dense(128, activation='relu', kernel_initializer='he_uniform')(class3)\n\toutput = Dense(1, activation='sigmoid')(class4)\n\t# output = Dense(2, activation='softmax')(class4)\n\t# define new model\n\tmodel = Model(inputs=model.inputs, outputs=output)\n\t# compile model\n\topt = SGD(lr=0.001, momentum=0.9)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:52:49.712662Z","iopub.execute_input":"2025-02-15T02:52:49.712982Z","iopub.status.idle":"2025-02-15T02:52:49.719201Z","shell.execute_reply.started":"2025-02-15T02:52:49.712958Z","shell.execute_reply":"2025-02-15T02:52:49.718384Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3 = define_model_inceptionv3()","metadata":{"execution":{"iopub.status.busy":"2025-02-15T02:53:29.014374Z","iopub.execute_input":"2025-02-15T02:53:29.014725Z","iopub.status.idle":"2025-02-15T02:53:31.092566Z","shell.execute_reply.started":"2025-02-15T02:53:29.014696Z","shell.execute_reply":"2025-02-15T02:53:31.091917Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_inceptionv3.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:53:32.907981Z","iopub.execute_input":"2025-02-15T02:53:32.908289Z","iopub.status.idle":"2025-02-15T02:53:33.581004Z","shell.execute_reply.started":"2025-02-15T02:53:32.908266Z","shell.execute_reply":"2025-02-15T02:53:33.580108Z"},"scrolled":true},"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()]\n    )","metadata":{"execution":{"iopub.status.busy":"2025-02-15T03:04:48.058696Z","iopub.execute_input":"2025-02-15T03:04:48.059391Z","iopub.status.idle":"2025-02-15T03:10:48.247155Z","shell.execute_reply.started":"2025-02-15T03:04:48.059356Z","shell.execute_reply":"2025-02-15T03:10:48.246287Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.237369Z","iopub.status.idle":"2025-02-15T02:21:08.237658Z","shell.execute_reply.started":"2025-02-15T02:21:08.2375Z","shell.execute_reply":"2025-02-15T02:21:08.237513Z"}},"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,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.241256Z","iopub.status.idle":"2025-02-15T02:21:08.241562Z","shell.execute_reply.started":"2025-02-15T02:21:08.241404Z","shell.execute_reply":"2025-02-15T02:21:08.241419Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot_images_with_labels(images, labels, \"Dog-Cat\", \"Training\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.24281Z","iopub.status.idle":"2025-02-15T02:21:08.243096Z","shell.execute_reply.started":"2025-02-15T02:21:08.242961Z","shell.execute_reply":"2025-02-15T02:21:08.242975Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# for index, layer in enumerate(model.layers):\n#     print(index, layer.output.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T02:21:08.245764Z","iopub.status.idle":"2025-02-15T02:21:08.246347Z","shell.execute_reply.started":"2025-02-15T02:21:08.246115Z","shell.execute_reply":"2025-02-15T02:21:08.246138Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # mark loaded layers as not trainable\n# for index, layer in enumerate(model.layers[:15]):\n#     print(index, layer.name, layer.output_shape)\n#     layer.trainable = False\n    \n# for 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-15T02:21:08.247522Z","iopub.status.idle":"2025-02-15T02:21:08.24804Z","shell.execute_reply.started":"2025-02-15T02:21:08.247789Z","shell.execute_reply":"2025-02-15T02:21:08.247813Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# evaluate model\n_, acc = model_inceptionv3.evaluate(test_it, steps=len(test_it), verbose=1)\nprint('> %.3f' % (acc * 100.0))\n# learning curves\n# summarize_diagnostics(history)\n\n# best_model = 'vgg16_model.hdf5'\n# my_model.save(best_model)","metadata":{"execution":{"iopub.status.busy":"2025-02-15T03:13:12.893504Z","iopub.execute_input":"2025-02-15T03:13:12.894343Z","iopub.status.idle":"2025-02-15T03:14:03.106054Z","shell.execute_reply.started":"2025-02-15T03:13:12.894313Z","shell.execute_reply":"2025-02-15T03:14:03.105043Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"images = test_it.__next__()\nimages.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:15:28.072696Z","iopub.execute_input":"2025-02-15T03:15:28.073007Z","iopub.status.idle":"2025-02-15T03:15:28.245543Z","shell.execute_reply.started":"2025-02-15T03:15:28.072983Z","shell.execute_reply":"2025-02-15T03:15:28.244701Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 5 first img: 1, 0, 1, 1, 0\nimages_to_predict = images[:5]\nimages_to_predict.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:17:20.026444Z","iopub.execute_input":"2025-02-15T03:17:20.027123Z","iopub.status.idle":"2025-02-15T03:17:20.032436Z","shell.execute_reply.started":"2025-02-15T03:17:20.02709Z","shell.execute_reply":"2025-02-15T03:17:20.031562Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"probs = model_inceptionv3.predict(images_to_predict, verbose=1)\nprobs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-15T03:18:24.110311Z","iopub.execute_input":"2025-02-15T03:18:24.111313Z","iopub.status.idle":"2025-02-15T03:18:26.745483Z","shell.execute_reply.started":"2025-02-15T03:18:24.111261Z","shell.execute_reply":"2025-02-15T03:18:26.744749Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Make Prediction","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}