{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"be209cb8-977c-d234-0932-d35537d10255"},"outputs":[],"source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output."},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"41a7b1c6-7390-a125-46b5-90b95df838a5"},"outputs":[],"source":"import cv2\nimport numpy as np\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"acde0d33-c8fd-98ab-17f7-85157c99686c"},"outputs":[],"source":"TRAIN_DIR = '../input/train'\nTEST_DIR = '../input/test'\nIMG_SIZE = 50\nalpha = 1e-3\n\nMODEL_NAME = 'dogsVscats_F5F5-{}-{}.model'.format(alpha, '2conv_example')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"df6409ac-a4d5-5f81-522b-8076fb72e5d7"},"outputs":[],"source":"def label_img(img):\n    word_label = img.split('.')[-3]\n    if word_label == 'cat': \n        return [1,0]\n    elif word_label == 'dog':\n        return [0,1]"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"7a23e8f4-1dbc-7380-9219-b683e77c1075"},"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('training_data.npy', training_data)\n    return training_data"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"5951c6ab-fb46-26fd-d55d-71c04b3b3167"},"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.imread(path,cv2.IMREAD_GRAYSCALE)\n        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n        testing_data.append([np.array(img), img_num])\n        \n    shuffle(testing_data)\n    np.save('test_data.npy', testing_data)\n    return testing_data\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"0d28a05f-ff6a-509e-687b-9f9cb6574d4d"},"outputs":[],"source":"train_data = create_train_data()\n#train_data = np.load('train_data.npy')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"7231772e-214b-fe0e-9df5-ba712efe6871"},"outputs":[],"source":"import tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet, 0.8)\n\nconvnet = fully_connected(convnet, 2, activation='softmax')\nconvnet = regression(convnet, optimizer='adam', learning_rate=alpha, loss='categorical_crossentropy', name='targets')\n\nmodel = tflearn.DNN(convnet, tensorboard_dir='log')\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"fd842ca0-e4fa-a0fb-98ae-8bc3af112efd"},"outputs":[],"source":"if os.path.exists('{}.meta'.format(MODEL_NAME)):\n    model.load(MODEL_NAME)\n    print('model loaded')\n   "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"289ef707-60f4-0802-74aa-6430ed665dcf"},"outputs":[],"source":"train = train_data[:-500]\ntest = train_data[-500:]\n\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"a9a27011-980f-78f7-1bc4-5dbbd2e2a67a"},"outputs":[],"source":"X = np.array([i[0] for i in train]). reshape(-1, IMG_SIZE, IMG_SIZE, 1)\nY = [i[1] for i in train]\n\ntest_X = np.array([i[0] for i in test]). reshape(-1, IMG_SIZE, IMG_SIZE, 1)\ntest_Y = [i[1] for i in test]"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"916b1b25-dd89-b4e9-9bc8-99aebb61065d"},"outputs":[],"source":" model.fit({'input': X}, {'targets': Y}, n_epoch=2, validation_set=({'input': test_X}, {'targets': test_Y}), \n    snapshot_step=500, show_metric=True, run_id=MODEL_NAME)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"abd546da-2734-61c4-84a8-dc0904d7f213"},"outputs":[],"source":"model.save(MODEL_NAME)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"ee77fd29-9914-7f85-177d-3935432e887b"},"outputs":[],"source":"import matplotlib.pyplot as plt\n\n# if you need to create the data:\n#test_data = process_test_data()\n# if you already have some saved:\ntest_data = np.load('test_data.npy')\nfig=plt.figure()\n\nfor num, data in enumerate(test_data[:12]):\n    img_num = data[1]\n    img_data = data[0]\n    \n    y = fig.add_subplot(3,4,num+1)\n    orig = img_data\n    data = img_data.reshape(IMG_SIZE,IMG_SIZE,1)\n    \n    model_out = model.predict([data])[0]\n    if np.argmax(model_out) == 1: str_label='Dog'\n    else: str_label='Cat'\n    \n    y.imshow(orig, cmap='gray')\n    plt.title(str_label)\n    y.axes.get_xaxis().set_visible(False)\n    y.axes.get_yaxis().set_visible(False)\nplt.show()   "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"eb86c373-b084-f10d-fcf5-765c43464e45"},"outputs":[],"source":"MODEL_NAME"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"bc5aae91-2f26-dafa-21dd-a89dce6c29a6"},"outputs":[],"source":""}],"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}