{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Face completion with a multi-output estimators\n\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, linear regression, ridge regression,\nand k nearest neighbors with or without hubness reduction\ncomplete the lower half of those faces.\n\n\nAdapted from `<https://scikit-learn.org/stable/auto_examples/plot_multioutput_face_completion.html>`_\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(__doc__)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.utils.validation import check_random_state\n\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import RidgeCV\n\nfrom skhubness.neighbors import KNeighborsRegressor\n\n# Load the faces datasets\ndata = fetch_olivetti_faces()\ntargets = data.target\n\ndata = data.images.reshape((len(data.images), -1))\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_estimators=10, max_features=32,\n                                       random_state=0),\n    \"k-NN\": KNeighborsRegressor(weights='distance'),\n    \"k-NN MP\": KNeighborsRegressor(hubness='mp',\n                                   hubness_params={'method': 'normal'},\n                                   weights='distance'),\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. * 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,\n                          title=\"true faces\")\n\n    sub.axis(\"off\")\n    sub.imshow(true_face.reshape(image_shape),\n               cmap=plt.cm.gray,\n               interpolation=\"nearest\")\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,\n                              title=est)\n\n        sub.axis(\"off\")\n        sub.imshow(completed_face.reshape(image_shape),\n                   cmap=plt.cm.gray,\n                   interpolation=\"nearest\")\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.7.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}