{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Training Dogs and Cats dataset with 2000 images. \n### Building powerful image classification models using very little data.\nThis notebook is inspired by this post by Francois Chollet : https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html"},{"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    %tensorflow_version 2.x\nexcept Exception:\n    pass","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport pandas as pd\n\n%matplotlib inline\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.__version__, keras.__version__","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"print(os.listdir('../input/dogs-vs-cats/'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Extract files from zip folders"},{"metadata":{"trusted":true},"cell_type":"code","source":"from zipfile import ZipFile\nwith ZipFile('../input/dogs-vs-cats/train.zip', 'r') as zf:\n    zf.extractall('destination_path/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# print(os.listdir('./destination_path/train'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Loading data into a Pandas Dataframe\nAppend file with 1 if dog, otherwise 0"},{"metadata":{"trusted":true},"cell_type":"code","source":"filenames = os.listdir('./destination_path/train')\ncategories = []\nfor filename in filenames:\n    category = filename.split('.')[0]\n    if category == 'dog':\n        categories.append(1)\n    else:\n        categories.append(0)\n        \n# laod data into a dataframe\ndf = pd.DataFrame({\n    'filename': filenames,\n    'category': categories\n})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pathlib\nimport random\n\nfrom tensorflow.keras.preprocessing.image import load_img","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Display 9 random images"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 12))\nfor i in range(0, 9):\n    plt.subplot(3, 3, i+1)\n    sample_image = random.choice(filenames)\n    image = load_img(\"./destination_path/train/\"+sample_image)\n    plt.imshow(image)\n    plt.title(sample_image)\n    plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Change 0 and 1 to cat and dog string values for binary crossentropy."},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0: 'cat', 1: 'dog'}) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" Sample 2000 images."},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df = df.groupby('category').apply(lambda x: x.sample(2000)).reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_df['category'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train and Validation sets\n\n3200 images for training and 800 for validation."},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, val_df = train_test_split(new_df, test_size=0.2, random_state=42)\ntrain_df = train_df.reset_index(drop=True)\nval_df = val_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Simple ConvNet Model\n\n3 blocks of (Conv2D -> BatchNorm -> Activation -> MaxPooling2D).<br>\nFully Connected Layers (Dense256 -> Dense64 -> Dropout -> Dense1 -> Sigmoid)"},{"metadata":{"trusted":true},"cell_type":"code","source":"# imports\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Activation, Dropout, Dense, Flatten, MaxPooling2D \nfrom tensorflow.keras.layers import BatchNormalization\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# constants\n\nimage_width, image_height = 150, 150\nimage_channels = 3\nimage_size = (image_width, image_height)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define model \n\nmodel = Sequential([\n    Conv2D(32, 3, use_bias=False, input_shape = (image_width, image_height, image_channels)),\n    BatchNormalization(),\n    Activation('relu'),\n    MaxPooling2D(),\n    \n    Conv2D(32, 3, use_bias=False),\n    BatchNormalization(),\n    Activation('relu'),\n    MaxPooling2D(),\n    \n    Conv2D(64, 3, use_bias=False),\n    BatchNormalization(),\n    Activation('relu'),\n    MaxPooling2D(),\n    \n    # fcn\n    Flatten(),\n    Dense(256, use_bias=False),\n    BatchNormalization(),\n    Activation('relu'),\n    Dense(64, use_bias=False),\n    Activation('relu'),\n    Dropout(0.5),\n    Dense(1, activation='sigmoid')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# compile model\n\nmodel.compile(loss='binary_crossentropy', optimizer=keras.optimizers.RMSprop(),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"early_stop = EarlyStopping(patience=10, verbose=1, restore_best_weights=True)\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,\n                              patience=5, min_lr=0.0001, verbose=1)\n\ncallbacks = [early_stop, reduce_lr]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 32\n\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                   rotation_range=15,\n                                   shear_range=0.1,\n                                   horizontal_flip=True,\n                                   zoom_range=0.2,\n                                   width_shift_range=0.1,\n                                   height_shift_range=0.1)\n\nval_datagen = ImageDataGenerator(rescale=1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# flow from Dataframe\n\ntrain_generator = train_datagen.flow_from_dataframe(train_df,\n                                                    './destination_path/train/',\n                                                    x_col='filename',\n                                                    y_col='category',\n                                                    target_size=image_size,\n                                                    class_mode='binary',\n                                                    batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_generator = val_datagen.flow_from_dataframe(val_df,\n                                                 './destination_path/train/',\n                                                    x_col='filename',\n                                                    y_col='category',\n                                                    target_size=image_size,\n                                                    class_mode='binary',\n                                                  batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Sample an Image"},{"metadata":{"trusted":true},"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                                                       './destination_path/train/',\n                                                       x_col = 'filename',\n                                                       y_col = 'category',\n                                                       target_size = image_size,\n                                                       class_mode = 'categorical')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_train = train_df.shape[0]\nprint(total_train)\ntotal_val = val_df.shape[0]\nprint(total_val)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"device_name = tf.test.gpu_device_name()\nif \"GPU\" not in device_name:\n    print(\"GPU device not found\")\nprint('Found GPU at: {}'.format(device_name))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.backend.clear_session()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 30\n\nhistory = model.fit_generator(train_generator,\n                              epochs=epochs,\n                              validation_data=valid_generator,\n                              validation_steps=total_val//batch_size,\n                              steps_per_epoch=total_train//batch_size,\n                              callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Learning Curves"},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nplt.figure(figsize=(14, 8))\nplt.subplot(1, 2, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.legend(loc = 'upper right')\nplt.ylabel('Accuracy')\n# plt.ylim([0.5, 1.0])\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylabel('Cross Entropy')\n# plt.ylim([0.5,1.0])\nplt.title('Training and Validation Loss')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss, accuracy = model.evaluate_generator(valid_generator, steps=total_val//batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"loss, accuracy","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## VGG16"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import VGG16\nfrom tensorflow.keras.layers import GlobalAveragePooling2D","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = VGG16(weights='imagenet', input_shape = (image_width, image_height, image_channels),\n                   include_top = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# freeze vgg16\n\nlen(base_model.layers)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# freeze the first 15 layers\n\nfor layer in base_model.layers[:15]:\n    layer.trainable = False\n    \nfor layer in base_model.layers[15:]:\n    layer.trainable = True\n\nbase_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Add a classification head\n\nnew_model = Sequential([\n    base_model,\n    GlobalAveragePooling2D(),\n    Dense(512, activation='relu'),\n    Dropout(0.2),\n    Dense(1, activation='sigmoid')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_model.compile(loss='binary_crossentropy',\n             optimizer = 'rmsprop',\n             metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_new = new_model.fit_generator(train_generator,\n                              epochs=30,\n                              validation_data=valid_generator,\n                              validation_steps=total_val//batch_size,\n                              steps_per_epoch=total_train//batch_size,\n                              callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vgg_loss, vgg_accuracy = new_model.evaluate_generator(valid_generator, steps=total_val//batch_size)\n\nvgg_loss, vgg_accuracy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history_new.history['accuracy']\nval_acc = history_new.history['val_accuracy']\n\nloss = history_new.history['loss']\nval_loss = history_new.history['val_loss']\n\nplt.figure(figsize=(14, 8))\nplt.subplot(1, 2, 1)\nplt.plot(acc, label='Training Accuracy')\nplt.plot(val_acc, label='Validation Accuracy')\nplt.legend(loc = 'lower right')\nplt.ylabel('Accuracy')\nplt.ylim([0, 1.0])\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(loss, label='Training Loss')\nplt.plot(val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.ylabel('Cross Entropy')\nplt.ylim([0,1.0])\nplt.title('Training and Validation Loss')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}