{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Linear and Quadratic Discriminant Analysis with covariance ellipsoid\n\nThis example plots the covariance ellipsoids of each class and the decision boundary\nlearned by :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis` (LDA) and\n:class:`~sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis` (QDA). The\nellipsoids display the double standard deviation for each class. With LDA, the standard\ndeviation is the same for all the classes, while each class has its own standard\ndeviation with QDA.\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": [
        "## Data generation\n\nFirst, we define a function to generate synthetic data. It creates two blobs centered\nat `(0, 0)` and `(1, 1)`. Each blob is assigned a specific class. The dispersion of\nthe blob is controlled by the parameters `cov_class_1` and `cov_class_2`, that are the\ncovariance matrices used when generating the samples from the Gaussian distributions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\n\ndef make_data(n_samples, n_features, cov_class_1, cov_class_2, seed=0):\n    rng = np.random.RandomState(seed)\n    X = np.concatenate(\n        [\n            rng.randn(n_samples, n_features) @ cov_class_1,\n            rng.randn(n_samples, n_features) @ cov_class_2 + np.array([1, 1]),\n        ]\n    )\n    y = np.concatenate([np.zeros(n_samples), np.ones(n_samples)])\n    return X, y"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We generate three datasets. In the first dataset, the two classes share the same\ncovariance matrix, and this covariance matrix has the specificity of being spherical\n(isotropic). The second dataset is similar to the first one but does not enforce the\ncovariance to be spherical. Finally, the third dataset has a non-spherical covariance\nmatrix for each class.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "covariance = np.array([[1, 0], [0, 1]])\nX_isotropic_covariance, y_isotropic_covariance = make_data(\n    n_samples=1_000,\n    n_features=2,\n    cov_class_1=covariance,\n    cov_class_2=covariance,\n    seed=0,\n)\ncovariance = np.array([[0.0, -0.23], [0.83, 0.23]])\nX_shared_covariance, y_shared_covariance = make_data(\n    n_samples=300,\n    n_features=2,\n    cov_class_1=covariance,\n    cov_class_2=covariance,\n    seed=0,\n)\ncov_class_1 = np.array([[0.0, -1.0], [2.5, 0.7]]) * 2.0\ncov_class_2 = cov_class_1.T\nX_different_covariance, y_different_covariance = make_data(\n    n_samples=300,\n    n_features=2,\n    cov_class_1=cov_class_1,\n    cov_class_2=cov_class_2,\n    seed=0,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Plotting Functions\n\nThe code below is used to plot several pieces of information from the estimators used,\ni.e., :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis` (LDA) and\n:class:`~sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis` (QDA). The\ndisplayed information includes:\n\n- the decision boundary based on the probability estimate of the estimator;\n- a scatter plot with circles representing the well-classified samples;\n- a scatter plot with crosses representing the misclassified samples;\n- the mean of each class, estimated by the estimator, marked with a star;\n- the estimated covariance represented by an ellipse at 2 standard deviations from the\n  mean.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib as mpl\nfrom matplotlib import colors\n\nfrom sklearn.inspection import DecisionBoundaryDisplay\n\n\ndef plot_ellipse(mean, cov, color, ax):\n    v, w = np.linalg.eigh(cov)\n    u = w[0] / np.linalg.norm(w[0])\n    angle = np.arctan(u[1] / u[0])\n    angle = 180 * angle / np.pi  # convert to degrees\n    # filled Gaussian at 2 standard deviation\n    ell = mpl.patches.Ellipse(\n        mean,\n        2 * v[0] ** 0.5,\n        2 * v[1] ** 0.5,\n        angle=180 + angle,\n        facecolor=color,\n        edgecolor=\"black\",\n        linewidth=2,\n    )\n    ell.set_clip_box(ax.bbox)\n    ell.set_alpha(0.4)\n    ax.add_artist(ell)\n\n\ndef plot_result(estimator, X, y, ax):\n    cmap = colors.ListedColormap([\"tab:red\", \"tab:blue\"])\n    DecisionBoundaryDisplay.from_estimator(\n        estimator,\n        X,\n        response_method=\"predict_proba\",\n        plot_method=\"pcolormesh\",\n        ax=ax,\n        cmap=\"RdBu\",\n        alpha=0.3,\n    )\n    DecisionBoundaryDisplay.from_estimator(\n        estimator,\n        X,\n        response_method=\"predict_proba\",\n        plot_method=\"contour\",\n        ax=ax,\n        alpha=1.0,\n        levels=[0.5],\n    )\n    y_pred = estimator.predict(X)\n    X_right, y_right = X[y == y_pred], y[y == y_pred]\n    X_wrong, y_wrong = X[y != y_pred], y[y != y_pred]\n    ax.scatter(X_right[:, 0], X_right[:, 1], c=y_right, s=20, cmap=cmap, alpha=0.5)\n    ax.scatter(\n        X_wrong[:, 0],\n        X_wrong[:, 1],\n        c=y_wrong,\n        s=30,\n        cmap=cmap,\n        alpha=0.9,\n        marker=\"x\",\n    )\n    ax.scatter(\n        estimator.means_[:, 0],\n        estimator.means_[:, 1],\n        c=\"yellow\",\n        s=200,\n        marker=\"*\",\n        edgecolor=\"black\",\n    )\n\n    if isinstance(estimator, LinearDiscriminantAnalysis):\n        covariance = [estimator.covariance_] * 2\n    else:\n        covariance = estimator.covariance_\n    plot_ellipse(estimator.means_[0], covariance[0], \"tab:red\", ax)\n    plot_ellipse(estimator.means_[1], covariance[1], \"tab:blue\", ax)\n\n    ax.set_box_aspect(1)\n    ax.spines[\"top\"].set_visible(False)\n    ax.spines[\"bottom\"].set_visible(False)\n    ax.spines[\"left\"].set_visible(False)\n    ax.spines[\"right\"].set_visible(False)\n    ax.set(xticks=[], yticks=[])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Comparison of LDA and QDA\n\nWe compare the two estimators LDA and QDA on all three datasets.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nfrom sklearn.discriminant_analysis import (\n    LinearDiscriminantAnalysis,\n    QuadraticDiscriminantAnalysis,\n)\n\nfig, axs = plt.subplots(nrows=3, ncols=2, sharex=\"row\", sharey=\"row\", figsize=(8, 12))\n\nlda = LinearDiscriminantAnalysis(solver=\"svd\", store_covariance=True)\nqda = QuadraticDiscriminantAnalysis(solver=\"svd\", store_covariance=True)\n\nfor ax_row, X, y in zip(\n    axs,\n    (X_isotropic_covariance, X_shared_covariance, X_different_covariance),\n    (y_isotropic_covariance, y_shared_covariance, y_different_covariance),\n):\n    lda.fit(X, y)\n    plot_result(lda, X, y, ax_row[0])\n    qda.fit(X, y)\n    plot_result(qda, X, y, ax_row[1])\n\naxs[0, 0].set_title(\"Linear Discriminant Analysis\")\naxs[0, 0].set_ylabel(\"Data with fixed and spherical covariance\")\naxs[1, 0].set_ylabel(\"Data with fixed covariance\")\naxs[0, 1].set_title(\"Quadratic Discriminant Analysis\")\naxs[2, 0].set_ylabel(\"Data with varying covariances\")\nfig.suptitle(\n    \"Linear Discriminant Analysis vs Quadratic Discriminant Analysis\",\n    y=0.94,\n    fontsize=15,\n)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The first important thing to notice is that LDA and QDA are equivalent for the\nfirst and second datasets. Indeed, the major difference is that LDA assumes\nthat the covariance matrix of each class is equal, while QDA estimates a\ncovariance matrix per class. Since in these cases the data generative process\nhas the same covariance matrix for both classes, QDA estimates two covariance\nmatrices that are (almost) equal and therefore equivalent to the covariance\nmatrix estimated by LDA.\n\nIn the first dataset the covariance matrix used to generate the dataset is\nspherical, which results in a discriminant boundary that aligns with the\nperpendicular bisector between the two means. This is no longer the case for\nthe second dataset. The discriminant boundary only passes through the middle\nof the two means.\n\nFinally, in the third dataset, we observe the real difference between LDA and\nQDA. QDA fits two covariance matrices and provides a non-linear discriminant\nboundary, whereas LDA underfits since it assumes that both classes share a\nsingle covariance matrix.\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
}