{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 1. Importing necessary packages"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport random\n\nimport matplotlib.pyplot as plt\n\nimport os\nimport zipfile\n\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extracting the zip file\n\nlocal_zip = '/kaggle/input/dogs-vs-cats/train.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = '/tmp/train'\nimg_names = os.listdir(os.path.join(base_dir))\nimg_names[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample = random.choice(img_names)\nimage = load_img(\"/tmp/train/\"+sample)\nplt.imshow(image)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preparing the traning data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let's assign the label Dog and Cat for the images\n\nlabel = []\n\nfor i in img_names:\n    if(i.split(\".\")[0] == \"dog\"):\n        label.append(\"Dog\")\n    else:\n        label.append(\"Cat\")\n\nlabel[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.DataFrame({\"Image\" : img_names, \"Label\" : label})\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.Label.value_counts().plot.bar(color = ['red','blue'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Thus, this is a balanced dataset with equal no.of dogs and cats images"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, validate_df = train_test_split(df, test_size = 0.2)\ntrain_df = train_df.reset_index(drop = True)\nvalidate_df = validate_df.reset_index(drop = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building the model"},{"metadata":{},"cell_type":"markdown","source":"* **Conv Layer**: This layer will extract important features from image\n* **Pooling Laye**r: This layer reduce the spatial volume of input image after convolution by isolating the important features\n* **Hidden Layer**: It connect the network from a layer to another layer\n* **Output Layer**: It is the final layer with neurons equals to no.of classes"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    \n    tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    \n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='relu'),\n    \n    tf.keras.layers.Dense(1, activation='sigmoid')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss = 'binary_crossentropy',\n              optimizer = 'SGD',\n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Training Generator with Image Augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_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      fill_mode='nearest')\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    train_df, \n    \"/tmp/train/\", \n    x_col='Image',\n    y_col='Label',\n    target_size = (150, 150),\n    class_mode = 'binary',\n    batch_size = 20\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Validation Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df, \n    \"/tmp/train/\", \n    x_col='Image',\n    y_col='Label',\n    target_size = (150, 150),\n    class_mode = 'binary',\n    batch_size = 20\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n      train_generator,\n      steps_per_epoch = np.ceil(20000/20),  # 20000 images = batch_size * steps\n      epochs = 10,\n      validation_data=validation_generator,\n      validation_steps = np.ceil(5000/20),  # 5000 images = batch_size * steps\n      verbose = 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"To attain higher accuracy, number of epochs can be increased !!!"},{"metadata":{},"cell_type":"markdown","source":"## Visualizing the training"},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(len(acc))\n\nplt.figure(figsize=(7,7))\n\nplt.plot(epochs, acc, 'r', label='Training accuracy')\nplt.plot(epochs, val_acc, 'b', label='Validation accuracy')\nplt.title('Training and validation accuracy')\nplt.legend()\n\nplt.figure(figsize=(7,7))\n\nplt.plot(epochs, loss, 'r', label='Training Loss')\nplt.plot(epochs, val_loss, 'b', label='Validation Loss')\nplt.title('Training and validation loss')\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Preparing the Test Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extracting the zip file\n\nlocal_zip = '/kaggle/input/dogs-vs-cats/test1.zip'\nzip_ref = zipfile.ZipFile(local_zip, 'r')\nzip_ref.extractall('/tmp')\nzip_ref.close()\n\ntest_dir = '/tmp/test1/'\ntest_img = os.listdir(os.path.join(test_dir))\ntest_img[:10]\n\ntest_df = pd.DataFrame({'Image': test_img})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Test Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\n\ntest_generator = test_gen.flow_from_dataframe(\n    test_df, \n    \"/tmp/test1/\", \n    x_col = 'Image',\n    y_col = None,\n    class_mode = None,\n    target_size = (150, 150),\n    batch_size = 20,\n    shuffle = False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict = model.predict_generator(test_generator, steps = np.ceil(12500/20))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def label(predict):\n    if(predict > 0.5):\n        return \"Dog\"\n    else:\n        return \"Cat\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['Label'] = predict\ntest_df['Label'] = test_df['Label'].apply(label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.Label.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.Label.value_counts().plot.bar(color = ['red','blue'])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"v = random.randint(0, 12000)\n\nsample_test = test_df.iloc[v:(v+18)].reset_index(drop = True)\nsample_test.head()\n\nplt.figure(figsize=(12, 24))\nfor index, row in sample_test.iterrows():\n    filename = row['Image']\n    category = row['Label']\n    img = load_img(\"/tmp/test1/\" + filename, target_size = (150, 150))\n    plt.subplot(6, 3, index + 1)\n    plt.imshow(img)\n    plt.xlabel(filename + ' ( ' + \"{}\".format(category) + ' )' )\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### That's all Folks!!!"}],"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}