{"cells":[{"cell_type":"markdown","metadata":{"_cell_guid":"764fe135-c09e-9769-5794-500867154d93"},"source":"Starter EDA and ConvNet implementation using Keras. \n\nInspiration for this notebook comes from this [Keras blog post](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html) and the [VGG ConvNet paper](https://arxiv.org/pdf/1409.1556.pdf). "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"f517b919-7954-2a26-6510-ae715710b25d"},"outputs":[],"source":"import theano"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"3d458c15-e131-f3c4-f756-843d6454bb37"},"outputs":[],"source":"import os, cv2, random\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import ticker\nimport seaborn as sns\n%matplotlib inline \n\nfrom keras.models import Sequential\nfrom keras.layers import Input, Dropout, Flatten, Convolution2D, MaxPooling2D, Dense, Activation\nfrom keras.optimizers import RMSprop, SGD, Adam\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping\nfrom keras.utils import np_utils"},{"cell_type":"markdown","metadata":{"_cell_guid":"04681981-55ac-7820-a0ae-38f98c851c39"},"source":"## Preparing the Data\n\nThis function resizes the images to 64x64 and samples 4000 images (8%) of the data to run efficiently as a Kaggle Kernel. I also separated cats and dogs for exploratory analysis. "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"663d335e-1b84-a8cb-19ee-8f04839cf4e5"},"outputs":[],"source":"TRAIN_DIR = '../input/train/'\nTEST_DIR = '../input/test/'\n\nROWS = 64\nCOLS = 64\nCHANNELS = 3\n\n#train_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)] # use this for full dataset\ntrain_dogs =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog' in i]\ntrain_cats =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat' in i]\n\ntest_images =  [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\n\n# slice datasets for memory efficiency on Kaggle Kernels, delete if using full dataset\ntrain_images = train_dogs[:150] + train_cats[:100]\nrandom.shuffle(train_images)\ntest_images =  test_images[:10]\n\ndef read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE\n    return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC)\n\n\ndef prep_data(images):\n    count = len(images)\n    data = np.ndarray((count, CHANNELS, ROWS, COLS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        data[i] = image.T\n        if i%250 == 0: print('Processed {} of {}'.format(i, count))\n    \n    return data\n\ntrain = prep_data(train_images)\ntest = prep_data(test_images)\n\nprint(\"Train shape: {}\".format(train.shape))\nprint(\"Test shape: {}\".format(test.shape))"},{"cell_type":"markdown","metadata":{"_cell_guid":"ed0fc95a-53bc-3517-245d-cf1f5122bc2d"},"source":"### Generating the Labels\n\nWe're dealing with a binary classification problem here - (1) dog (0) cat. The lables can be created by looping over the file names in the train directory. It's nice to see the training data is perfectly balanced. "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c0f2fbf6-8d78-7d42-6579-5486a36c1e60"},"outputs":[],"source":"labels = []\nfor i in train_images:\n    if 'dog' in i:\n        labels.append(1)\n    else:\n        labels.append(0)\n\nsns.countplot(labels)\nsns.plt.title('Cats and Dogs')"},{"cell_type":"markdown","metadata":{"_cell_guid":"4bb0bd2a-0512-aa72-c628-5b6ac946d97c"},"source":"### Checking out Cats and Dogs\nA quick side-by-side comparison of the animals."},{"cell_type":"markdown","metadata":{"_cell_guid":"599a11ba-aaa4-8266-03ea-d816518e2a81"},"source":"### Your Average Cat and Dog Photo\n\nJust for fun, the mean pixel values for cats and dogs. I can almost see a resemblance, a ghost, if you will..."},{"cell_type":"markdown","metadata":{"_cell_guid":"51e403b6-bcfc-b4fa-3770-9850cc86bae3"},"source":"## CatdogNet-16\n\nA scaled down version of the VGG-16, with a few notable changes.\n\n- Number of convolution filters cut in half, fully connected (dense) layers scaled down. \n- Optimizer changed to `RMSprop`. \n- Output layer activation set to `sigmoid` for binary crossentropy. \n- Some layers commented out for efficiency.\n\nThe full network takes about 80s per epoch on a GTX1070 (or 2hr+ on CPU) on the full dataset.  (This script only trains on 8% of the 25K images. )"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"4c477612-41d3-3112-5176-3c4ad9633080"},"outputs":[],"source":"optimizer = SGD(lr=1e-3)\n#logloss-> binary_crossentropy\nobjective = 'binary_crossentropy'\n\n#set dim_ordering to 'th' so it reads channel dimension at index 1\ndef catdog():\n    \n    model = Sequential()\n\n    model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=(3, ROWS, COLS), dim_ordering='th',activation='relu'))\n    model.add(Convolution2D(32, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Convolution2D(64, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(Convolution2D(64, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Convolution2D(128, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(Convolution2D(128, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n    \n    model.add(Convolution2D(256, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n    model.add(Convolution2D(256, 3, 3, border_mode='same', dim_ordering='th',activation='relu'))\n#     model.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\n    model.add(MaxPooling2D(pool_size=(2, 2)))\n\n#     model.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\n#     model.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\n#     model.add(Convolution2D(256, 3, 3, border_mode='same', activation='relu'))\n#     model.add(MaxPooling2D(pool_size=(2, 2)))\n\n    model.add(Flatten())\n    model.add(Dense(256, activation='relu'))\n    model.add(Dropout(0.5))\n    \n    model.add(Dense(256, activation='relu'))\n    model.add(Dropout(0.5))\n\n    model.add(Dense(1))\n    model.add(Activation('sigmoid'))\n\n    return model\n\n\nmodel = catdog()\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d6fa0a7f-8068-d96b-006f-2e679ace3cfe"},"outputs":[],"source":"model.compile(loss=objective, optimizer=optimizer, metrics=['binary_crossentropy'])\n"},{"cell_type":"markdown","metadata":{"_cell_guid":"b7fbf156-2268-62ce-5fed-52a09af5e6f7"},"source":"### Train and Predict\n\nI'm using Keras's early stopping callback to end training when the validation loss stops improving, otherwise the model will overfit. I will also be tracking the loss history on each epoch to visualize the overfitting trend. \n\nNote: A slice of 1000 images was used to fit the model for CPU efficency. The model's perfrmance improves significantly when used on the entire dataset. "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"ca613169-4b41-e9d5-27c7-6629f8e035c8"},"outputs":[],"source":"nb_epoch = 5\nbatch_size = 10\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='auto')        \n        \nfrom keras.callbacks import History \nhistory = History()\ntrain_model=model.fit(train, labels, batch_size=batch_size, nb_epoch=nb_epoch,\n              validation_split=0.25, verbose=0, shuffle=True, callbacks=[history,early_stopping])\n    \n\npredictions = model.predict(test, verbose=0)\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"b0b19a31-2dbe-fd36-486f-3e22b1cc0594"},"outputs":[],"source":"predictions"},{"cell_type":"markdown","metadata":{"_cell_guid":"d9382e7d-31db-0d75-6876-aaccb126e4f6"},"source":"## How'd We Do?\n\nI'm pretty sure I can distinguish a cat from a dog 100% of the time, but how confident is the model?...\n\nTip: Run on the full dataset with a GPU for a LB logloss of ~0.4 and accuracy at approx 90%. "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"8d7edca4-fdf5-19ce-db2c-bfb6f9621b04"},"outputs":[],"source":"print(train_model.history.keys())"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"a79e64d4-4fb1-68ce-4fa8-5dbb6c224c2f"},"outputs":[],"source":"#plot log loss\nplt.plot(train_model.history['loss'], 'blue', label='training loss')\nplt.plot(train_model.history['val_loss'], 'green', label='validation loss')\nplt.title('model log loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(loc='upper right')\n\nplt.show()"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c665d01b-a5a7-2f7e-e5d4-09e108920e40"},"outputs":[],"source":"for i in range(0,5):\n    if predictions[i, 0] >= 0.5: \n        print('I am {:.2%} sure this is a Dog'.format(predictions[i][0]))\n    else: \n        print('I am {:.2%} sure this is a Cat'.format(1-predictions[i][0]))\n        \n    plt.imshow(test[i].T)\n    plt.show()"}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.5.2"}},"nbformat":4,"nbformat_minor":0}