{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Face completion with a multi-output estimators\n\nThis example shows the use of multi-output estimator to complete images.\nThe goal is to predict the lower half of a face given its upper half.\n\nThe first column of images shows true faces. The next columns illustrate\nhow extremely randomized trees, k nearest neighbors, linear\nregression and ridge regression complete the lower half of those faces.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.linear_model import LinearRegression, RidgeCV\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.utils.validation import check_random_state\n\n# Load the faces datasets\ndata, targets = fetch_olivetti_faces(return_X_y=True)\n\ntrain = data[targets < 30]\ntest = data[targets >= 30]  # Test on independent people\n\n# Test on a subset of people\nn_faces = 5\nrng = check_random_state(4)\nface_ids = rng.randint(test.shape[0], size=(n_faces,))\ntest = test[face_ids, :]\n\nn_pixels = data.shape[1]\n# Upper half of the faces\nX_train = train[:, : (n_pixels + 1) // 2]\n# Lower half of the faces\ny_train = train[:, n_pixels // 2 :]\nX_test = test[:, : (n_pixels + 1) // 2]\ny_test = test[:, n_pixels // 2 :]\n\n# Fit estimators\nESTIMATORS = {\n    \"Extra trees\": ExtraTreesRegressor(\n        n_estimators=10, max_features=32, random_state=0\n    ),\n    \"K-nn\": KNeighborsRegressor(),\n    \"Linear regression\": LinearRegression(),\n    \"Ridge\": RidgeCV(),\n}\n\ny_test_predict = dict()\nfor name, estimator in ESTIMATORS.items():\n    estimator.fit(X_train, y_train)\n    y_test_predict[name] = estimator.predict(X_test)\n\n# Plot the completed faces\nimage_shape = (64, 64)\n\nn_cols = 1 + len(ESTIMATORS)\nplt.figure(figsize=(2.0 * n_cols, 2.26 * n_faces))\nplt.suptitle(\"Face completion with multi-output estimators\", size=16)\n\nfor i in range(n_faces):\n    true_face = np.hstack((X_test[i], y_test[i]))\n\n    if i:\n        sub = plt.subplot(n_faces, n_cols, i * n_cols + 1)\n    else:\n        sub = plt.subplot(n_faces, n_cols, i * n_cols + 1, title=\"true faces\")\n\n    sub.axis(\"off\")\n    sub.imshow(\n        true_face.reshape(image_shape), cmap=plt.cm.gray, interpolation=\"nearest\"\n    )\n\n    for j, est in enumerate(sorted(ESTIMATORS)):\n        completed_face = np.hstack((X_test[i], y_test_predict[est][i]))\n\n        if i:\n            sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j)\n\n        else:\n            sub = plt.subplot(n_faces, n_cols, i * n_cols + 2 + j, title=est)\n\n        sub.axis(\"off\")\n        sub.imshow(\n            completed_face.reshape(image_shape),\n            cmap=plt.cm.gray,\n            interpolation=\"nearest\",\n        )\n\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.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}