{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Importing Libraries","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import zipfile\nimport random\nimport tensorflow as tf\nfrom tensorflow import keras\nimport keras_preprocessing\nfrom keras_preprocessing import image\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom shutil import copyfile\nfrom tensorflow.keras.regularizers import l2\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Extracting training set into a directory named 'training'.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('training')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Checking whether the zip files were extracted or not.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"print(len(os.listdir('/kaggle/working/training/train')))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Make different directories for training and testing (cats and dogs).**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = '/kaggle/working'\ntrain_dir = os.makedirs(os.path.join(base_dir, 'train'))\nvalidation_dir = os.makedirs(os.path.join(base_dir, 'validation'))\n\n# Directory with our training cat pictures\ntrain_cats_dir = os.makedirs('/kaggle/working/train/cats')\n\n# Directory with our training dog pictures\ntrain_dogs_dir = os.makedirs('/kaggle/working/train/dogs')\n\n# Directory with our validation cat pictures\nvalidation_cats_dir = os.makedirs('/kaggle/working/validation/cats')\n\n# Directory with our validation dog pictures\nvalidation_dogs_dir = os.makedirs('/kaggle/working/validation/dogs')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Appending files into the training directory and then dividing them into training and validation sets.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"list_images = os.listdir(\"/kaggle/working/training/train/\")\nprint(len(list_images))\nfiles = []\nfor file_name in list_images:\n    if(os.path.getsize(\"/kaggle/working/training/train/\" + file_name)) > 0:\n        files.append(file_name)\n    else:\n        print(file_name + \"has zero length!\")\n        \nfiles = random.sample(files, len(files))\ntrain_set = files[0 : round(0.8*len(files))]\nval_set = files[-(len(files) - len(train_set)) : ]\nprint(\"Train-set size:\", len(train_set))\nprint(\"Validation-set size:\", len(val_set))\n\n\nfor file_name in train_set:\n    if('cat' in file_name):        \n        copyfile(\"/kaggle/working/training/train/\" + file_name, \"/kaggle/working/train/cats/\" + file_name)\n    elif('dog' in file_name):\n        copyfile(\"/kaggle/working/training/train/\" + file_name, \"/kaggle/working/train/dogs/\" + file_name)\n        \nfor file_name in val_set:\n    if('cat' in file_name):        \n        copyfile(\"/kaggle/working/training/train/\" + file_name, \"/kaggle/working/validation/cats/\" + file_name)\n    elif('dog' in file_name):\n        copyfile(\"/kaggle/working/training/train/\" + file_name, \"/kaggle/working/validation/dogs/\" + file_name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"No. of cats in train set \", len(os.listdir(\"/kaggle/working/train/cats/\")))\nprint(\"No. of dogs in train set \", len(os.listdir(\"/kaggle/working/train/dogs/\")))\nprint(\"No. of cats in validation set \", len(os.listdir(\"/kaggle/working/validation/cats/\")))\nprint(\"No. of dogs in validation set \", len(os.listdir(\"/kaggle/working/validation/dogs/\")))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preparing training and validation data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"training_dir = \"/kaggle/working/train/\"\ntrain_datagen = ImageDataGenerator(\n                rescale=1./255,\n                shear_range=0.1,\n                zoom_range=0.1,\n                horizontal_flip=True)\n\ntrain_generator = train_datagen.flow_from_directory(\n                  training_dir,\n                  batch_size=32,\n                  class_mode='binary',\n                  target_size=(200, 200))\n\nvalidation_dir =  \"/kaggle/working/validation/\"\nvalidation_datagen = ImageDataGenerator(rescale=1./255)\n\nvalidation_generator = validation_datagen.flow_from_directory(\n                       validation_dir,\n                       batch_size=32,\n                       class_mode='binary',\n                       target_size=(200, 200))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**Here, we have built a Sequential model with 5 convolution layers with the image size 200X200 and a Dense layer with 1024 neurons. We have also specified callbacks based on validation accuracy(patience means process will come to a halt after the no. of epochs for which val_acc doesn't improve).**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# EarlyStopping and Reduce Learning Rate Callbacks\nmy_callback_es = tf.keras.callbacks.EarlyStopping(monitor='val_acc', patience=5)\nmy_callback_rlr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_acc', patience=2, factor=0.5, min_lr=0.00001, verbose=1)\n\nmodel = tf.keras.models.Sequential([\n    #Conv layer 1\n    tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(200, 200, 3)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPool2D(2, 2),\n    #Conv layer 2\n    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPool2D(2, 2),\n    #Conv layer 3\n    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPool2D(2, 2),\n    #Conv layer 4\n    tf.keras.layers.Conv2D(256, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPool2D(2, 2),\n    #Conv layer 5\n    tf.keras.layers.Conv2D(256, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPool2D(2, 2),\n    #Flatten\n    tf.keras.layers.Flatten(),\n    #Fully Connected layer\n    tf.keras.layers.Dense(1024, activation='relu', kernel_regularizer=l2(0.001)),\n    tf.keras.layers.BatchNormalization(),\n    #Dropout\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(1, activation='sigmoid', kernel_regularizer=l2(0.001))\n    \n])\nmodel.summary()\nmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])\n\nhistory = model.fit_generator(\n    train_generator, \n    steps_per_epoch = len(train_set) // 32,\n    epochs = 100,\n    verbose = 1,\n    validation_data = validation_generator,\n    validation_steps = len(val_set) // 32,\n    callbacks=[my_callback_es, my_callback_rlr])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualizing Accuracy and Loss","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\n\nplt.figure()\n\nplt.plot(epochs, loss, 'r', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.ylim(top=1.0)\nplt.title('Training and validation loss')\nplt.legend(loc=0)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Saving model for later use.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save_weights('Dense1024_Dropout_model_wieghts.h5')\nmodel.save('Dense1024_Dropout_model_keras.h5')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Extracting test file into 'testing' directory.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"local_zip = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('testing')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images = os.listdir('/kaggle/working/testing/test')\nprint(len(test_images))\n\nprint(test_images[0:5])\n\nID = [int(test_img[:-4]) for test_img in test_images]\nprint(ID[0:5])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preparing Test data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dir = \"/kaggle/working/testing/\"\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_datagen.flow_from_directory(\n                 test_dir,\n                 target_size=(200, 200),\n                 batch_size=32,\n                 class_mode='binary',\n                 shuffle=False)\n\ntest_generator.reset()\npredictions = model.predict_generator(test_generator, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Flatten the prections for submission.**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = predictions.flatten()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame({\"id\": ID, \"label\": predictions})\nsubmission.to_csv(\"dogs_cats.csv\", index = False)\nsubmission.head()","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}