{"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\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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\n\nfiles_to_unzip = ['test1' , 'train']\n\nfor zip_file in files_to_unzip:\n    with zipfile.ZipFile(\"../input/dogs-vs-cats/{}.zip\".format(zip_file), \"r\") as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"filenames = os.listdir(\"../working/train\")\n\ncategories = []\n\nfor file_name in filenames:\n    if file_name.split('.')[0] == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n        \ndf = pd.DataFrame({\n    'filename' : filenames,\n    'category' : categories\n})\n\ndf.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\n\nsns.countplot(x = 'category', data = df)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Will show a random sample image from train set","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import load_img, ImageDataGenerator\nimport random\nimport matplotlib.pyplot as plt\n\nsample = random.choice(filenames)\n\nsample_image = load_img(\"../working/train/\" + sample)\n\nplt.imshow(sample_image)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = 128\n\ninput_shape = (image_size, image_size, 3)\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"simple_model = keras.Sequential([\n    \n    layers.Conv2D(filters = 32, kernel_size = 3, activation = 'relu', input_shape = input_shape),\n    layers.BatchNormalization(),\n    layers.MaxPool2D(),\n    layers.Dropout(0.25),\n    \n    layers.Conv2D(filters = 64, kernel_size = 3, activation = 'relu'),\n    layers.BatchNormalization(),\n    layers.MaxPool2D(),\n    layers.Dropout(0.25),\n    \n    layers.Conv2D(filters = 128, kernel_size = 3, activation = 'relu'),\n    layers.BatchNormalization(),\n    layers.MaxPool2D(),\n    layers.Dropout(0.25),\n    \n    layers.Flatten(),\n    \n    layers.Dense(512, activation = 'relu'),\n    layers.BatchNormalization(),\n    layers.Dropout(0.25),\n    \n    layers.Dense(1, activation = 'sigmoid'),\n    \n    \n])\n\nsimple_model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"simple_model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ndf[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) \n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, validate_df = train_test_split(df, test_size = 0.2)\ntrain_df = train_df.reset_index()\nvalidate_df = validate_df.reset_index()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    \n    rescale = 1./255,\n    rotation_range = 15, \n    shear_range = 0.1,\n    zoom_range = 0.2,\n    horizontal_flip = True,\n    width_shift_range = 0.1,\n    height_shift_range = 0.1,\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale = 1./255)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 150","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(train_df, \n                                                    \"../working/train/\", \n                                                    x_col = 'filename', \n                                                    y_col = 'category',\n                                                    class_mode = 'binary',\n                                                    target_size = (128, 128), \n                                                    batch_size = batch_size,\n                                                   )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_generator = validation_datagen.flow_from_dataframe(validate_df, \n                                                    \"../working/train/\", \n                                                    x_col = 'filename', \n                                                    y_col = 'category',\n                                                    class_mode = 'binary',\n                                                    target_size = (128, 128), \n                                                    batch_size = batch_size,\n                                                   )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### See some sample images","metadata":{}},{"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop = True)\n\nexample_generator = train_datagen.flow_from_dataframe(example_df,\n                                                      \"../working/train\",\n                                                     x_col = 'filename',\n                                                     y_col = 'category',\n                                                    \n                                                     )\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 9):\n    plt.subplot(3, 3, i+1)\n    for X_batch, Y_batch in example_generator:\n        image = X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping\n\nearlystop = EarlyStopping(patience=10)\n\ncallbacks = [earlystop]\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\nhistory = simple_model.fit(train_generator,\n                                epochs=5,     # 20\n                                validation_data = validation_generator,\n                                validation_steps = validate_df.shape[0]//batch_size,     \n                                steps_per_epoch = train_df.shape[0]//batch_size,\n                                callbacks = callbacks\n                                )\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_frame = pd.DataFrame(history.history)\n\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['accuracy', 'val_accuracy']].plot()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## VGG16","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.applications.vgg16 import VGG16\n\npretrained_base = VGG16(input_shape = input_shape, include_top = False, weights = 'imagenet')\n\npretrained_base.trainable = False","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = layers.Flatten()(pretrained_base.output)\n\nx = layers.Dense(512, activation = 'relu')(x)\n\nx = layers.Dropout(0.5)(x)\n\nx = layers.Dense(1, activation = 'sigmoid')(x)\n\nmodel = keras.models.Model(pretrained_base.input, x)\n\nmodel.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_vgg = model.fit(train_generator,\n                    epochs = 10,     # 20\n                    validation_data = validation_generator,\n                    validation_steps = validate_df.shape[0]//batch_size,     \n                    steps_per_epoch = train_df.shape[0]//batch_size,\n                    callbacks = callbacks\n                    )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_vgg_frame = pd.DataFrame(history_vgg.history)\n\nhistory_vgg_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_vgg_frame.loc[:, ['accuracy', 'val_accuracy']].plot()","metadata":{},"execution_count":null,"outputs":[]}]}