{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "_cell_guid": "ec96b202-b504-a30d-7690-b456905dd198"
      },
      "source": [
        "# Plot a Confusion Matrix\n",
        "\n",
        "I find it helpful to see how well a classifier is doing by plotting a confusion matrix. This function produces both 'regular' and normalized confusion matrices."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "35eff6dc-5645-ac99-ff4e-98f9dc8c305b"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "\n",
        "def plot_confusion_matrix(cm,\n",
        "                          target_names,\n",
        "                          title='Confusion matrix',\n",
        "                          cmap=None,\n",
        "                          normalize=True):\n",
        "    \"\"\"\n",
        "    given a sklearn confusion matrix (cm), make a nice plot\n",
        "\n",
        "    Arguments\n",
        "    ---------\n",
        "    cm:           confusion matrix from sklearn.metrics.confusion_matrix\n",
        "\n",
        "    target_names: given classification classes such as [0, 1, 2]\n",
        "                  the class names, for example: ['high', 'medium', 'low']\n",
        "\n",
        "    title:        the text to display at the top of the matrix\n",
        "\n",
        "    cmap:         the gradient of the values displayed from matplotlib.pyplot.cm\n",
        "                  see http://matplotlib.org/examples/color/colormaps_reference.html\n",
        "                  plt.get_cmap('jet') or plt.cm.Blues\n",
        "\n",
        "    normalize:    If False, plot the raw numbers\n",
        "                  If True, plot the proportions\n",
        "\n",
        "    Usage\n",
        "    -----\n",
        "    plot_confusion_matrix(cm           = cm,                  # confusion matrix created by\n",
        "                                                              # sklearn.metrics.confusion_matrix\n",
        "                          normalize    = True,                # show proportions\n",
        "                          target_names = y_labels_vals,       # list of names of the classes\n",
        "                          title        = best_estimator_name) # title of graph\n",
        "\n",
        "    Citiation\n",
        "    ---------\n",
        "    http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\n",
        "\n",
        "    \"\"\"\n",
        "    import matplotlib.pyplot as plt\n",
        "    import numpy as np\n",
        "    import itertools\n",
        "\n",
        "    accuracy = np.trace(cm) / float(np.sum(cm))\n",
        "    misclass = 1 - accuracy\n",
        "\n",
        "    if cmap is None:\n",
        "        cmap = plt.get_cmap('Blues')\n",
        "\n",
        "    plt.figure(figsize=(8, 6))\n",
        "    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n",
        "    plt.title(title)\n",
        "    plt.colorbar()\n",
        "\n",
        "    if target_names is not None:\n",
        "        tick_marks = np.arange(len(target_names))\n",
        "        plt.xticks(tick_marks, target_names, rotation=45)\n",
        "        plt.yticks(tick_marks, target_names)\n",
        "\n",
        "    if normalize:\n",
        "        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n",
        "\n",
        "\n",
        "    thresh = cm.max() / 1.5 if normalize else cm.max() / 2\n",
        "    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n",
        "        if normalize:\n",
        "            plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\n",
        "                     horizontalalignment=\"center\",\n",
        "                     color=\"white\" if cm[i, j] > thresh else \"black\")\n",
        "        else:\n",
        "            plt.text(j, i, \"{:,}\".format(cm[i, j]),\n",
        "                     horizontalalignment=\"center\",\n",
        "                     color=\"white\" if cm[i, j] > thresh else \"black\")\n",
        "\n",
        "\n",
        "    plt.tight_layout()\n",
        "    plt.ylabel('True label')\n",
        "    plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n",
        "    plt.show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "0dcab899-c365-9e50-61aa-e7fb8812a37c"
      },
      "outputs": [],
      "source": [
        "plot_confusion_matrix(cm           = np.array([[ 1098,  1934,   807],\n",
        "                                              [  604,  4392,  6233],\n",
        "                                              [  162,  2362, 31760]]), \n",
        "                      normalize    = False,\n",
        "                      target_names = ['high', 'medium', 'low'],\n",
        "                      title        = \"Confusion Matrix\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "09ebd590-50f7-f5ce-4f86-89c7e2fd0994"
      },
      "outputs": [],
      "source": [
        "plot_confusion_matrix(cm           = np.array([[ 1098,  1934,   807],\n",
        "                                              [  604,  4392,  6233],\n",
        "                                              [  162,  2362, 31760]]), \n",
        "                      normalize    = True,\n",
        "                      target_names = ['high', 'medium', 'low'],\n",
        "                      title        = \"Confusion Matrix, Normalized\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "_cell_guid": "8c4295de-8b14-4fef-d04a-412743c7a51c"
      },
      "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
}