{"cells":[{"metadata":{"_cell_guid":"764fe135-c09e-9769-5794-500867154d93","_uuid":"02fbd1bc2a9ec2d626b80dd2f4c572a045c0d1cd"},"cell_type":"markdown","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). \n"},{"metadata":{"_cell_guid":"3d458c15-e131-f3c4-f756-843d6454bb37","_uuid":"807038b248dd891dae24d41005cb077557f2b8c0","trusted":true},"cell_type":"code","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\nfrom keras.callbacks import ModelCheckpoint, Callback, EarlyStopping\nfrom keras.utils import np_utils\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD\nfrom keras import regularizers\nfrom keras.callbacks import TensorBoard\nfrom keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"04681981-55ac-7820-a0ae-38f98c851c39","_uuid":"f11a64fac2bcdff429a8ff8f9a48766e2fc49e09"},"cell_type":"markdown","source":"## Preparing the Data\n\nThis function resizes the images to 64x64 and samples 2000 images (8%) of the data to run efficiently as a Kaggle Kernel. I also separated cats and dogs for exploratory analysis. "},{"metadata":{"trusted":true,"_uuid":"73b0933ae3dce4545445761b2ab0e62cf781cc53"},"cell_type":"code","source":"import os\nos.listdir(os.getcwd() + '/../input')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"663d335e-1b84-a8cb-19ee-8f04839cf4e5","_uuid":"36aa07d60a793278090cbd6ca9caa43158f3cb97","trusted":true},"cell_type":"code","source":"ROOT_DIR = os.getcwd()\nTRAIN_DIR = '../input/train/'\nTEST_DIR = '../input/test/'\n\nROWS = 64\nCOLS = 64\nCHANNELS = 3\n\ntrain_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[:1000] + train_cats[:1000]\nrandom.shuffle(train_images)\ntest_images =  test_images[:100]\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, ROWS, COLS, CHANNELS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        data[i] = image\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))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"1fd1f8e8d19de623dadbe144ba633f5d90b6254e"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"ed0fc95a-53bc-3517-245d-cf1f5122bc2d","_uuid":"3c6081fb2f7b2b160d3abe78b7c895d673cc95ab"},"cell_type":"markdown","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. "},{"metadata":{"_cell_guid":"c0f2fbf6-8d78-7d42-6579-5486a36c1e60","_uuid":"3a7353f8f42e6be827362d0cbf3d05f56a20eee6","trusted":true},"cell_type":"code","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)\nplt.title('Cats and Dogs')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"4bb0bd2a-0512-aa72-c628-5b6ac946d97c","_uuid":"a65b67da4e65d4afaeec5fa626900e3647ba2ead"},"cell_type":"markdown","source":"### Checking out Cats and Dogs\nA quick side-by-side comparison of the animals."},{"metadata":{"_cell_guid":"0b7c79ae-6543-2ed8-e3f5-af4f5beb9cf7","_uuid":"bc0c3d1a1a105c225e9e36ad7e572ffb2537bc40","trusted":true},"cell_type":"code","source":"def show_cats_and_dogs(idx):\n    cat = read_image(train_cats[idx])\n    dog = read_image(train_dogs[idx])\n    pair = np.concatenate((cat, dog), axis=1)\n    plt.figure(figsize=(10,5))\n    plt.imshow(pair)\n    plt.show()\n    \nfor idx in range(0,5):\n    show_cats_and_dogs(idx)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"599a11ba-aaa4-8266-03ea-d816518e2a81","_uuid":"1a9d139d78ebbabb9fee4c6165f89a49fd092d50"},"cell_type":"markdown","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..."},{"metadata":{"_cell_guid":"7d3c6eb7-c370-9752-67c8-c780bab14abe","_uuid":"b36588a1ed2f32c2242f334b300a35c97cd8e3cf","trusted":true},"cell_type":"code","source":"dog_avg = np.array([dog[0].T for i, dog in enumerate(train) if labels[i]==1]).mean(axis=0)\nplt.imshow(dog_avg)\nplt.title('Your Average Dog')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a5a93063-de92-18ce-b48f-68a193e90002","_uuid":"9bac2c1a747eba114b9eda285b7e7efbd0fb4ac2","trusted":true},"cell_type":"code","source":"cat_avg = np.array([cat[0].T for i, cat in enumerate(train) if labels[i]==0]).mean(axis=0)\nplt.imshow(cat_avg)\nplt.title('Your Average Cat')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"51e403b6-bcfc-b4fa-3770-9850cc86bae3","_uuid":"1533d7fc066792ec767a3d1b09af2d7e743d3063"},"cell_type":"markdown","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. )"},{"metadata":{"_cell_guid":"4c477612-41d3-3112-5176-3c4ad9633080","_uuid":"ece69bde27be324478ab6cdf7f32277075b5edb9","trusted":true},"cell_type":"code","source":"objective = 'binary_crossentropy'\n\n\ndef catdog():\n    \n    model = Sequential()\n    model.add(Convolution2D(32, 2, 2, border_mode='same', input_shape=(ROWS, COLS, 3), activation='relu'))\n    model.add(Convolution2D(32, 2, 2, border_mode='same', activation='relu'))\n    model.add(MaxPooling2D((2, 2), name='block1_pool1', data_format='channels_last'))\n    model.add(BatchNormalization())\n\n    model.add(Convolution2D(64, 3, 3, border_mode='same', activation='relu'))\n    model.add(Convolution2D(64, 3, 3, border_mode='same', activation='relu'))\n    model.add(MaxPooling2D((2, 2), name='block1_pool2', data_format='channels_last'))\n    model.add(BatchNormalization())\n    \n    model.add(Convolution2D(128, 3, 3, border_mode='same', activation='relu'))\n    model.add(Convolution2D(128, 3, 3, border_mode='same', activation='relu'))\n    model.add(MaxPooling2D((2, 2), name='block1_pool3', data_format='channels_last'))\n    model.add(BatchNormalization())\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(MaxPooling2D((2, 2), name='block1_pool4', data_format='channels_last'))\n    model.add(BatchNormalization())\n\n    model.add(Flatten())\n    model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01)))\n    model.add(Dropout(0.5))\n    \n    model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01)))\n    model.add(Dropout(0.5))\n\n    model.add(Dense(1))\n    model.add(Activation('sigmoid'))\n    optimizer = SGD(lr=1e-6, decay=1e-6, momentum=0.9, nesterov=True)\n    model.compile(loss=objective, optimizer=optimizer, metrics=['accuracy'])\n    # model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\n    return model\n\n\nmodel = catdog()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"b7fbf156-2268-62ce-5fed-52a09af5e6f7","_uuid":"488a41fa4d17372a659cd55d56b67185278bc7eb"},"cell_type":"markdown","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. "},{"metadata":{"_cell_guid":"ca613169-4b41-e9d5-27c7-6629f8e035c8","_uuid":"e32aa1426e219dcc3b558b2e40225d778399f7d3","trusted":true},"cell_type":"code","source":"nb_epoch = 5\nbatch_size = 16\n\n## Callback for loss logging per epoch\nclass LossHistory(Callback):\n    def on_train_begin(self, logs={}):\n        self.losses = []\n        self.val_losses = []\n        \n    def on_epoch_end(self, batch, logs={}):\n        self.losses.append(logs.get('loss'))\n        self.val_losses.append(logs.get('val_loss'))\n##\n#1. monitor：需要监视的量\n#2. patience：当early stop被激活（如发现loss相比上一个epoch训练没有下降），则经过patience个epoch后停止训练。\n#3. verbose：信息展示模式\n#4. mode：‘auto’，‘min’，‘max’之一，在min模式下，如果检测值停止下降则中止训练。在max模式下，当检测值不再上升则停止训练。\nlrate = ReduceLROnPlateau(min_lr=0.00001)\ntb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)  # 在当前目录新建logs文件夹，记录 evens.out\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='auto')        \n        \ndef run_catdog():\n    \n    history = LossHistory()\n    model.fit(train, labels, batch_size=batch_size, nb_epoch=nb_epoch,\n              validation_split=0.25, verbose=1, shuffle=True, callbacks=[history, early_stopping, tb])\n    \n\n    predictions = model.predict(test, verbose=0)\n    return predictions, history\n\npredictions, history = run_catdog()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"6266d01c-9d4c-a1dc-8cb9-ce7b3107b536","_uuid":"2abebf4258de937bdf62db675640f7fb327c27bd","trusted":true},"cell_type":"code","source":"loss = history.losses\nval_loss = history.val_losses\n\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.title('VGG-16 Loss Trend')\nplt.plot(loss, 'blue', label='Training Loss')\nplt.plot(val_loss, 'green', label='Validation Loss')\nplt.xticks(range(0,nb_epoch)[0::2])\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"d9382e7d-31db-0d75-6876-aaccb126e4f6","_uuid":"b2a92bd9017ba41e443f432139b01bc72e9c14f7"},"cell_type":"markdown","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%. "},{"metadata":{"_cell_guid":"c665d01b-a5a7-2f7e-e5d4-09e108920e40","_uuid":"76c35c51a4ed3f4d57bcc2217ffb9744bf51ccbd","trusted":true},"cell_type":"code","source":"for i in range(0,10):\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])\n    plt.show()","execution_count":null,"outputs":[]}],"metadata":{"_change_revision":0,"_is_fork":false,"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}