{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "5fd3e0f5-506d-78c6-754e-3daee51d56a2"
      },
      "source": ""
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "7aa44095-297e-84ea-82ec-1980b4f1fe76"
      },
      "outputs": [],
      "source": [
        "import cv2\n",
        "import numpy as np\n",
        "import os\n",
        "from random import shuffle\n",
        "# from tqdm import tqdm\n",
        "\n",
        "TRAIN_DIR = '../input/dogs-vs-cats-redux-kernels-edition/train'\n",
        "TEST_DIR = '../input/dogs-vs-cats-redux-kernels-edition/test'\n",
        "IMG_SIZE = 50\n",
        "LR = 1e-3\n",
        "\n",
        "MODEL_NAME = 'catsdogs-{}-{}.model'.format(LR, '2conv-basic')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "5b2e8f17-a494-54ed-bc5c-0d45aab9e58c"
      },
      "outputs": [],
      "source": [
        "def label_img(img):\n",
        "    # dog.93.png\n",
        "    word_label = img.split('.')[-3]\n",
        "    if word_label == 'cat': return [1, 0]\n",
        "    elif word_label == 'dog': return [0, 1]\n",
        "\n",
        "def create_train_data():\n",
        "    training_data = []\n",
        "    # for img in tqdm(os.listdir(TRAIN_DIR)):\n",
        "    for img in os.listdir(TRAIN_DIR):\n",
        "        label = label_img(img)\n",
        "        path = os.path.join(TRAIN_DIR, img)\n",
        "        img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE, IMG_SIZE))\n",
        "        training_data.append([np.array(img), np.array(label)])\n",
        "    shuffle(training_data)\n",
        "    np.save('train_data.npy', training_data)\n",
        "    return training_data\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6aaca0e8-7c7b-bb60-2dae-259fb4562ce0"
      },
      "outputs": [],
      "source": [
        "def process_test_data():\n",
        "    testing_data = []\n",
        "    # for img in tqdm(os.listdir(TEST_DIR)):\n",
        "    for img in os.listdir(TEST_DIR):\n",
        "        path = os.path.join(TEST_DIR, img)\n",
        "        img_num = img.split('.')[0]\n",
        "        img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_SIZE, IMG_SIZE))\n",
        "        tseting_data.append([np.array(img), img_num])\n",
        "    np.save('test_data.npy', testing_data)\n",
        "    return testing_data\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "5eb185ae-c702-8a4c-2fed-5b6b0f6a24c6"
      },
      "outputs": [],
      "source": [
        "model.fit({'input: X'}, {'targets: Y'}, n_epoch = 5,\n",
        "          validation_set = ({'input: test_x'}, {'targets: test_y'}),\n",
        "          snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "f68a58c6-fb5e-3d3f-f3f6-31b2d29139eb"
      },
      "outputs": [],
      "source": [
        "train_data = create_train_data()\n",
        "# train_data = np.load('train_data.npy')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "b47f7e42-a3fe-c361-46f6-1fde83fa5327"
      },
      "source": [
        "## Convolutional Neural Network ##"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "3c0e1c00-b6bd-5e11-19cb-2263687cc78c"
      },
      "outputs": [],
      "source": [
        "import tflearn\n",
        "from tflearn.layers.conv import conv_2d, max_pool_2d\n",
        "from tflearn.layers.core import input_data, dropout, fully_connected\n",
        "from tflearn.layers.estimator import regression\n",
        "\n",
        "convnet = input_data(shape = [None, IMG_SIZE, IMG_SIZE, 1], name = 'input')\n",
        "\n",
        "convnet = conv_2d(convnet, 32, 2, activation = 'relu')\n",
        "convnet = max_pool_2d(convnet, 2)\n",
        "\n",
        "convnet = conv_2d(convnet, 64, 2, activation = 'relu')\n",
        "convnet = max_pool_2d(convnet, 2)\n",
        "\n",
        "convnet = fully_connected(convnet, 1024, activation = 'relu')\n",
        "convnet = dropout(convnet, 0.8)\n",
        "\n",
        "convnet = fully_connected(convnet, 2, activation = 'softmax')\n",
        "convnet = regression(convnet, optimizer = 'adam', learning_rate = LR, loss = 'categorical_crossentropy', name = 'targets')\n",
        "\n",
        "model = tflearn.DNN(convnet, tensorboard_dir='log')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "9e99e5ee-327d-f452-cc0d-d81d321c6a93"
      },
      "outputs": [],
      "source": [
        "if os.path.exists('{}.meta'.format(MODEL_NAME)):\n",
        "    model.load(MODEL_NAME)\n",
        "    print(\"Model Loaded!\")\n",
        "\n",
        "\n",
        "train = train_data[:-500]\n",
        "test = train_data[-500:]\n",
        "\n",
        "X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n",
        "Y = [i[1] for i in train]\n",
        "\n",
        "test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n",
        "test_y = [i[1] for i in test]\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "a96319b2-ca68-4638-01d7-52b5d1b90876"
      },
      "outputs": [],
      "source": [
        "model.fit({'input': X'}, {'targets'': Y}, n_epoch = 5,\n",
        "          validation_set = ({'input': test_x}, {'targets': test_y}),\n",
        "          snapshot_step = 500, show_metric = True, run_id = MODEL_NAME)\n"
      ]
    }
  ],
  "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
}