{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Isotonic Regression\n\n\nAn illustration of the isotonic regression on generated data. The\nisotonic regression finds a non-decreasing approximation of a function\nwhile minimizing the mean squared error on the training data. The benefit\nof such a model is that it does not assume any form for the target\nfunction such as linearity. For comparison a linear regression is also\npresented.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(__doc__)\n\n# Author: Nelle Varoquaux <nelle.varoquaux@gmail.com>\n#         Alexandre Gramfort <alexandre.gramfort@inria.fr>\n# License: BSD\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.isotonic import IsotonicRegression\nfrom sklearn.utils import check_random_state\n\nn = 100\nx = np.arange(n)\nrs = check_random_state(0)\ny = rs.randint(-50, 50, size=(n,)) + 50. * np.log1p(np.arange(n))\n\n# #############################################################################\n# Fit IsotonicRegression and LinearRegression models\n\nir = IsotonicRegression()\n\ny_ = ir.fit_transform(x, y)\n\nlr = LinearRegression()\nlr.fit(x[:, np.newaxis], y)  # x needs to be 2d for LinearRegression\n\n# #############################################################################\n# Plot result\n\nsegments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]\nlc = LineCollection(segments, zorder=0)\nlc.set_array(np.ones(len(y)))\nlc.set_linewidths(np.full(n, 0.5))\n\nfig = plt.figure()\nplt.plot(x, y, 'r.', markersize=12)\nplt.plot(x, y_, 'g.-', markersize=12)\nplt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')\nplt.gca().add_collection(lc)\nplt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')\nplt.title('Isotonic regression')\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.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}