{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Comparison of Calibration of Classifiers\n\n\nWell calibrated classifiers are probabilistic classifiers for which the output\nof the predict_proba method can be directly interpreted as a confidence level.\nFor instance a well calibrated (binary) classifier should classify the samples\nsuch that among the samples to which it gave a predict_proba value close to\n0.8, approx. 80% actually belong to the positive class.\n\nLogisticRegression returns well calibrated predictions as it directly\noptimizes log-loss. In contrast, the other methods return biased probabilities,\nwith different biases per method:\n\n* GaussianNaiveBayes tends to push probabilities to 0 or 1 (note the counts in\n  the histograms). This is mainly because it makes the assumption that features\n  are conditionally independent given the class, which is not the case in this\n  dataset which contains 2 redundant features.\n\n* RandomForestClassifier shows the opposite behavior: the histograms show\n  peaks at approx. 0.2 and 0.9 probability, while probabilities close to 0 or 1\n  are very rare. An explanation for this is given by Niculescu-Mizil and Caruana\n  [1]_: \"Methods such as bagging and random forests that average predictions\n  from a base set of models can have difficulty making predictions near 0 and 1\n  because variance in the underlying base models will bias predictions that\n  should be near zero or one away from these values. Because predictions are\n  restricted to the interval [0,1], errors caused by variance tend to be one-\n  sided near zero and one. For example, if a model should predict p = 0 for a\n  case, the only way bagging can achieve this is if all bagged trees predict\n  zero. If we add noise to the trees that bagging is averaging over, this noise\n  will cause some trees to predict values larger than 0 for this case, thus\n  moving the average prediction of the bagged ensemble away from 0. We observe\n  this effect most strongly with random forests because the base-level trees\n  trained with random forests have relatively high variance due to feature\n  subsetting.\" As a result, the calibration curve shows a characteristic\n  sigmoid shape, indicating that the classifier could trust its \"intuition\"\n  more and return probabilities closer to 0 or 1 typically.\n\n* Support Vector Classification (SVC) shows an even more sigmoid curve as\n  the  RandomForestClassifier, which is typical for maximum-margin methods\n  (compare Niculescu-Mizil and Caruana [1]_), which focus on hard samples\n  that are close to the decision boundary (the support vectors).\n\n.. topic:: References:\n\n    .. [1] Predicting Good Probabilities with Supervised Learning,\n          A. Niculescu-Mizil & R. Caruana, ICML 2005\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(__doc__)\n\n# Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>\n# License: BSD Style.\n\nimport numpy as np\nnp.random.seed(0)\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn import datasets\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.calibration import calibration_curve\n\nX, y = datasets.make_classification(n_samples=100000, n_features=20,\n                                    n_informative=2, n_redundant=2)\n\ntrain_samples = 100  # Samples used for training the models\n\nX_train = X[:train_samples]\nX_test = X[train_samples:]\ny_train = y[:train_samples]\ny_test = y[train_samples:]\n\n# Create classifiers\nlr = LogisticRegression(solver='lbfgs')\ngnb = GaussianNB()\nsvc = LinearSVC(C=1.0)\nrfc = RandomForestClassifier(n_estimators=100)\n\n\n# #############################################################################\n# Plot calibration plots\n\nplt.figure(figsize=(10, 10))\nax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)\nax2 = plt.subplot2grid((3, 1), (2, 0))\n\nax1.plot([0, 1], [0, 1], \"k:\", label=\"Perfectly calibrated\")\nfor clf, name in [(lr, 'Logistic'),\n                  (gnb, 'Naive Bayes'),\n                  (svc, 'Support Vector Classification'),\n                  (rfc, 'Random Forest')]:\n    clf.fit(X_train, y_train)\n    if hasattr(clf, \"predict_proba\"):\n        prob_pos = clf.predict_proba(X_test)[:, 1]\n    else:  # use decision function\n        prob_pos = clf.decision_function(X_test)\n        prob_pos = \\\n            (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min())\n    fraction_of_positives, mean_predicted_value = \\\n        calibration_curve(y_test, prob_pos, n_bins=10)\n\n    ax1.plot(mean_predicted_value, fraction_of_positives, \"s-\",\n             label=\"%s\" % (name, ))\n\n    ax2.hist(prob_pos, range=(0, 1), bins=10, label=name,\n             histtype=\"step\", lw=2)\n\nax1.set_ylabel(\"Fraction of positives\")\nax1.set_ylim([-0.05, 1.05])\nax1.legend(loc=\"lower right\")\nax1.set_title('Calibration plots  (reliability curve)')\n\nax2.set_xlabel(\"Mean predicted value\")\nax2.set_ylabel(\"Count\")\nax2.legend(loc=\"upper center\", ncol=2)\n\nplt.tight_layout()\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "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.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}