{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Detection error tradeoff (DET) curve\n\nIn this example, we compare two binary classification multi-threshold metrics:\nthe Receiver Operating Characteristic (ROC) and the Detection Error Tradeoff\n(DET). For such purpose, we evaluate two different classifiers for the same\nclassification task.\n\nROC curves feature true positive rate (TPR) on the Y axis, and false positive\nrate (FPR) on the X axis. This means that the top left corner of the plot is the\n\"ideal\" point - a FPR of zero, and a TPR of one.\n\nDET curves are a variation of ROC curves where False Negative Rate (FNR) is\nplotted on the y-axis instead of the TPR. In this case the origin (bottom left\ncorner) is the \"ideal\" point.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>- See :func:`sklearn.metrics.roc_curve` for further information about ROC\n      curves.\n\n    - See :func:`sklearn.metrics.det_curve` for further information about\n      DET curves.\n\n    - This example is loosely based on\n      `sphx_glr_auto_examples_classification_plot_classifier_comparison.py`\n      example.\n\n    - See `sphx_glr_auto_examples_model_selection_plot_roc_crossval.py` for\n      an example estimating the variance of the ROC curves and ROC-AUC.</p></div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Generate synthetic data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nX, y = make_classification(\n    n_samples=1_000,\n    n_features=2,\n    n_redundant=0,\n    n_informative=2,\n    random_state=1,\n    n_clusters_per_class=1,\n)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Define the classifiers\n\nHere we define two different classifiers. The goal is to visually compare their\nstatistical performance across thresholds using the ROC and DET curves.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.dummy import DummyClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import LinearSVC\n\nclassifiers = {\n    \"Linear SVM\": make_pipeline(StandardScaler(), LinearSVC(C=0.025)),\n    \"Random Forest\": RandomForestClassifier(\n        max_depth=5, n_estimators=10, max_features=1, random_state=0\n    ),\n    \"Non-informative baseline\": DummyClassifier(),\n}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compare ROC and DET curves\n\nDET curves are commonly plotted in normal deviate scale. To achieve this the\nDET display transforms the error rates as returned by the\n:func:`~sklearn.metrics.det_curve` and the axis scale using\n`scipy.stats.norm`.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.metrics import DetCurveDisplay, RocCurveDisplay\n\nfig, [ax_roc, ax_det] = plt.subplots(1, 2, figsize=(11, 5))\n\nax_roc.set_title(\"Receiver Operating Characteristic (ROC) curves\")\nax_det.set_title(\"Detection Error Tradeoff (DET) curves\")\n\nax_roc.grid(linestyle=\"--\")\nax_det.grid(linestyle=\"--\")\n\nfor name, clf in classifiers.items():\n    (color, linestyle) = (\n        (\"black\", \"--\") if name == \"Non-informative baseline\" else (None, None)\n    )\n    clf.fit(X_train, y_train)\n    RocCurveDisplay.from_estimator(\n        clf,\n        X_test,\n        y_test,\n        ax=ax_roc,\n        name=name,\n        curve_kwargs=dict(color=color, linestyle=linestyle),\n    )\n    DetCurveDisplay.from_estimator(\n        clf, X_test, y_test, ax=ax_det, name=name, color=color, linestyle=linestyle\n    )\n\nplt.legend()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Notice that it is easier to visually assess the overall performance of\ndifferent classification algorithms using DET curves than using ROC curves. As\nROC curves are plot in a linear scale, different classifiers usually appear\nsimilar for a large part of the plot and differ the most in the top left\ncorner of the graph. On the other hand, because DET curves represent straight\nlines in normal deviate scale, they tend to be distinguishable as a whole and\nthe area of interest spans a large part of the plot.\n\nDET curves give direct feedback of the detection error tradeoff to aid in\noperating point analysis. The user can then decide the FNR they are willing to\naccept at the expense of the FPR (or vice-versa).\n\n## Non-informative classifier baseline for the ROC and DET curves\n\nThe diagonal black-dotted lines in the plots above correspond to a\n:class:`~sklearn.dummy.DummyClassifier` using the default \"prior\" strategy, to\nserve as baseline for comparison with other classifiers. This classifier makes\nconstant predictions, independent of the input features in `X`, making it a\nnon-informative classifier.\n\nTo further understand the non-informative baseline of the ROC and DET curves,\nwe recall the following mathematical definitions:\n\n$\\text{FPR} = \\frac{\\text{FP}}{\\text{FP} + \\text{TN}}$\n\n$\\text{FNR} = \\frac{\\text{FN}}{\\text{TP} + \\text{FN}}$\n\n$\\text{TPR} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}}$\n\nA classifier that always predict the positive class would have no true\nnegatives nor false negatives, giving $\\text{FPR} = \\text{TPR} = 1$ and\n$\\text{FNR} = 0$, i.e.:\n\n- a single point in the upper right corner of the ROC plane,\n- a single point in the lower right corner of the DET plane.\n\nSimilarly, a classifier that always predict the negative class would have no\ntrue positives nor false positives, thus $\\text{FPR} = \\text{TPR} = 0$\nand $\\text{FNR} = 1$, i.e.:\n\n- a single point in the lower left corner of the ROC plane,\n- a single point in the upper left corner of the DET plane.\n\n"
      ]
    }
  ],
  "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.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}