{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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\nimport zipfile\nimport shutil\n\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":"2023-05-03T03:32:22.750159Z","iopub.execute_input":"2023-05-03T03:32:22.750510Z","iopub.status.idle":"2023-05-03T03:32:22.757779Z","shell.execute_reply.started":"2023-05-03T03:32:22.750483Z","shell.execute_reply":"2023-05-03T03:32:22.756768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"zip_ref = zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r')\nzip_ref.extractall('/kaggle/working')\nzip_ref.close()","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:34:27.310069Z","iopub.execute_input":"2023-05-03T03:34:27.310499Z","iopub.status.idle":"2023-05-03T03:34:38.224462Z","shell.execute_reply.started":"2023-05-03T03:34:27.310471Z","shell.execute_reply":"2023-05-03T03:34:38.222155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_dir = '/kaggle/working'\ntrain_dir = os.path.join(base_dir, 'train')\nvalidation_dir = os.path.join(base_dir, 'validation')\n\nos.mkdir(validation_dir)\n\n# Directory with our training cat pictures\ntrain_cats_dir = os.path.join(train_dir, 'cats')\nos.mkdir(train_cats_dir)\n\n# Directory with our training dog pictures\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\nos.mkdir(train_dogs_dir)\n\n# Directory with our validation cat pictures\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nos.mkdir(validation_cats_dir)\n\n# Directory with our validation dog pictures\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\nos.mkdir(validation_dogs_dir)\n\nprint(len(os.listdir(validation_dir)))","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:34:57.505869Z","iopub.execute_input":"2023-05-03T03:34:57.506195Z","iopub.status.idle":"2023-05-03T03:34:57.517762Z","shell.execute_reply.started":"2023-05-03T03:34:57.506169Z","shell.execute_reply":"2023-05-03T03:34:57.516191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Move dogs and cats images in separate folder.\nfiles = os.listdir(train_dir)\n\n# Split the original training set into a reduced training set and a\n# validation set. \nvalidation_split = 0.2\ntrain_split = 0.8\n\nindex = 0\nlength_train_dir = len(files) # length of the train dir\n\nprint(length_train_dir)","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:35:06.750208Z","iopub.execute_input":"2023-05-03T03:35:06.750581Z","iopub.status.idle":"2023-05-03T03:35:06.771553Z","shell.execute_reply.started":"2023-05-03T03:35:06.750553Z","shell.execute_reply":"2023-05-03T03:35:06.770680Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Too slow training . I limited the size ot the data set for conveniance !!","metadata":{}},{"cell_type":"code","source":"while index < length_train_dir :\n    filename = files[index]\n    if 'cat' in filename and filename.endswith(\"jpg\") and (len(os.listdir(train_cats_dir)) < 1000):\n        src = os.path.join(train_dir, filename)\n        dst = os.path.join(train_cats_dir, filename)\n        shutil.move(src, dst)\n    elif 'dog' in filename and filename.endswith(\"jpg\") and (len(os.listdir(train_dogs_dir)) < 1000):\n        src = os.path.join(train_dir, filename)\n        dst = os.path.join(train_dogs_dir, filename)\n        shutil.move(src, dst)\n    elif 'cat' in filename and filename.endswith(\"jpg\") and (len(os.listdir(validation_cats_dir)) < 500):\n        src = os.path.join(train_dir, filename)\n        dst = os.path.join(validation_cats_dir, filename)\n        shutil.move(src, dst)\n    elif 'dog' in filename and filename.endswith(\"jpg\") and (len(os.listdir(validation_dogs_dir)) <500):\n        src = os.path.join(train_dir, filename)\n        dst = os.path.join(validation_dogs_dir, filename)\n        shutil.move(src, dst)\n    index += 1","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:38:52.981714Z","iopub.execute_input":"2023-05-03T03:38:52.982269Z","iopub.status.idle":"2023-05-03T03:39:07.999286Z","shell.execute_reply.started":"2023-05-03T03:38:52.982214Z","shell.execute_reply":"2023-05-03T03:39:07.998353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_cat_fnames = os.listdir(train_cats_dir)\nprint(train_cat_fnames[:10])\n\ntrain_dog_fnames = os.listdir(train_dogs_dir)\ntrain_dog_fnames.sort()\nprint(train_dog_fnames[:10])","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:43:08.456700Z","iopub.execute_input":"2023-05-03T03:43:08.457037Z","iopub.status.idle":"2023-05-03T03:43:08.464187Z","shell.execute_reply.started":"2023-05-03T03:43:08.457010Z","shell.execute_reply":"2023-05-03T03:43:08.463289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('total training cat images:', len(os.listdir(train_cats_dir)))\nprint('total training dog images:', len(os.listdir(train_dogs_dir)))\nprint('total validation cat images:', len(os.listdir(validation_cats_dir)))\nprint('total validation dog images:', len(os.listdir(validation_dogs_dir)))","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:43:10.837605Z","iopub.execute_input":"2023-05-03T03:43:10.837939Z","iopub.status.idle":"2023-05-03T03:43:10.847659Z","shell.execute_reply.started":"2023-05-03T03:43:10.837911Z","shell.execute_reply":"2023-05-03T03:43:10.846696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":" For both cats and dogs, i limited the size for  2000 training images and 1000 test images.","metadata":{}},{"cell_type":"markdown","source":"## Data Augmentation","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ndatagen = ImageDataGenerator(\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')","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:43:35.316454Z","iopub.execute_input":"2023-05-03T03:43:35.317527Z","iopub.status.idle":"2023-05-03T03:43:41.767906Z","shell.execute_reply.started":"2023-05-03T03:43:35.317487Z","shell.execute_reply":"2023-05-03T03:43:41.767006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Adding rescale, rotation_range, width_shift_range, height_shift_range,\n# shear_range, zoom_range, and horizontal flip to our ImageDataGenerator\ntrain_datagen = 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\n# Note that the validation data should not be augmented!\nval_datagen = ImageDataGenerator(rescale=1./255)\n\n# Flow training images in batches of 32 using train_datagen generator\ntrain_generator = train_datagen.flow_from_directory(\n        train_dir,  # This is the source directory for training images\n        target_size=(150, 150),  # All images will be resized to 150x150\n        batch_size=20,\n        # Since we use binary_crossentropy loss, we need binary labels\n        class_mode='binary')\n\n# Flow validation images in batches of 32 using val_datagen generator\nvalidation_generator = val_datagen.flow_from_directory(\n        validation_dir,\n        target_size=(150, 150),\n        batch_size=20,\n        class_mode='binary')","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:43:44.754895Z","iopub.execute_input":"2023-05-03T03:43:44.755564Z","iopub.status.idle":"2023-05-03T03:43:44.953075Z","shell.execute_reply.started":"2023-05-03T03:43:44.755531Z","shell.execute_reply":"2023-05-03T03:43:44.952273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Adding Dropout","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import layers\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.optimizers import RMSprop","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:43:58.535968Z","iopub.execute_input":"2023-05-03T03:43:58.536341Z","iopub.status.idle":"2023-05-03T03:43:58.541671Z","shell.execute_reply.started":"2023-05-03T03:43:58.536312Z","shell.execute_reply":"2023-05-03T03:43:58.540533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Our input feature map is 150x150x3: 150x150 for the image pixels, and 3 for\n# the three color channels: R, G, and B\nimg_input = layers.Input(shape=(150, 150, 3))\n\n# First convolution extracts 16 filters that are 3x3\n# Convolution is followed by max-pooling layer with a 2x2 window\nx = layers.Conv2D(16, 3, activation='relu')(img_input)\nx = layers.MaxPooling2D(2)(x)\n\n# Second convolution extracts 32 filters that are 3x3\n# Convolution is followed by max-pooling layer with a 2x2 window\nx = layers.Conv2D(32, 3, activation='relu')(x)\nx = layers.MaxPooling2D(2)(x)\n\n# Third convolution extracts 64 filters that are 3x3\n# Convolution is followed by max-pooling layer with a 2x2 window\nx = layers.Convolution2D(64, 3, activation='relu')(x)\nx = layers.MaxPooling2D(2)(x)\n\n# Flatten feature map to a 1-dim tensor\nx = layers.Flatten()(x)\n\n# Create a fully connected layer with ReLU activation and 512 hidden units\nx = layers.Dense(512, activation='relu')(x)\n\n# Add a dropout rate of 0.5\nx = layers.Dropout(0.5)(x)\n\n# Create output layer with a single node and sigmoid activation\noutput = layers.Dense(1, activation='sigmoid')(x)\n\n# Configure and compile the model\nmodel = Model(img_input, output)\nmodel.compile(loss='binary_crossentropy',\n              optimizer=RMSprop(lr=0.001),\n              metrics=['acc'])","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:44:06.836679Z","iopub.execute_input":"2023-05-03T03:44:06.837012Z","iopub.status.idle":"2023-05-03T03:44:09.474283Z","shell.execute_reply.started":"2023-05-03T03:44:06.836985Z","shell.execute_reply":"2023-05-03T03:44:09.473428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training","metadata":{}},{"cell_type":"code","source":"history = model.fit_generator(\n      train_generator,\n      steps_per_epoch=100,\n      epochs=50,\n      validation_data=validation_generator,\n      validation_steps=50,\n      verbose=2)","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:44:24.851114Z","iopub.execute_input":"2023-05-03T03:44:24.851669Z","iopub.status.idle":"2023-05-03T03:55:42.566266Z","shell.execute_reply.started":"2023-05-03T03:44:24.851638Z","shell.execute_reply":"2023-05-03T03:55:42.565271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training and  Accuracy  visualisation for cnn","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:57:22.018868Z","iopub.execute_input":"2023-05-03T03:57:22.019289Z","iopub.status.idle":"2023-05-03T03:57:22.023244Z","shell.execute_reply.started":"2023-05-03T03:57:22.019220Z","shell.execute_reply":"2023-05-03T03:57:22.022338Z"}}},{"cell_type":"code","source":"%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Retrieve a list of accuracy results on training and validation data\n# sets for each training epoch\nacc = history.history['acc']\nval_acc = history.history['val_acc']\n\n# Retrieve a list of list results on training and validation data\n# sets for each training epoch\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\n# Get number of epochs\nepochs = range(len(acc))\n\n# Plot training and validation accuracy per epoch\nplt.plot(epochs, acc,label=\"Training accuracy\")\nplt.plot(epochs, val_acc,label=\"validation accuracy\")\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\n# Plot training and validation loss per epoch\nplt.plot(epochs, loss,label=\"Training loss\")\nplt.plot(epochs, val_loss,label=\"validation loss\")\nplt.legend()\nplt.title('Training and validation loss')","metadata":{"execution":{"iopub.status.busy":"2023-05-03T03:57:33.556629Z","iopub.execute_input":"2023-05-03T03:57:33.557146Z","iopub.status.idle":"2023-05-03T03:57:34.083863Z","shell.execute_reply.started":"2023-05-03T03:57:33.557103Z","shell.execute_reply":"2023-05-03T03:57:34.082983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import Sequential, save_model, load_model\nsave_model(model, 'dog_vs_cat_cnn_model.h5')","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:15:00.715708Z","iopub.execute_input":"2023-05-03T04:15:00.716053Z","iopub.status.idle":"2023-05-03T04:15:00.915914Z","shell.execute_reply.started":"2023-05-03T04:15:00.716026Z","shell.execute_reply":"2023-05-03T04:15:00.914943Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### FCN","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Flatten\nfrom keras.optimizers import SGD","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:15:43.697853Z","iopub.execute_input":"2023-05-03T04:15:43.698249Z","iopub.status.idle":"2023-05-03T04:15:43.702634Z","shell.execute_reply.started":"2023-05-03T04:15:43.698201Z","shell.execute_reply":"2023-05-03T04:15:43.701681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Flatten(input_shape=(150, 150, 3)))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:15:44.744009Z","iopub.execute_input":"2023-05-03T04:15:44.744368Z","iopub.status.idle":"2023-05-03T04:15:44.797405Z","shell.execute_reply.started":"2023-05-03T04:15:44.744339Z","shell.execute_reply":"2023-05-03T04:15:44.796469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=SGD(lr=0.001),\n              loss='binary_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:15:51.046856Z","iopub.execute_input":"2023-05-03T04:15:51.047187Z","iopub.status.idle":"2023-05-03T04:15:51.061165Z","shell.execute_reply.started":"2023-05-03T04:15:51.047160Z","shell.execute_reply":"2023-05-03T04:15:51.059280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history2 = model.fit(train_generator,\n          steps_per_epoch=100,\n          epochs=50,\n          validation_data=validation_generator,\n          validation_steps=50)","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:23:56.649649Z","iopub.execute_input":"2023-05-03T04:23:56.649975Z","iopub.status.idle":"2023-05-03T04:35:27.322422Z","shell.execute_reply.started":"2023-05-03T04:23:56.649948Z","shell.execute_reply":"2023-05-03T04:35:27.321475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Retrieve a list of accuracy results on training and validation data\n# sets for each training epoch\nacc2 = history2.history['accuracy']\nval_acc2 = history2.history['val_accuracy']\n\n# Retrieve a list of list results on training and validation data\n# sets for each training epoch\nloss2 = history2.history['loss']\nval_loss2 = history2.history['val_loss']\n\n# Get number of epochs\nepochs2 = range(len(acc2))\n\n# Plot training and validation accuracy per epoch\nplt.plot(epochs2, acc2,label=\"Training accuracy\")\nplt.plot(epochs2, val_acc2,label=\"validation accuracy\")\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure()\n\n# Plot training and validation loss per epoch\nplt.plot(epochs2, loss2,label=\"Training loss\")\nplt.plot(epochs2, val_loss2,label=\"validation loss\")\nplt.legend()\nplt.title('Training and validation loss')","metadata":{"execution":{"iopub.status.busy":"2023-05-03T04:35:41.208596Z","iopub.execute_input":"2023-05-03T04:35:41.208960Z","iopub.status.idle":"2023-05-03T04:35:41.798420Z","shell.execute_reply.started":"2023-05-03T04:35:41.208929Z","shell.execute_reply":"2023-05-03T04:35:41.797602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"The graph thell us that **convolution neural network** do a better job than **full neural network** for  the image classification in the same condition","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}