{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\n\nimport tensorflow as tf\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\nimport sklearn\nfrom sklearn import metrics\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\n\n#unzip dataset will be found in \"../working\"\ndef unzip_dataset(path_to_zip_file, directory_to_extract_to):\n    with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:\n        zip_ref.extractall(directory_to_extract_to)\n        \nunzip_dataset(path_to_zip_file = \"../input/dogs-vs-cats-redux-kernels-edition/train.zip\", directory_to_extract_to = \"./\")\nunzip_dataset(path_to_zip_file = \"../input/dogs-vs-cats-redux-kernels-edition/test.zip\", directory_to_extract_to = \"./\")\n\nprint(os.listdir(\"../working\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR = '../working/train'\nTEST_DIR = '../working/test'\nIMG_SIZE = 50\nLR = 1e-3\n\ndef label_img(img):\n    word_label = img.split('.')\n    # conversion to one-hot array [cat,dog]\n    #                            [much cat, no dog]\n    if word_label[0] == 'cat': return [1,0]\n    #                             [no cat, very doggo]\n    elif word_label[0] == 'dog': return [0,1]\n    \ndef create_train_data():\n    training_data = []\n    training_label = []\n    i = 0\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.imread(path,cv2.IMREAD_COLOR)\n        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))[:,:, ::-1]\n        training_data.append(np.array(img))\n        training_label.append(np.array(label))\n        # test code\n#         i+=1\n#         if i == 10:\n#             break\n        # ---\n    return np.array(training_data), np.array(training_label)\n\ndef process_test_data():\n    testing_data = []\n    testing_ids = []\n    i = 0\n    for img in tqdm(os.listdir(TEST_DIR)):\n        path = os.path.join(TEST_DIR,img)\n        test_id = img.split('.')[0]\n        img = cv2.imread(path,cv2.IMREAD_COLOR)\n        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n        testing_data.append(np.array(img))\n        testing_ids.append(np.array(test_id))\n        # test code\n#         if i == 10:\n#             break\n#         i += 1\n        # ---\n    return np.array(testing_data), np.array(testing_ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data, labels = create_train_data()\ndata = data / 255 # normalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data, test_ids = process_test_data()\ntest_data = test_data / 255 # normalization","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(data[0])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 2. Data Pre-processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, X_valid = tf.split(  \n            data,\n            num_or_size_splits=[int(0.7 * data.shape[0]), 0, int(0.3 * data.shape[0])],\n            axis=0\n        )\ny_train, y_test, y_valid = tf.split(\n            labels,\n            [int(0.7 * data.shape[0]), 0, int(0.3 * data.shape[0])],\n            axis=0\n        )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 3. Model Building and Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import layers, models \n(_, data_length, data_width, _) = data.shape\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3, 3), activation = 'relu', input_shape = (data_length, data_width, 3)))\nmodel.add(layers.MaxPool2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(layers.MaxPool2D((2, 2)))\nmodel.add(layers.Conv2D(64, (3, 3), activation = 'relu'))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(64, activation = 'relu'))\nmodel.add(layers.Dense(2, activation = 'softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"METRICS = [\n    tf.keras.metrics.BinaryAccuracy(name='accuracy'),\n    tf.keras.metrics.TruePositives(name='tp'),\n    tf.keras.metrics.FalsePositives(name='fp'),\n    tf.keras.metrics.TrueNegatives(name='tn'),\n    tf.keras.metrics.FalseNegatives(name='fn'), \n    tf.keras.metrics.Precision(name='precision'),\n    tf.keras.metrics.Recall(name='recall'),\n    tf.keras.metrics.AUC(name='auc'),\n]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer = 'adam',\n              loss = tf.keras.losses.binary_crossentropy,\n              metrics = METRICS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs = 23, \n                    batch_size = 1000, shuffle = True,\n                    validation_data = (X_valid, y_valid)\n                   )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(model.predict(tf.expand_dims(X_train[0], 0)))\nprint(model.predict_classes(tf.expand_dims(X_train[0], 0)))\n# print(history.history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.evaluate(X_valid, y_valid)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4.1 Loss, AUC, Precision, and Recall Curve"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_predictions = model.predict_classes(X_train)\nvalid_predictions = model.predict_classes(X_valid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_metrics(history):\n    metrics =  ['loss', 'auc', 'precision', 'recall']\n    plt.figure(figsize=(15, 15))\n    for n, metric in enumerate(metrics):\n        name = metric\n        plt.subplot(2,2,n+1)\n        plt.plot(history.epoch,  history.history[metric], color= 'b', label='Train')\n        plt.plot(history.epoch, history.history['val_'+metric],\n                 color= 'r', linestyle=\"--\", label='Val')\n        plt.title(name)\n        plt.xlabel('Epoch')\n        plt.ylabel(name)\n        if metric == 'loss':\n            plt.ylim([0, plt.ylim()[1]])\n        elif metric == 'auc':\n            plt.ylim([0.8,1])\n        else:\n            plt.ylim([0,1])\n        plt.legend()\n        \nplot_metrics(history)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4.2 ROC Curve"},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_roc(name, labels, predictions, **kwargs):\n    fp, tp, _ = metrics.roc_curve(labels, predictions)\n\n    plt.plot(100*fp, 100*tp, label = name, linewidth=2, **kwargs)\n    plt.xlabel('False positives [%]')\n    plt.ylabel('True positives [%]')\n#     plt.xlim([-0.5,20])\n#     plt.ylim([80,100.5])\n    plt.grid(True)\n    ax = plt.gca()\n    ax.set_aspect('equal')\nplt.figure(figsize=(7, 7))\nplot_roc(\"Train Baseline\", y_train[:, 0], train_predictions, color ='b')\nplot_roc(\"Test Baseline\", y_valid[:, 0], valid_predictions, color = 'r', linestyle = '--')\nplt.legend(loc = 'lower right')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4.3 Confusion Matrix"},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nplt.figure(figsize = (7, 7))\ndef plot_cm(labels, predictions, p=0.5):\n    cm = metrics.confusion_matrix(labels, predictions > p)\n#     plt.figure(figsize=(5,5))\n    sns.heatmap(cm, annot=True, fmt=\"d\", cmap = 'YlGnBu')\n    plt.title('Confusion matrix @{:.2f}'.format(p))\n    plt.ylabel('Actual label')\n    plt.xlabel('Predicted label')\nplot_cm(y_train[:, 0], train_predictions)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 4. Model Testing"},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.save('saved_model')\nresults = model.predict(test_data)\nresults = results[:, 1] / np.sum(results, axis = 1)\nsubmission = pd.concat([pd.Series(test_ids), pd.Series(results)], axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = submission.rename(columns = {0: 'id', 1: 'label'})\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# submission.to_csv('submission.csv', index = False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}