{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "965595e2-36b2-240d-9a11-6c4c382edc0b"
      },
      "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/train'\n",
        "TEST_DIR = '../input/test'\n",
        "IMG_SIZE=50\n",
        "LR=1e-3\n",
        "\n",
        "MODEL_NAME='dogsvscats-{}-{}.model'.format(LR,'2conv-basic')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "36674161-69ab-38d3-f56d-87babbb5f5e4"
      },
      "outputs": [],
      "source": [
        "def label_img(img):\n",
        "    word_label=img.split('.')[-3]\n",
        "    if word_label == 'cat':return [1,0]\n",
        "    elif word_label =='dog':return [0,1]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "16d5bf6e-3619-39b9-f978-4d38a2a92741"
      },
      "outputs": [],
      "source": [
        "def create_train_data():\n",
        "    training_data=[]\n",
        "    for img in tqdm(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",
        "    "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "9ea01c28-e638-ab20-0814-d4c39c0fd7ee"
      },
      "outputs": [],
      "source": [
        "def process_test_data():\n",
        "    testing_data=[]\n",
        "    for img in tqdm(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",
        "        testing_data.append([np.array(img),img_num])\n",
        "        \n",
        "    np.save('test_data.npy',testing_data)\n",
        "    return testing_data"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "d04adaf6-72d8-af56-d42e-5eb84aface3f"
      },
      "outputs": [],
      "source": [
        "train_data = create_train_data()\n",
        "#if you already have the train data\n",
        "#train_data=np.load('train_data.npy')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "30283108-5751-7b3d-7e0d-19f67a787004"
      },
      "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,\n",
        "                     loss='categorical_crossentropy',name='targets')\n",
        "\n",
        "model = tflearn.DNN(convnet,tensorboard_dir='log')\n",
        "\n",
        "#print(model.predict([test_x[1]]))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "c81359a6-7f50-30d9-8888-af424e5385b5"
      },
      "outputs": [],
      "source": [
        "if os.path.exists('{}.meta'.format(MODEL_NAME)):\n",
        "    model.load(MODEL_NAME)\n",
        "    print('model_loaded!')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "7d902586-d276-6092-b5cd-677a572942f3"
      },
      "outputs": [],
      "source": [
        "train = train_data[:-500]# the last 500 data\n",
        "test = train_data[-500:]#\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "863883e5-6755-2794-ddc9-d50f0411cd23"
      },
      "outputs": [],
      "source": [
        "X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1) #i[0]is image data\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]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "65ce51d8-5cb4-3b53-9e4d-f2e1aa85c767"
      },
      "outputs": [],
      "source": [
        "model.fit({'input':X} ,{'targets': Y}, n_epoch=3,\n",
        "          validation_set=({'input':test_x}, {'targets': test_y}),\n",
        "          snapshot_step=5000, show_metric=True,run_id=MODEL_NAME)"
      ]
    }
  ],
  "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
}