{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "c17988a6-23f6-b9c4-938f-9b2351627c23"
      },
      "source": ""
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "40b9b187-f9c7-3cdb-a6e3-f608cfefc1af"
      },
      "outputs": [],
      "source": [
        "import os, cv2, random\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "from matplotlib import ticker\n",
        "import seaborn as sns\n",
        "\n",
        "from keras.models import Sequential\n",
        "from keras.layers import Input, Dropout, Flatten, Convolution2D, MaxPooling2D, Dense, Activation\n",
        "from keras.optimizers import RMSprop\n",
        "from keras.callbacks import ModelCheckpoint, Callback, EarlyStopping\n",
        "from keras.utils import np_utils"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "bb66cce8-71b1-56a4-86ff-402910aa1264"
      },
      "outputs": [],
      "source": [
        "TRAIN_DIR = '../input/train/'\n",
        "TEST_DIR = '../input/test/'\n",
        "train_dogs =   [(TRAIN_DIR+i, 1) for i in os.listdir(TRAIN_DIR) if 'dog' in i]\n",
        "train_cats =   [(TRAIN_DIR+i, 0) for i in os.listdir(TRAIN_DIR) if 'cat' in i]\n",
        "#\u53d6\u6d4b\u8bd5\u96c6\uff0c\u8fd9\u4e2a\u5730\u65b9\u9700\u8981\u63d0\u524d\u5360\u4f4d\uff0c-1\u5c31\u662f\u5360\u4f4d\u7b26\u3002\n",
        "test_images =  [(TEST_DIR+i, -1) for i in os.listdir(TEST_DIR)]\n",
        "print(test_images[0])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "516e95da-b868-27ff-6d61-6c17deb01f6a"
      },
      "outputs": [],
      "source": [
        "TRAIN_NUM = 50\n",
        "# \u56e0\u4e3a\u8fd0\u884c\u901f\u5ea6\u592a\u6162\uff0c\u9009\u53d6TRAIN_NUM\u4e2a\u6570\u636e\uff0c\u5e76\u968f\u673a\u6563\u5217\n",
        "\n",
        "train_images = train_dogs[:TRAIN_NUM]+ train_cats[:TRAIN_NUM]\n",
        "random.shuffle(train_images)\n",
        "# \u53d6\u4e2aTEST_NUM\u4e2a\u505a\u6d4b\u8bd5\n",
        "test_images =  test_images"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "eb2e9153-361b-2e9a-124f-e682fcd3ac97"
      },
      "outputs": [],
      "source": [
        "ROWS = 64\n",
        "COLS = 64\n",
        "\n",
        "#\u8fd9\u91cc\u4f20\u5165\u7c7b\u4f3ctrain_dogs\u7684K-V\u683c\u5f0flist\u3002\u5c06\u56fe\u7247\u7edf\u4e00\u5316\n",
        "# \u8fd4\u56de \u7edf\u4e00\u5316\u540e\u7684\u56fe\u7247 + label    \n",
        "def read_image(tuple_set):\n",
        "    file_path = tuple_set[0]\n",
        "    label = tuple_set[1]\n",
        "    img = cv2.imread(file_path, cv2.IMREAD_COLOR)\n",
        "    # \u8fd9\u91cc\u7684\u53c2\u6570\uff0c\u53ef\u4ee5\u662f\u5f69\u8272\u6216\u8005\u7070\u5ea6(GRAYSCALE)\n",
        "    return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC), label\n",
        "    # \u8fd9\u91cc\uff0c\u53ef\u4ee5\u9009\u62e9\u538b\u7f29\u56fe\u7247\u7684\u65b9\u5f0f\uff0czoom\uff08cv2.INTER_CUBIC & cv2.INTER_LINEAR\uff09\u8fd8\u662fshrink\uff08cv2.INTER_AREA\uff09"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "02654c0c-24d8-ef57-133b-ba00f7af05fc"
      },
      "outputs": [],
      "source": [
        "CHANNELS = 3\n",
        "# \u4ee3\u8868RGB\u4e09\u4e2a\u989c\u8272\u9891\u9053\n",
        "# \u5c06\u56fe\u7247\u53d8\u4e3anumpy\u6570\u7ec4\n",
        "# \u8fd4\u56de\u7edf\u4e00\u5316\u540e\u7684numpy\u6570\u7ec4 + label  \n",
        "def prep_data(images):\n",
        "    no_images = len(images)\n",
        "    data = np.ndarray((no_images, CHANNELS, ROWS, COLS), dtype=np.uint8)\n",
        "    labels = []\n",
        "    \n",
        "    for i, image_file in enumerate(images):       \n",
        "        image, label = read_image(image_file)\n",
        "        data[i] = image.T\n",
        "        labels.append(label)\n",
        "    return data, labels\n",
        "\n",
        "x_train, y_train = prep_data(train_images)\n",
        "x_test, y_test = prep_data(test_images)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "e2cc4904-aa20-04af-5ac8-4c582dc2f93c"
      },
      "outputs": [],
      "source": [
        "optimizer = RMSprop(lr=1e-4)      #\u5b66\u4e60\u65b9\u6cd5\uff0c\u4e00\u6b65\u8de8\u591a\u5927\n",
        "objective = 'binary_crossentropy' #0-1\u5dee\u8ddd\u71b5\uff0c\u56e0\u4e3a\u8fd9\u91cc\u5c31\u662f0-1\n",
        "\n",
        "# \u5efa\u9020\u6a21\u578bVGG-16\u6784\u67b6\u65b9\u5f0f    \n",
        "model = Sequential()\n",
        "#\u8f93\u5165\u4e00\u4e2a\u77e9\u9635 32\u4e2a\u7279\u5f81\uff0c3*3 \n",
        "#\u51e0\u5957CNN\u540e\uff0c\u7279\u5f81\u8981\u8d8a\u6765\u8d8a\u591a\uff0c\u4ece\u5927\u5904\u5230\u7ec6\u8282\u770b\u3002\u5982\u679c\u4ece\u7ec6\u8282\u5230\u5927\u770b\u3002feature\u4ece\u5927\u5230\u5c0f\n",
        "model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=(3, ROWS, COLS), activation='relu'))\n",
        "model.add(Convolution2D(32, 3, 3, border_mode='same', activation='relu'))\n",
        "model.add(MaxPooling2D( pool_size=(2, 2),dim_ordering=\"th\"))\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(pool_size=(2, 2),dim_ordering=\"th\"))\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(pool_size=(2, 2),dim_ordering=\"th\"))\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(pool_size=(2, 2),dim_ordering=\"th\"))\n",
        "\n",
        "model.add(Flatten()) ##\u53d8\u6210\u4e00\u6761\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",
        "model.compile(loss=objective, optimizer=optimizer, metrics=['accuracy'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "70485d9e-c309-3fe6-e0cc-99331eb30200"
      },
      "outputs": [],
      "source": [
        "#\u8fd9\u4e00\u90e8\u5206\u7b97CNN\u505c\u6b62\u70b9\n",
        "\n",
        "nb_epoch = 10\n",
        "batch_size = 10\n",
        "#\u6ca1\u6709\u51cf\u5c11\u53cd\u800c\u589e\u9ad8\u4e86\uff0c\u6211\u4eec\u7ed9\u4ed63\u6b65\u8010\u5fc3\n",
        "\n",
        "early_stopping = EarlyStopping(monitor='val_loss', patience=3, verbose=1, mode='auto')        \n",
        "# \u8dd1\u6a21\u578b\n",
        "model.fit(x_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch,\n",
        "          validation_split=0.2, verbose=0, shuffle=True, callbacks=[early_stopping])\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "6123dc01-e99e-c245-a146-fd7c6e72d7d1"
      },
      "outputs": [],
      "source": [
        "predictions = model.predict(x_test, verbose=0)\n",
        "print(predictions)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "a8aa8261-dc4e-a866-94e9-023ccfddaf76"
      },
      "outputs": [],
      "source": [
        "predictions[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.5.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}