{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Faces recognition example using eigenfaces and kernel approximation\n\nThis example builds a classical face recognition pipeline on the \"Labeled Faces\nin the Wild\" (LFW) dataset, a preprocessed excerpt of which is available here:\nhttps://www.kaggle.com/datasets/jessicali9530/lfw-dataset\n\nWe reduce the dimensionality of the face images with PCA (the eigenfaces), then\napproximate the RBF kernel with :class:`~sklearn.kernel_approximation.Nystroem`\nand train a :class:`~sklearn.linear_model.LogisticRegression` on the resulting\nfeatures. The full chain is wrapped in a :class:`~sklearn.pipeline.Pipeline` so\nthat cross-validation does not leak information from the test set. The\nhyperparameters are tuned with a successive halving search\n(:class:`~sklearn.model_selection.HalvingRandomSearchCV`) that minimizes the\nlog loss. We finally evaluate the model both quantitatively, with a\nclassification report and one-vs-rest ROC and precision-recall curves, and\nqualitatively, by displaying the predictions and the eigenfaces.\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": [
        "## Loading the dataset\n\nWe download the Labeled Faces in the Wild (LFW) dataset and load it as numpy\narrays. Each sample is a flattened grayscale image; the target is the identity\nof the person pictured.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.datasets import fetch_lfw_people\n\nlfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)\n\n# Introspect the image arrays to find the shapes (for plotting).\nn_samples, height, width = lfw_people.images.shape\n\n# For machine learning we use the data directly (relative pixel positions are\n# ignored by this model).\nX = lfw_people.data\nn_features = X.shape[1]\n\n# The label to predict is the id of the person.\ny = lfw_people.target\ntarget_names = lfw_people.target_names\nn_classes = target_names.shape[0]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(\"Total dataset size:\")\nprint(f\"n_samples: {n_samples}\")\nprint(f\"n_features: {n_features}\")\nprint(f\"n_classes: {n_classes}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Splitting the dataset\n\nWe hold out 25% of the data for testing. Preprocessing and model fitting are\nchained in a pipeline below so that scaling and feature extraction are learned\nonly from the training folds during cross-validation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.25, random_state=42\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Building the model pipeline\n\nWe chain preprocessing and classification in a\n:class:`~sklearn.pipeline.Pipeline`. PCA extracts eigenfaces as a compact\nrepresentation; :class:`~sklearn.kernel_approximation.Nystroem` approximates\nthe RBF feature map so that a linear\n:class:`~sklearn.linear_model.LogisticRegression` can model non-linear\ndecision boundaries while scaling better than a kernel SVM. Because logistic\nregression outputs calibrated probabilities, we can tune the model by\nminimizing the log loss.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.decomposition import PCA\nfrom sklearn.kernel_approximation import Nystroem\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nn_components = 150\n\nmodel = Pipeline(\n    steps=[\n        (\"scaler\", StandardScaler()),\n        (\"pca\", PCA(n_components=n_components, svd_solver=\"randomized\", whiten=True)),\n        (\"nystroem\", Nystroem(random_state=42)),\n        (\"logreg\", LogisticRegression(max_iter=5_000)),\n    ]\n)\nmodel"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Tuning the pipeline with successive halving\n\nWe tune the ``gamma`` and ``n_components`` of the Nystroem approximation and\nthe ``C`` regularization of the logistic regression with a successive halving\nsearch (:class:`~sklearn.model_selection.HalvingRandomSearchCV`). The search\nminimizes the log loss (``neg_log_loss``) and screens many candidates on small\ntraining subsets before investing compute in the most promising ones. We set\n``min_resources`` high enough so that PCA can always extract 150 eigenfaces,\neven in the first halving iteration.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from time import time\n\nfrom scipy.stats import loguniform, randint\n\nfrom sklearn.experimental import enable_halving_search_cv  # noqa: F401\nfrom sklearn.model_selection import HalvingRandomSearchCV\n\nprint(\"Fitting the classifier to the training set\")\nt0 = time()\nparam_distributions = {\n    \"nystroem__gamma\": loguniform(1e-4, 1e-1),\n    \"nystroem__n_components\": randint(50, 200),\n    \"logreg__C\": loguniform(1e-2, 1e2),\n}\nclf = HalvingRandomSearchCV(\n    model,\n    param_distributions,\n    n_candidates=30,\n    factor=3,\n    min_resources=300,\n    scoring=\"neg_log_loss\",\n    random_state=42,\n)\nclf = clf.fit(X_train, y_train)\nprint(f\"done in {time() - t0:.3f}s\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(\"Best estimator found by successive halving search:\")\nclf.best_estimator_"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Quantitative evaluation\n\nWe measure the model quality on the held-out test set with a classification\nreport and, since the probabilities are well calibrated, one-vs-rest ROC and\nprecision-recall curves. The pipeline handles preprocessing internally.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.preprocessing import label_binarize\n\nprint(\"Predicting people's names on the test set\")\nt0 = time()\ny_pred = clf.predict(X_test)\ny_score = clf.predict_proba(X_test)\nprint(f\"done in {time() - t0:.3f}s\")\n\nprint(classification_report(y_test, y_pred, target_names=target_names))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Because the problem is multiclass, we summarize the ranking quality of the\npredicted probabilities with one-vs-rest curves: each identity is in turn\ntreated as the positive class against all the others. The ROC curve relates the\ntrue positive rate to the false positive rate, while the precision-recall curve\nis more informative when the positive class is rare, as is the case here where\neach identity is a small fraction of the test set.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay\n\nclasses = list(range(n_classes))\ny_onehot_test = label_binarize(y_test, classes=classes)\n\nfig, (ax_roc, ax_pr) = plt.subplots(1, 2, figsize=(13, 6))\n\nfor class_id, name in enumerate(target_names):\n    RocCurveDisplay.from_predictions(\n        y_onehot_test[:, class_id],\n        y_score[:, class_id],\n        name=name,\n        ax=ax_roc,\n        plot_chance_level=(class_id == n_classes - 1),\n    )\n    PrecisionRecallDisplay.from_predictions(\n        y_onehot_test[:, class_id],\n        y_score[:, class_id],\n        name=name,\n        ax=ax_pr,\n    )\n\nax_roc.set_title(\"One-vs-rest ROC curves\")\nax_pr.set_title(\"One-vs-rest precision-recall curves\")\nplt.tight_layout()\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Qualitative evaluation\n\nWe visualize a gallery of test portraits with their predicted and true labels\nto inspect the model's mistakes at a glance.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_gallery(images, titles, height, width, n_row=3, n_col=4):\n    \"\"\"Plot a gallery of portraits.\"\"\"\n    fig, axs = plt.subplots(n_row, n_col, figsize=(1.8 * n_col, 2.4 * n_row))\n    fig.subplots_adjust(bottom=0, left=0.01, right=0.99, top=0.90, hspace=0.35)\n    for ax, image, title in zip(axs.ravel(), images, titles):\n        ax.imshow(image.reshape((height, width)), cmap=plt.cm.gray)\n        ax.set_title(title, size=12)\n        ax.set_xticks(())\n        ax.set_yticks(())\n    return fig\n\n\ndef make_title(y_pred, y_test, target_names, i):\n    pred_name = target_names[y_pred[i]].rsplit(\" \", 1)[-1]\n    true_name = target_names[y_test[i]].rsplit(\" \", 1)[-1]\n    return f\"predicted: {pred_name}\\ntrue:      {true_name}\"\n\n\nprediction_titles = [\n    make_title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])\n]\n\nplot_gallery(X_test, prediction_titles, height, width)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Eigenfaces gallery\n\nWe display the most significant eigenfaces, i.e. the principal components that\nform the basis of the face representation learned by the fitted pipeline.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pca = clf.best_estimator_.named_steps[\"pca\"]\neigenfaces = pca.components_.reshape((pca.n_components_, height, width))\n\neigenface_titles = [f\"eigenface {i}\" for i in range(eigenfaces.shape[0])]\nplot_gallery(eigenfaces, eigenface_titles, height, width)\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Conclusion\n\nThis example walks through a classical face recognition pipeline in scikit-learn:\n\n- **Eigenfaces (PCA)** reduce the high-dimensional pixel space to a compact set\n  of uncorrelated features that capture the main variations across faces.\n- **Nystroem + LogisticRegression** approximate a non-linear RBF kernel with a\n  linear model that scales better than a kernel SVM and is tuned to minimize\n  the log loss.\n- **Pipeline** chains preprocessing and classification so that cross-validation\n  does not leak information from the test set.\n- **Quantitative and qualitative evaluation** on a held-out test set confirm\n  whether the pipeline generalizes. The one-vs-rest ROC and precision-recall\n  curves show how well the predicted probabilities rank each identity against\n  the others, independently of any single decision threshold.\n\nIn practice, face recognition is often better addressed with convolutional\nneural networks, but this family of models is outside the scope of the\nscikit-learn library. Interested readers should instead try PyTorch or\nTensorFlow to implement such models.\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.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}