{ "metadata": { "name": "04_houses_regression" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Supervised Learning: Regression of Housing Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By the end of this section you will\n", "\n", "- Know how to instantiate a scikit-learn regression model\n", "- Know how to train a regressor by calling the `fit(...)` method\n", "- Know how to predict new labels by calling the `predict(...)` method\n", "\n", "Here we'll do a short example of a regression problem: learning a continuous value\n", "from a set of features.\n", "\n", "We'll use the simple Boston house prices set, available in scikit-learn. This\n", "records measurements of 13 attributes of housing markets around Boston, as well\n", "as the median price. The question is: can you predict the price of a new\n", "market given its attributes?\n", "\n", "First we'll load the dataset:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.datasets import load_boston\n", "data = load_boston()\n", "print data.keys()" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that there are just over 500 data points:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print data.data.shape\n", "print data.target.shape" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The ``DESCR`` variable has a long description of the dataset:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print data.DESCR" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It often helps to quickly visualize pieces of the data using histograms, scatter plots,\n", "or other plot types. Here we'll load pylab and show a histogram of the target values:\n", "the median price in each neighborhood." ] }, { "cell_type": "code", "collapsed": false, "input": [ "%pylab inline" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.hist(data.target)\n", "plt.xlabel('price ($1000s)')\n", "plt.ylabel('count')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Quick Exercise:** Try some scatter plots of the features versus the target.\n", "\n", "Are there any features that seem to have a strong correlation with the\n", "target value? Any that don't?\n", "\n", "Remember, you can get at the data columns using:\n", "\n", " column_i = data.data[:, i]" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a manual version of a technique called **feature selection**.\n", "\n", "Sometimes, in Machine Learning it is useful to use \n", "feature selection to decide which features are most useful for a\n", "particular problem. Automated methods exist which quantify this sort\n", "of exercise of choosing the most informative features. We won't cover\n", "feature selection in this tutorial, but you can read about it elsewhere." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Predicting Home Prices: a Simple Linear Regression" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we'll use ``scikit-learn`` to perform a simple linear regression\n", "on the housing data. There are many possibilities of regressors to\n", "use. A particularly simple one is ``LinearRegression``: this is\n", "basically a wrapper around an ordinary least squares calculation.\n", "\n", "We'll set it up like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.linear_model import LinearRegression\n", "\n", "clf = LinearRegression()\n", "\n", "clf.fit(data.data, data.target)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "predicted = clf.predict(data.data)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "plt.scatter(data.target, predicted)\n", "plt.plot([0, 50], [0, 50], '--k')\n", "plt.axis('tight')\n", "plt.xlabel('True price ($1000s)')\n", "plt.ylabel('Predicted price ($1000s)')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The prediction at least correlates with the true price, though there\n", "are clearly some biases. We could imagine evaluating the performance\n", "of the regressor by, say, computing the RMS residuals between the\n", "true and predicted price. There are some subtleties in this, however,\n", "which we'll cover in a later section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many examples of regression-type problems in machine learning\n", "\n", "- **Sales:** given consumer data, predict how much they will spend\n", "- **Advertising:** given information about a user, predict the click-through rate for a web ad.\n", "- **Collaborative Filtering:** given a collection of user-ratings for movies, predict preferences for other movies & users\n", "- **Astronomy:** given observations of galaxies, predict their mass or redshift\n", "\n", "And much, much more." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Exercise: Decision Tree Regression" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many other types of regressors available in scikit-learn:\n", "we'll try one more here.\n", "\n", "**Use the DecisionTreeRegressor class to fit the housing data**.\n", "\n", "You can copy and paste some of the above code, replacing `LinearRegression`\n", "with `DecisionTreeRegressor`." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.tree import DecisionTreeRegressor\n", "# Instantiate the model, fit the results, and scatter in vs. out" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do you see anything surprising in the results?\n", "\n", "The Decision Tree classifier is an example of an *instance-based* algorithm.\n", "Rather than try to determine a model that best fits the data, an instance-based\n", "algorithm in some way matches unknown data to the known catalog of training points.\n", "\n", "How does this fact explain the results you saw here?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll return to the subject of Decision trees at a later point in the tutorial." ] } ], "metadata": {} } ] }