{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "f821c4ca-531d-6498-57ac-532457ad5751"
      },
      "outputs": [],
      "source": [
        "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n",
        "import glob\n",
        "import os\n",
        "import cv2\n",
        "from skimage import color\n",
        "from skimage import io\n",
        "import tensorflow as tf\n",
        "import tflearn\n",
        "from tflearn.layers.core import input_data, dropout, fully_connected\n",
        "from tflearn.layers.conv import conv_2d, max_pool_2d\n",
        "from tflearn.layers.normalization import local_response_normalization\n",
        "from tflearn.layers.estimator import regression\n",
        "import random\n",
        "import csv as csv\n",
        "import numpy as np\n",
        "%matplotlib inline \n",
        "\n",
        "\n",
        "# Any results you write to the current directory are saved as output."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "516d3e19-b455-a2a6-826d-95d11d288f52"
      },
      "outputs": [],
      "source": [
        "TRAIN_DIR = '../input/train/'\n",
        "TEST_DIR = '../input/test/'\n",
        "NUMBER_OF_TRAIN_DATA = 10\n",
        "\n",
        "def read_image(file_path):        \n",
        "    img= cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)\n",
        "    img= cv2.resize(img, (150, 150), interpolation=cv2.INTER_CUBIC)\n",
        "    return img\n",
        "\n",
        "def prep_data(images):\n",
        "    count = len(images)\n",
        "    data = np.ndarray((count,1, 150, 150), 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",
        "\n",
        "train_cats = sorted(glob.glob(os.path.join(TRAIN_DIR, 'cat*.jpg')))\n",
        "train_dogs = sorted(glob.glob(os.path.join(TRAIN_DIR, 'dog*.jpg')))\n",
        "train_all = train_dogs+train_cats \n",
        "\n",
        "random.Random(4).shuffle(train_all)\n",
        "\n",
        "test_all = sorted(glob.glob(os.path.join(TEST_DIR, '*.jpg')))\n",
        "\n",
        "X_train = prep_data([path for path in train_all[0:NUMBER_OF_TRAIN_DATA]] )\n",
        "Y_train = np.array([1. if 'dog' in name else 0. for name in train_all[0:NUMBER_OF_TRAIN_DATA]])\n",
        "\n",
        "X_test = [read_image(path) for path in test_all] \n",
        "Y_test = np.array([1. if 'dog' in name else 0. for name in test_all])\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "076cf2c1-4707-d340-76d7-c18b0593e4a6"
      },
      "outputs": [],
      "source": [
        "print(X_train.shape())\n",
        "print(Y_train.shape())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "2c1ad5ca-86ca-546c-88e7-e158e2ae8b06"
      },
      "outputs": [],
      "source": [
        "tf.reset_default_graph()\n",
        "\n",
        "net = input_data(shape=[None, 1,150, 150], name='input')\n",
        "net = conv_2d(net, 32, 3, activation='relu', regularizer=\"L2\")\n",
        "net = max_pool_2d(net, 2)\n",
        "net = local_response_normalization(net)\n",
        "net = conv_2d(net, 64, 3, activation='relu', regularizer=\"L2\")\n",
        "net = max_pool_2d(net, 2)\n",
        "net = local_response_normalization(net)\n",
        "net = fully_connected(net, 128, activation='tanh')\n",
        "net = dropout(net, 0.8)\n",
        "net = fully_connected(net, 256, activation='tanh')\n",
        "net = dropout(net, 0.8)\n",
        "net = fully_connected(net, 10, activation='softmax')\n",
        "net = regression(net, optimizer='adam', learning_rate=0.01,\n",
        "                     loss='categorical_crossentropy', name='target')\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "1d386e1e-2d24-4173-d3a2-b8ae18777b48"
      },
      "outputs": [],
      "source": [
        "model = tflearn.DNN(net, tensorboard_verbose=0)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "437d3086-a863-320d-ff3c-d667ceb2ae6a"
      },
      "outputs": [],
      "source": [
        "model.fit(X_train, Y_train, n_epoch=1,\n",
        "           validation_set=({'input': X_test}, {'target': Y_test}),\n",
        "           snapshot_step=100, show_metric=True, run_id='convnet_mnist')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "76be9b6d-7d53-1084-e51c-798714cba42d"
      },
      "outputs": [],
      "source": [
        "print(model.predict(np.reshape(X_test[0], (-1, 22500)))[0][0])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "01b4f49e-cfd2-bf15-e346-2dd27896a604"
      },
      "outputs": [],
      "source": [
        "myfile = open('submission.csv', 'w')\n",
        "wr = csv.writer(myfile, quoting=csv.QUOTE_NONE,quotechar='',escapechar='\\\\')\n",
        "wr.writerow([\"id\",\"label\"])\n",
        "\n",
        "for i in range(0,len(X_test)):\n",
        "     wr.writerow([i+1,float(model.predict(np.reshape(X_test[i], (-1, 22500)))[0][0])])"
      ]
    }
  ],
  "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.6.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}