{"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":"gpu","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":"2024-01-26T12:12:36.153710Z","iopub.execute_input":"2024-01-26T12:12:36.154660Z","iopub.status.idle":"2024-01-26T12:12:36.538268Z","shell.execute_reply.started":"2024-01-26T12:12:36.154621Z","shell.execute_reply":"2024-01-26T12:12:36.537216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-01-26T12:12:36.540411Z","iopub.execute_input":"2024-01-26T12:12:36.540961Z","iopub.status.idle":"2024-01-26T12:12:52.734294Z","shell.execute_reply.started":"2024-01-26T12:12:36.540924Z","shell.execute_reply":"2024-01-26T12:12:52.733349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:12:52.735695Z","iopub.execute_input":"2024-01-26T12:12:52.736027Z","iopub.status.idle":"2024-01-26T12:12:53.679105Z","shell.execute_reply.started":"2024-01-26T12:12:52.736000Z","shell.execute_reply":"2024-01-26T12:12:53.677933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/dogs | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:12:53.682363Z","iopub.execute_input":"2024-01-26T12:12:53.682701Z","iopub.status.idle":"2024-01-26T12:12:54.710163Z","shell.execute_reply.started":"2024-01-26T12:12:53.682671Z","shell.execute_reply":"2024-01-26T12:12:54.709091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -l dataset_dogs_vs_cats/train/cats | wc -l","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:12:54.711547Z","iopub.execute_input":"2024-01-26T12:12:54.711837Z","iopub.status.idle":"2024-01-26T12:12:55.729673Z","shell.execute_reply.started":"2024-01-26T12:12:54.711812Z","shell.execute_reply":"2024-01-26T12:12:55.728500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot dog photos from the dogs vs cats dataset\nfrom matplotlib import pyplot\nfrom matplotlib.image import imread\ntrain_folder = '/kaggle/working/train/'\n\n# define location of dataset\nfolder = train_folder\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":"2024-01-26T12:12:55.731162Z","iopub.execute_input":"2024-01-26T12:12:55.731503Z","iopub.status.idle":"2024-01-26T12:12:56.938120Z","shell.execute_reply.started":"2024-01-26T12:12:55.731468Z","shell.execute_reply":"2024-01-26T12:12:56.936982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-01-26T12:12:56.939423Z","iopub.execute_input":"2024-01-26T12:12:56.939709Z","iopub.status.idle":"2024-01-26T12:12:58.161871Z","shell.execute_reply.started":"2024-01-26T12:12:56.939684Z","shell.execute_reply":"2024-01-26T12:12:58.160761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\n# 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-26T12:12:58.163571Z","iopub.execute_input":"2024-01-26T12:12:58.163858Z","iopub.status.idle":"2024-01-26T12:14:25.446114Z","shell.execute_reply.started":"2024-01-26T12:12:58.163832Z","shell.execute_reply":"2024-01-26T12:14:25.444966Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load and confirm the shape\nfrom numpy import load\nphotos = load('dogs_vs_cats_photos.npy')\nlabels = load('dogs_vs_cats_labels.npy')\nprint(photos.shape, labels.shape)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:14:25.447759Z","iopub.execute_input":"2024-01-26T12:14:25.448441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-01-26T12:15:10.169322Z","iopub.execute_input":"2024-01-26T12:15:10.169718Z","iopub.status.idle":"2024-01-26T12:15:10.198690Z","shell.execute_reply.started":"2024-01-26T12:15:10.169684Z","shell.execute_reply":"2024-01-26T12:15:10.197831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-01-26T12:15:10.200327Z","iopub.execute_input":"2024-01-26T12:15:10.200656Z","iopub.status.idle":"2024-01-26T12:15:10.207737Z","shell.execute_reply.started":"2024-01-26T12:15:10.200628Z","shell.execute_reply":"2024-01-26T12:15:10.206653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2024-01-26T12:15:10.208849Z","iopub.execute_input":"2024-01-26T12:15:10.209097Z","iopub.status.idle":"2024-01-26T12:15:26.833828Z","shell.execute_reply.started":"2024-01-26T12:15:10.209075Z","shell.execute_reply":"2024-01-26T12:15:26.832900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install livelossplot==0.5.5","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:26.836089Z","iopub.execute_input":"2024-01-26T12:15:26.836394Z","iopub.status.idle":"2024-01-26T12:15:39.826011Z","shell.execute_reply.started":"2024-01-26T12:15:26.836367Z","shell.execute_reply":"2024-01-26T12:15:39.824798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import 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.layers import Dropout\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom livelossplot import PlotLossesKeras","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:39.827506Z","iopub.execute_input":"2024-01-26T12:15:39.827846Z","iopub.status.idle":"2024-01-26T12:15:48.247519Z","shell.execute_reply.started":"2024-01-26T12:15:39.827815Z","shell.execute_reply":"2024-01-26T12:15:48.246699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# define cnn model\ndef define_model():\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(Conv2D(64, (3, 3), activation='relu', kernel_initializer='he_uniform', padding='same', input_shape=(200, 200, 3)))\n\tmodel.add(MaxPooling2D((2, 2)))\n\tmodel.add(Conv2D(128, (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(Dropout(0.4))\n\tmodel.add(Dense(1, activation='sigmoid'))\n\t# compile model\n\topt = Adam(lr=0.001)\n\tmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\treturn model","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:48.248742Z","iopub.execute_input":"2024-01-26T12:15:48.249448Z","iopub.status.idle":"2024-01-26T12:15:48.258329Z","shell.execute_reply.started":"2024-01-26T12:15:48.249409Z","shell.execute_reply":"2024-01-26T12:15:48.257449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = define_model()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:48.259684Z","iopub.execute_input":"2024-01-26T12:15:48.260027Z","iopub.status.idle":"2024-01-26T12:15:49.337150Z","shell.execute_reply.started":"2024-01-26T12:15:48.259995Z","shell.execute_reply":"2024-01-26T12:15:49.336380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:49.338321Z","iopub.execute_input":"2024-01-26T12:15:49.338617Z","iopub.status.idle":"2024-01-26T12:15:49.343283Z","shell.execute_reply.started":"2024-01-26T12:15:49.338590Z","shell.execute_reply":"2024-01-26T12:15:49.342296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create data generator\ndatagen = ImageDataGenerator(rescale=1.0/255.0)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:49.344448Z","iopub.execute_input":"2024-01-26T12:15:49.344707Z","iopub.status.idle":"2024-01-26T12:15:49.355258Z","shell.execute_reply.started":"2024-01-26T12:15:49.344684Z","shell.execute_reply":"2024-01-26T12:15:49.354368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare iterators\ntrain_it = datagen.flow_from_directory('dataset_dogs_vs_cats/train/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))\ntest_it = datagen.flow_from_directory('dataset_dogs_vs_cats/test/',\n\tclass_mode='binary', batch_size=64, target_size=(200, 200))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:49.358014Z","iopub.execute_input":"2024-01-26T12:15:49.358288Z","iopub.status.idle":"2024-01-26T12:15:50.392483Z","shell.execute_reply.started":"2024-01-26T12:15:49.358264Z","shell.execute_reply":"2024-01-26T12:15:50.391516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit model\nhistory = model.fit(train_it, steps_per_epoch=len(train_it),\n                    validation_data=test_it, validation_steps=len(test_it),\n                    epochs=30,callbacks=[PlotLossesKeras()], verbose=0)","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:15:50.393774Z","iopub.execute_input":"2024-01-26T12:15:50.394128Z","iopub.status.idle":"2024-01-26T12:38:30.915001Z","shell.execute_reply.started":"2024-01-26T12:15:50.394098Z","shell.execute_reply":"2024-01-26T12:38:30.913910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate model\n_, acc = model.evaluate(test_it, steps=len(test_it), verbose=0)\nprint('> %.3f' % (acc * 100.0))","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:38:30.916520Z","iopub.execute_input":"2024-01-26T12:38:30.916887Z","iopub.status.idle":"2024-01-26T12:38:41.955027Z","shell.execute_reply.started":"2024-01-26T12:38:30.916857Z","shell.execute_reply":"2024-01-26T12:38:41.953971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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\tpyplot.close()","metadata":{"execution":{"iopub.status.busy":"2024-01-26T12:38:41.956489Z","iopub.execute_input":"2024-01-26T12:38:41.956849Z","iopub.status.idle":"2024-01-26T12:38:41.964827Z","shell.execute_reply.started":"2024-01-26T12:38:41.956820Z","shell.execute_reply":"2024-01-26T12:38:41.963736Z"},"trusted":true},"execution_count":null,"outputs":[]}]}