mirror of
https://github.com/donnemartin/data-science-ipython-notebooks.git
synced 2024-03-22 13:30:56 +08:00
1055 lines
256 KiB
Python
1055 lines
256 KiB
Python
|
{
|
||
|
"cells": [
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Validation and Model Selection"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Credits: Forked from [PyCon 2015 Scikit-learn Tutorial](https://github.com/jakevdp/sklearn_pycon2015) by Jake VanderPlas\n",
|
||
|
"\n",
|
||
|
"In this section, we'll look at *model evaluation* and the tuning of *hyperparameters*, which are parameters that define the model."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 1,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"from __future__ import print_function, division\n",
|
||
|
"\n",
|
||
|
"%matplotlib inline\n",
|
||
|
"import numpy as np\n",
|
||
|
"import matplotlib.pyplot as plt\n",
|
||
|
"\n",
|
||
|
"# Use seaborn for plotting defaults\n",
|
||
|
"import seaborn as sns; sns.set()"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Validating Models\n",
|
||
|
"\n",
|
||
|
"One of the most important pieces of machine learning is **model validation**: that is, checking how well your model fits a given dataset. But there are some pitfalls you need to watch out for.\n",
|
||
|
"\n",
|
||
|
"Consider the digits example we've been looking at previously. How might we check how well our model fits the data?"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 2,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"from sklearn.datasets import load_digits\n",
|
||
|
"digits = load_digits()\n",
|
||
|
"X = digits.data\n",
|
||
|
"y = digits.target"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Let's fit a K-neighbors classifier"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 3,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',\n",
|
||
|
" metric_params=None, n_neighbors=1, p=2, weights='uniform')"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 3,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from sklearn.neighbors import KNeighborsClassifier\n",
|
||
|
"knn = KNeighborsClassifier(n_neighbors=1)\n",
|
||
|
"knn.fit(X, y)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now we'll use this classifier to *predict* labels for the data"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 4,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"y_pred = knn.predict(X)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Finally, we can check how well our prediction did:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 5,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stdout",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"1797 / 1797 correct\n"
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"print(\"{0} / {1} correct\".format(np.sum(y == y_pred), len(y)))"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"It seems we have a perfect classifier!\n",
|
||
|
"\n",
|
||
|
"**Question: what's wrong with this?**"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Validation Sets\n",
|
||
|
"\n",
|
||
|
"Above we made the mistake of testing our data on the same set of data that was used for training. **This is not generally a good idea**. If we optimize our estimator this way, we will tend to **over-fit** the data: that is, we learn the noise.\n",
|
||
|
"\n",
|
||
|
"A better way to test a model is to use a hold-out set which doesn't enter the training. We've seen this before using scikit-learn's train/test split utility:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 6,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"((1347, 64), (450, 64))"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 6,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from sklearn.cross_validation import train_test_split\n",
|
||
|
"X_train, X_test, y_train, y_test = train_test_split(X, y)\n",
|
||
|
"X_train.shape, X_test.shape"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now we train on the training data, and validate on the test data:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 7,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stdout",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"438 / 450 correct\n"
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"knn = KNeighborsClassifier(n_neighbors=1)\n",
|
||
|
"knn.fit(X_train, y_train)\n",
|
||
|
"y_pred = knn.predict(X_test)\n",
|
||
|
"print(\"{0} / {1} correct\".format(np.sum(y_test == y_pred), len(y_test)))"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This gives us a more reliable estimate of how our model is doing.\n",
|
||
|
"\n",
|
||
|
"The metric we're using here, comparing the number of matches to the total number of samples, is known as the **accuracy score**, and can be computed using the following routine:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 8,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"0.97333333333333338"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 8,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from sklearn.metrics import accuracy_score\n",
|
||
|
"accuracy_score(y_test, y_pred)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This can also be computed directly from the ``model.score`` method:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 9,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"0.97333333333333338"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 9,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"knn.score(X_test, y_test)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Using this, we can ask how this changes as we change the model parameters, in this case the number of neighbors:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 10,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stdout",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"1 0.973333333333\n",
|
||
|
"5 0.982222222222\n",
|
||
|
"10 0.971111111111\n",
|
||
|
"20 0.955555555556\n",
|
||
|
"30 0.96\n"
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"for n_neighbors in [1, 5, 10, 20, 30]:\n",
|
||
|
" knn = KNeighborsClassifier(n_neighbors)\n",
|
||
|
" knn.fit(X_train, y_train)\n",
|
||
|
" print(n_neighbors, knn.score(X_test, y_test))"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"We see that in this case, a small number of neighbors seems to be the best option."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Cross-Validation\n",
|
||
|
"\n",
|
||
|
"One problem with validation sets is that you \"lose\" some of the data. Above, we've only used 3/4 of the data for the training, and used 1/4 for the validation. Another option is to use **2-fold cross-validation**, where we split the sample in half and perform the validation twice:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 11,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"((898, 64), (899, 64))"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 11,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"X1, X2, y1, y2 = train_test_split(X, y, test_size=0.5, random_state=0)\n",
|
||
|
"X1.shape, X2.shape"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 12,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"name": "stdout",
|
||
|
"output_type": "stream",
|
||
|
"text": [
|
||
|
"0.983296213808\n",
|
||
|
"0.982202447164\n"
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"print(KNeighborsClassifier(1).fit(X2, y2).score(X1, y1))\n",
|
||
|
"print(KNeighborsClassifier(1).fit(X1, y1).score(X2, y2))"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Thus a two-fold cross-validation gives us two estimates of the score for that parameter.\n",
|
||
|
"\n",
|
||
|
"Because this is a bit of a pain to do by hand, scikit-learn has a utility routine to help:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 13,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"0.97614938602520218"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 13,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from sklearn.cross_validation import cross_val_score\n",
|
||
|
"cv = cross_val_score(KNeighborsClassifier(1), X, y, cv=10)\n",
|
||
|
"cv.mean()"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### K-fold Cross-Validation\n",
|
||
|
"\n",
|
||
|
"Here we've used 2-fold cross-validation. This is just one specialization of $K$-fold cross-validation, where we split the data into $K$ chunks and perform $K$ fits, where each chunk gets a turn as the validation set.\n",
|
||
|
"We can do this by changing the ``cv`` parameter above. Let's do 10-fold cross-validation:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 14,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"text/plain": [
|
||
|
"array([ 0.93513514, 0.99453552, 0.97237569, 0.98888889, 0.96089385,\n",
|
||
|
" 0.98882682, 0.99441341, 0.98876404, 0.97175141, 0.96590909])"
|
||
|
]
|
||
|
},
|
||
|
"execution_count": 14,
|
||
|
"metadata": {},
|
||
|
"output_type": "execute_result"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"cross_val_score(KNeighborsClassifier(1), X, y, cv=10)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This gives us an even better idea of how well our model is doing."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Overfitting, Underfitting and Model Selection"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now that we've gone over the basics of validation, and cross-validation, it's time to go into even more depth regarding model selection.\n",
|
||
|
"\n",
|
||
|
"The issues associated with validation and \n",
|
||
|
"cross-validation are some of the most important\n",
|
||
|
"aspects of the practice of machine learning. Selecting the optimal model\n",
|
||
|
"for your data is vital, and is a piece of the problem that is not often\n",
|
||
|
"appreciated by machine learning practitioners.\n",
|
||
|
"\n",
|
||
|
"Of core importance is the following question:\n",
|
||
|
"\n",
|
||
|
"**If our estimator is underperforming, how should we move forward?**\n",
|
||
|
"\n",
|
||
|
"- Use simpler or more complicated model?\n",
|
||
|
"- Add more features to each observed data point?\n",
|
||
|
"- Add more training samples?\n",
|
||
|
"\n",
|
||
|
"The answer is often counter-intuitive. In particular, **Sometimes using a\n",
|
||
|
"more complicated model will give _worse_ results.** Also, **Sometimes adding\n",
|
||
|
"training data will not improve your results.** The ability to determine\n",
|
||
|
"what steps will improve your model is what separates the successful machine\n",
|
||
|
"learning practitioners from the unsuccessful."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### Illustration of the Bias-Variance Tradeoff\n",
|
||
|
"\n",
|
||
|
"For this section, we'll work with a simple 1D regression problem. This will help us to\n",
|
||
|
"easily visualize the data and the model, and the results generalize easily to higher-dimensional\n",
|
||
|
"datasets. We'll explore a simple **linear regression** problem.\n",
|
||
|
"This can be accomplished within scikit-learn with the `sklearn.linear_model` module.\n",
|
||
|
"\n",
|
||
|
"We'll create a simple nonlinear function that we'd like to fit"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 15,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"def test_func(x, err=0.5):\n",
|
||
|
" y = 10 - 1. / (x + 0.1)\n",
|
||
|
" if err > 0:\n",
|
||
|
" y = np.random.normal(y, err)\n",
|
||
|
" return y"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now let's create a realization of this dataset:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 16,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"def make_data(N=40, error=1.0, random_seed=1):\n",
|
||
|
" # randomly sample the data\n",
|
||
|
" np.random.seed(1)\n",
|
||
|
" X = np.random.random(N)[:, np.newaxis]\n",
|
||
|
" y = test_func(X.ravel(), error)\n",
|
||
|
" \n",
|
||
|
" return X, y"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 17,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFVCAYAAAA+OJwpAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAF2xJREFUeJzt3X+Q3Hddx/HnlaZdLNfCwCKoKCLyUQcZRrFwAZJ2kFgI\nLQmQyRpbuA4/W+jUwnDQooyDMtMpAkIECgVykA5eptiLZIIxiOUinQNGBCkjvLE46IyjEiolEbsN\nbdc/dq/ZXHN7t3v747Pf7/Mx0+nu3X1vP+/udV/fz4/v5zvRaDSQJEmjdcaoGyBJkgxkSZKyYCBL\nkpQBA1mSpAwYyJIkZcBAliQpA2eu5YdSSs8Ero+IC1NKTwfeD9wP3Au8PCK+P8A2SpJUeKv2kFNK\nM8BNwNmtL/0Z8IaIuBC4FXjL4JonSVI5rGXI+k7gJcBE63ktIr7RerwBuGcQDZMkqUxWDeSIuBW4\nr+35fwGklDYCrwfeO7DWSZJUEmuaQ14upbQTuA54YUTctdrPNxqNxsTExGo/JklSUXQdel0Hckrp\nUuA1wAUR8cM1tWpigqNHj3f7UoVQrU6Wtnawfusvb/1lrh2sv1qd7PqYbi57aqSUzgDeBzwCuDWl\ndFtK6Y+6flVJknSKNfWQI+J7wMbW00cPrDWSJJWUG4NIkpQBA1mSpAwYyJIkZcBAliQpAwayJEkZ\nMJAlScqAgSxJUgYMZEmSMmAgS5KUAQNZkqQMGMiSJGXAQJYkKQMGsiRJGTCQJUnKgIEsSVIGDGRJ\nkjJgIEuSlAEDWZKkDJw56gZIUj/U63Xm5o4AUKttolKpjLhFUncMZEljr16vs3PnPIuLlwMwP7+H\nffu2G8oaKw5ZSxp7c3NHWmG8AdjA4uL0g71laVwYyJIkZcBA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{},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"X, y = make_data(40, error=1)\n",
|
||
|
"plt.scatter(X.ravel(), y);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now say we want to perform a regression on this data. Let's use the built-in linear regression function to compute a fit:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 18,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFeCAYAAABU/2zqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4lNdh7/GvVoZF7GLVsHjh2BizSjbCZjNI8RI7Jolj\nxbVbcpM2S5ubJmmcJl1unyZt09w2aeq2SZomJnXaQJ0GO37oJRJghO3ItsS+Hhu8MBIgiVUsGm0z\n94/3FQwChDTM8s7M7/M8fqxllnMYmN+7nPm9WeFwGBEREUmu7GQPQERERBTIIiIinqBAFhER8QAF\nsoiIiAcokEVERDxAgSwiIuIBuckegIgknjGmGHjeWjs12WO5FmPM/wIetdY+cpXfTQf+I+JHOcAM\n4MPW2heMMd8EHgPagFeAL1lr2xIwbJGoKZBFxFOMMSOBvwaeBDZd7TbW2n3AnIj7/D2wyw3jTwAP\nAPOsteeMMd8Fvgl8Je6DF7kBCmRJK8aYJcDfAA3AHcAF4P8A/xswwH9ba7/k3vZh4E+AfPd2f2St\nfd0YMxb4ITAGGAe8D3zMWttsjHkPeBZYBkwC1lhrv3qVcXwW+DTQDgSBT1tr9xtjFgHPAF3A6zjB\nsQSYCjxjrb0zYh7PWGvv7MN4XgdmAl8D6tzHnwTkAauttX8TMaY/BM4Ae3v5M1wAfAsYDISAv7DW\nrjPGrAQ+CQxy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+s/cYG+oCHD3h1FreNmk4ZSV+Zt08muxs\nHZb2ij4FsjHmbuBb1tqlxphbgFVACNgD/L61Nhy/IYqISH+dOtvGxq31VO9o4Hywk5zsLO6ZMY6y\nEj+TxhYke3hyFdcNZGP
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1096035c0>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"X_test = np.linspace(-0.1, 1.1, 500)[:, None]\n",
|
||
|
"\n",
|
||
|
"from sklearn.linear_model import LinearRegression\n",
|
||
|
"from sklearn.metrics import mean_squared_error\n",
|
||
|
"model = LinearRegression()\n",
|
||
|
"model.fit(X, y)\n",
|
||
|
"y_test = model.predict(X_test)\n",
|
||
|
"\n",
|
||
|
"plt.scatter(X.ravel(), y)\n",
|
||
|
"plt.plot(X_test.ravel(), y_test)\n",
|
||
|
"plt.title(\"mean squared error: {0:.3g}\".format(mean_squared_error(model.predict(X), y)));"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"We have fit a straight line to the data, but clearly this model is not a good choice. We say that this model is **biased**, or that it **under-fits** the data.\n",
|
||
|
"\n",
|
||
|
"Let's try to improve this by creating a more complicated model. We can do this by adding degrees of freedom, and computing a polynomial regression over the inputs. Scikit-learn makes this easy with the ``PolynomialFeatures`` preprocessor, which can be pipelined with a linear regression.\n",
|
||
|
"\n",
|
||
|
"Let's make a convenience routine to do this:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 19,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
|
"from sklearn.linear_model import LinearRegression\n",
|
||
|
"from sklearn.pipeline import make_pipeline\n",
|
||
|
"\n",
|
||
|
"def PolynomialRegression(degree=2, **kwargs):\n",
|
||
|
" return make_pipeline(PolynomialFeatures(degree),\n",
|
||
|
" LinearRegression(**kwargs))"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now we'll use this to fit a quadratic curve to the data."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 20,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFeCAYAAABU/2zqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl8VPW9//HXZB0SEiAhEPadLzuIuAQVRMUNF3AjWm2x\n7a2trbXW1v7a+7v39/vd2/u4vUt769W2Wm+FVluDGyIFKYoYFUEF2Zcv+xYghLAlIZP1/P6YCYYQ\nQjLMZM7MvJ+PBw+yzJn5fDPJeZ/v+X7P93gcx0FEREQiKyHSBYiIiIgCWURExBUUyCIiIi6gQBYR\nEXEBBbKIiIgLKJBFRERcICnSBYhI+zPGTABes9YOiHQtTRljhgAvAllAOfBVa61t5nFTgP/Evx87\nDnzfWrs+8L0ngYeBWqAEeMRau6t9WiASHPWQRcRt/gz8xlo7Evg/wBtNH2CM6QS8DjxhrR0L/AiY\nb4xJMcbcAHwduNJaOw54E5jdbtWLBEk9ZIkpxphrgX8FioCRwGn8O/XvAwZ4w1r7w8Bjbwf+HkgJ\nPO5H1tqVxpjuwPNANyAX2AvcZ60tMcbswb9zvx7oC8y11v6kmTq+AzwCVAM+/D20LcaYScAzQB2w\nErgFuBYYADxjrR3dqB3PWGtHt6KelcAY4KfAqsDz9wWSgQJr7b82qukHwElgUws/w4nAL4B0oB74\nv9bahcaYWcA3gLTAc/wR+Gbg8xPW2uuNMf8A5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IjU50LtNTiQ1OZHERA+JCQkkJHjO9IYTPOA4UBfoMdfV1/t7z3UOVbWB3nWVv7fd0Ouu\n8NVSeqqKAyUVLbapY4f
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x109451b00>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"model = PolynomialRegression(2)\n",
|
||
|
"model.fit(X, y)\n",
|
||
|
"y_test = model.predict(X_test)\n",
|
||
|
"\n",
|
||
|
"plt.scatter(X.ravel(), y)\n",
|
||
|
"plt.plot(X_test.ravel(), y_test)\n",
|
||
|
"plt.title(\"mean squared error: {0:.3g}\".format(mean_squared_error(model.predict(X), y)));"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This reduces the mean squared error, and makes a much better fit. What happens if we use an even higher-degree polynomial?"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 21,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFeCAYAAABU/2zqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3Xd8XHed7//XmVEZdVnFsiz3dtzj2E5xip0CISGFGAgW\nEIJDWWB3WRbYXxaWbXcX7u5m97L3LrtLWUIMIUROICYYpzgNO8WOU5zE9bj3pmb1kTQz5/fHzMiy\nrDIazTmjkd7PxyNgSXPOfI9mdD7z+XybYds2IiIiklyeZDdAREREFJBFRESGBQVkERGRYUABWURE\nZBhQQBYRERkGFJBFRESGgbRkN0BE3GGa5lLgCcuypia7LT2ZpjkT+BlQBDQD91mWZfXyuBuBB4F0\noA34M8uy3jRN81vAqm4PHQ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FxWygSkBNZsr7kXqbk2xFpsTzINM2rgH+2\nLOtG0zQXAf8BBIF24D7Lss452MaUo+kGIpIs0Qw5MSVr3cvcNGCGbJrmA8D/AJmRb/1f4E8ty7oR\neBL4S+eal5qifwcqWYuI2xJZshZ3xVKyPgB8lAsflSoty3o/8u90oM2JhqW0rt2ektsMERl9LpSs\nh94jqWKfuwZ8xSzLehIIdPv6DIBpmtcAfwL8u2OtS1FdJWtFZBFxWVfJWhlyyompD7kn0zRXAX8F\nfNiyrNpYjiktzYvnqVJSwalGAHJywlX+0XTtvdH16/pHM7evP+gJ51k52RlDfu5WfycA6RleSkvz\nyMjwAlBSkosvY+DwMdpf+8EadEA2TfNe4I+AGyzLqo/1uOrqpsE+VcpqavQD0NgU/v/RdO09lZbm\n6fp1/cluRtIk4/rP1bY
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x1093c27b8>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"model = PolynomialRegression(30)\n",
|
||
|
"model.fit(X, y)\n",
|
||
|
"y_test = model.predict(X_test)\n",
|
||
|
"\n",
|
||
|
"plt.scatter(X.ravel(), y)\n",
|
||
|
"plt.plot(X_test.ravel(), y_test)\n",
|
||
|
"plt.title(\"mean squared error: {0:.3g}\".format(mean_squared_error(model.predict(X), y)))\n",
|
||
|
"plt.ylim(-4, 14);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"When we increase the degree to this extent, it's clear that the resulting fit is no longer reflecting the true underlying distribution, but is more sensitive to the noise in the training data. For this reason, we call it a **high-variance model**, and we say that it **over-fits** the data."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Just for fun, let's use IPython's interact capability (only in IPython 2.0+) to explore this interactively:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 22,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFeCAYAAABU/2zqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl8XOV97/HPaB1blmXZGnnfbT1gsLElNkMwUBKyENIQ\nkqCk0JgmTZukudkaUpLbe9umS5o2aRN6S9M0wSlpK5o0TsIlJQtQSLmGFslgs/3k3cZga7RZkq3R\nOvePcyTLwpI14xnNmZnv+/XihWY0y/PMyOd7znPO73lC8XgcERERyayCTDdAREREFMgiIiKBoEAW\nEREJAAWyiIhIACiQRUREAkCBLCIiEgBFmW6AiEw/59ylwPfMbGWm2zKec+4y4K+BmUAh8Odm9k9n\nedzNwDbgsH9XHLjGzE465/4N2AD0+L971Mw+k+62i5wPBbKIBIZzLgR8H7jTzB51zi0GmpxzT5vZ\n3nEPvwr4CzP70lle6kqgzsyOpbnJIimjQJac4py7Dvgz4ChwEXAK+N/A/wAc8G9m9mn/sTcDXwBK\n/Mf9rpk95ZybD3wDqAYWAIeA95pZ1Dl3ELgPuAFYBjxgZp87Szs+AvwW0A/EgN8ys5ecc1uAe4Ah\n4CngrcB1wErgHjNbP6Yf95jZ+im05ym8o8G7gWf8118GFAMNZvZnY9r0SeAE8MIkn+FVwJeAMmAY\n+AMze8g5txX4IN6R6wngO8CH/NudZnaDc+73gXpgEGgGfsfMjjvn/gNoAy4A7vX78NtmdtO4ty/x\n3+9RADM76pxrBRYDZwvkfufcu/G+vy+Y2S+dcyuBcuAbzrkVQCPwGTPrmKjPIkGgc8iSiy4Fvmhm\nFwLH8YLqbUAt8DHn3ALn3FrgT4C3mlktXnj+wDk3E7gNeNLMrjKzVXgb+zv8144DZWa2BS8QPu6c\nWz72zZ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FRETkDFM6Qjazg8BV/s15aWuN\niIhIntLEICIiIgGgQBYREQkABbKIiEgAKJBFREQCQIEsIiISAApkERGRAFAgi4iIBIACWUREJACS\nmstaREQkiIaGh9n7ygnicbhgeWWmm5MQBbKIiGS1gcFhXjrUTqNF2bmnlZ7eAUqKCrj3M9cSCoXO\n/QIBoUAWEZGsE+sfZPf+dpqaozy3t5VY/xAAs8tKuG7TYt6wfmFWhTEokEVEJEv09A7w3N5WGi3K\n8wfaGRwaBqCqIsyWSxZR5yKsXlRBQUF2BfEIBbKIZLVYLEZDwxMA1NdvIRwOZ7hFkkod3X3s3BOl\n0aLY4U6G43EAFleVUVsToc5FWFo9K+uOhs9GgSwiWWN8+ALcdtt2duy4E4Dt2+/jgQduUShnuZaO\nUzQ1t9LY3MK+o12j969cOJs6F6G2JsKCuTMz2ML0UCCLSFaIxWKvC9+3v322f7sYgB07ttLQ8CBb\nt96YwZZKouLxOEejJ2ls9o6EX4n2ABAKwQXL5lBb44Xw3Nm5vaOlQBaRrNDQ8MTrwnfBgj/PbKMk\nacPxOAde66LJojQ2R2np6AWgqDDEhtXzqKuJcMnaKmbPLMlwS6ePAllEstall67h2LH72LFjKwCb\nN2+jvv6WzDZKJjQ0PEzz4U4am73ypI7uPgBKiwu59IJq6moibFg9jxml+RlN+dlrEck69fVb2L79\nzPC9445buOMOaGh40H+Mzh8HzcDgEC8c7KDJojy716sRBigLF3H1+gXU1VSzbkUlJcWFGW5p5imQ\nRSQrhMNhHnjglrOGr84ZB0tv3yC/3HmUx545zK79bfT5NcIVs0q4vnYxdTURapbOoahQszePpUAW\nkawRDocVvgHVfaqfZ/e20mRRXjjYMVojHJkTpm6TF8IrF82mIAfKk9JFgSwiWU11yJnT3hVj555W\nGq0FO9KJXyLMkkgZ12x
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x109ee9e48>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"from IPython.html.widgets import interact\n",
|
||
|
"\n",
|
||
|
"def plot_fit(degree=1, Npts=50):\n",
|
||
|
" X, y = make_data(Npts, error=1)\n",
|
||
|
" X_test = np.linspace(-0.1, 1.1, 500)[:, None]\n",
|
||
|
" \n",
|
||
|
" model = PolynomialRegression(degree=degree)\n",
|
||
|
" model.fit(X, y)\n",
|
||
|
" y_test = model.predict(X_test)\n",
|
||
|
"\n",
|
||
|
" plt.scatter(X.ravel(), y)\n",
|
||
|
" plt.plot(X_test.ravel(), y_test)\n",
|
||
|
" plt.ylim(-4, 14)\n",
|
||
|
" plt.title(\"mean squared error: {0:.2f}\".format(mean_squared_error(model.predict(X), y)))\n",
|
||
|
" \n",
|
||
|
"interact(plot_fit, degree=[1, 30], Npts=[2, 100]);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### Detecting Over-fitting with Validation Curves\n",
|
||
|
"\n",
|
||
|
"Clearly, computing the error on the training data is not enough (we saw this previously). As above, we can use **cross-validation** to get a better handle on how the model fit is working.\n",
|
||
|
"\n",
|
||
|
"Let's do this here, again using the ``validation_curve`` utility. To make things more clear, we'll use a slightly larger dataset:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 23,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeMAAAFVCAYAAADc5IdQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAH9FJREFUeJzt3X+Q3Gd92PH3ORwshcNk6FHoFJJLIU+bSTtM68o6J0gx\nThyMLEXCUF1cy75MbQImHo+TmQPs4ukAnoLSmLpu6wABny0POY+D5aIIFCeGSA2jmCENDZm0T+v2\nOp3pDKC4GKspiw64/rG30t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Jk8/fQvT09OZR/+/\n+7tnOXr0vdx113UcPHiU/ft3VKIIShk4MpY6pBx1FbEu8lYj9e511/37r+k5mq/bOm37ms3MNNiz\nZ0dh+9p9b7d6/T3xxLFa3buUDMZShzwC4iBVpIqo1weT9rrroB9exllIo8jXs/t6zM9P5sNc1muy\n1X279tqZLb+37EVQysJpailn7ZHh4cPHehZNKFpd5EGmg1NMGQ96PVNINYWe9Zps1U6YKtTrr24c\nGUsdxj3qypKQVbfp3FE4WrvYqNdkenra119CFv3IWZ03v5e17+PKaJ6ZmeZNb3p405TlQw9dwxNP\nfHnknz1O2/V3kAIZvb6nrPd/FJMsKjKKvNtZx3vfaZiiHwbjnNX5RVnnvgN85jOneNe7rqazqtHc\n3N2srn4QmNx6Yi/91jgH+WDy3HPP8Z73LAPwkY8s8vKXvxyY/P0vyrawsiZwjbOddf/dtwKXVHCr\nq/MUKVu6X8Jav6nPZrPJTTd9ntOn3wvA17+e5gNGkfYet69Z0QOSU/3FYgKXlJPFxas2JcTMzX0U\neFPiVo1XUfb8FqUd0rA
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x109edfba8>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"X, y = make_data(120, error=1.0)\n",
|
||
|
"plt.scatter(X, y);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 24,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"from sklearn.learning_curve import validation_curve\n",
|
||
|
"\n",
|
||
|
"def rms_error(model, X, y):\n",
|
||
|
" y_pred = model.predict(X)\n",
|
||
|
" return np.sqrt(np.mean((y - y_pred) ** 2))\n",
|
||
|
"\n",
|
||
|
"degree = np.arange(0, 18)\n",
|
||
|
"val_train, val_test = validation_curve(PolynomialRegression(), X, y,\n",
|
||
|
" 'polynomialfeatures__degree', degree, cv=7,\n",
|
||
|
" scoring=rms_error)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Now let's plot the validation curves:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 25,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAfQAAAFgCAYAAABNIYvfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XecZGd95/vPiZW7uzpNjppRjTIS0UILEsE2NtiYe8EB\nX4EBAwsY2yAjhFYSxmDtlVkEFgYjDItYkm0ul12EcVpjkkVSnpGmRhpNT+5cHSqe9OwfVR2qq6rD\nzFR3V/Xv/XrVVPU5Vaef0zPT3/OE8zyaUgohhBBCtDZ9rQsghBBCiPMngS6EEEK0AQl0IYQQog1I\noAshhBBtQAJdCCGEaAMS6EIIIUQbMNe6AMvleb7KZPJrXYzzlkxGkfNYH9rhHKA9zqMdzgHkPNaT\ndjgHgL6+hLbc97ZMDd00jbUuwgUh57F+tMM5QHucRzucA8h5rCftcA4r1TKB7vneWhdBCCGEWLda\nJtAd313rIgghhBDrVgsFurPWRRBCCCHWrdYJ9ECa3IUQQohGWibQAxXgSagLIYQQdbVMoAO4gfSj\nCyGEEPW0VKA7MtJdCCGEqKulAt2TGroQQqxrjuNw//3fXPb7v/Od+/nhD7/fcP+XvvQFnnzy0IUo\nWttrmZniQJrchRBivRsbG+Vb3/qfvPKVr17W+1/xilcuuv93f/eNF6BUG0OLBbo0uQshxHL93b89\nzc8OD6/4c4ah4fuq7r7nHujndS/Z1/CzX/zi5xkYeIYvfOFvCIKAxx9/lGKxwPvffzvf+c79pNNP\nMjk5yb59+/nAB+7gc5/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417veNi/Q56ZW/f73v0upVOTe\ne7/AxMQEv/Vb5TXVjx07xrve9Ufs3buPf/mXf+Tb3/4WN998K/v3X8yf/MkHMM25KLvrrjv59Kc/\nxyWX7OFTn/os9933Oa699rq6K7nN96//+k/cc8+99PT08A//8C0A/uIv/pwPfejP2blzN9/+9v/i\n+PFj3HXXn/P+99/Gvn37+eEPv8c999zNu971R4yPj/P5z38Z0zR561vfyK23fpBdu3Zz//3/ky9/\n+YtcccWVdHZ28V/+y58yMHCMYrFwwX/2rRvoMjBOCCEW9Zp9r1y0Nt3I+Uyb+rznvYBPfeoTTE1N\n8dhjj/Ce97yP0dER/u7vvsr3v/9vRKNxfN+v+9kTJ45z4MClAHR1dbFrV3kVtd7ePr7whc8RCoXI\n53PEYvG6n5+YmCAWi9Hb2wvAVVc9i3vv/RTXXnvdkiu53X77n/HpT/8l4+NjvOAF1wKQyYyxc+du\nAH71V38NgNHREfbt2w/AlVdezV//9ScB2LJl6+yFxYkTA3z0o3cC5YVeduzYyQte8EJOnjzJLbe8\nF9M0ufHGN6/sB7sMLTkoDsp96EIIIdYXXde54YaX8dGP3smLXnQ9mqbxta99icsvv4Lbbvszbrjh\npagGg5p3794zu2La1NQUJ0+eAOATn/gob37z27j11g+yd+++2VXadH1uZTcoXwTkcjnGxkYBeOSR\nh2aXPl1sJTfXdfnud/+VP/3TP+cv//Kv+c537mdwcJCenj5OnToJwFe+8kW+//1/p7e3j6NHn549\n/szysLo+F6c7duzitts+xD33fIa3ve2dvPCF5UVdenp6+djHPsmNN76Je+/9q5X+aJfUsjV0P/AJ\nVICutew1iRBCtKVf+ZVX8Vu/9Ru84x3/PwAvfOGL+PjH/4Lvf//f2bNnL9FoFNetbmXVNI3/9J+u\n56GHHuT3f/8N9Pb20d3dA8Av/dIruO22m+nv38SBA5fOBvbll1/JRz5yB3/yJx+Ybba/+eZbufXW\n92HbJpFIjFtv/SBHjz6
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x10a3f2518>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"def plot_with_err(x, data, **kwargs):\n",
|
||
|
" mu, std = data.mean(1), data.std(1)\n",
|
||
|
" lines = plt.plot(x, mu, '-', **kwargs)\n",
|
||
|
" plt.fill_between(x, mu - std, mu + std, edgecolor='none',\n",
|
||
|
" facecolor=lines[0].get_color(), alpha=0.2)\n",
|
||
|
"\n",
|
||
|
"plot_with_err(degree, val_train, label='training scores')\n",
|
||
|
"plot_with_err(degree, val_test, label='validation scores')\n",
|
||
|
"plt.xlabel('degree'); plt.ylabel('rms error')\n",
|
||
|
"plt.legend();"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Notice the trend here, which is common for this type of plot.\n",
|
||
|
"\n",
|
||
|
"1. For a small model complexity, the training error and validation error are very similar. This indicates that the model is **under-fitting** the data: it doesn't have enough complexity to represent the data. Another way of putting it is that this is a **high-bias** model.\n",
|
||
|
"\n",
|
||
|
"2. As the model complexity grows, the training and validation scores diverge. This indicates that the model is **over-fitting** the data: it has so much flexibility, that it fits the noise rather than the underlying trend. Another way of putting it is that this is a **high-variance** model.\n",
|
||
|
"\n",
|
||
|
"3. Note that the training score (nearly) always improves with model complexity. This is because a more complicated model can fit the noise better, so the model improves. The validation data generally has a sweet spot, which here is around 5 terms.\n",
|
||
|
"\n",
|
||
|
"Here's our best-fit model according to the cross-validation:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 26,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAeQAAAFVCAYAAAA+OJwpAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AA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8akMXmMKMik\nuCCDonw3hTluCnPTyUhP6TO5RWpQV0pyEoW5bgpz+946cvHiFWzcupi84jqmnbOa2ReM48OjDazf\ndpT1244CkJuVxhmThnHmpOFMLynAnZbS5+P4X9dr8bdM3EZXd4GEnxKySByI5wUthnqz0d7RwdHj\nzRysbOTAsQbeeHs37iklXDX3Jfw5NI9X3zkEQEFOOjNOKaQ4L50Pdx3AnQI3X38uo4pySU6KjVmi\n/puTTwCraa6DI7uu4cpZL/PlL1zGkeNNmP017Piwhm17j/PPTYf556bDpCS7mDaxkHMmF7Lzne0k\nJ4HX23pSywQ8D1ytefwRooQsEieitaDFRwlyCfB3SkrWcf31/zroeaH2Owdys9EV08Yti8kZXs/0\nc16jOb+E7/3pTQ5XNdLW3n16ZxKpbi/HDwyjviqXuspMbr/5Pe6642Iy3akfHXbF1IDicxqvtxV4\nHLiz8ycP4/Vm4XK5GDUsi1HDsph/1hg6fD72HK7jvV1VvLerkk0fVLHpgyravOkc3TUCb9U6oBl/\nQvYAL3LmmSu5+eZmbr89fm74nETzkCPMqfMQo0Xlj8/y19TUcMUVf2bPnq8A/a+H3FX+cK+fXNfU\nyp6D1Ty7chONbS4y8vM4XNWEp7W9x3FpqUmMGZ7FmOHZjCnKYmxRNsNzU/jsp56L2Hra3UX7+ns8\nHj7/+V/z9NPfpvuc7Hv
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x10a2f5ba8>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"model = PolynomialRegression(4).fit(X, y)\n",
|
||
|
"plt.scatter(X, y)\n",
|
||
|
"plt.plot(X_test, model.predict(X_test));"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"### Detecting Data Sufficiency with Learning Curves\n",
|
||
|
"\n",
|
||
|
"As you might guess, the exact turning-point of the tradeoff between bias and variance is highly dependent on the number of training points used. Here we'll illustrate the use of *learning curves*, which display this property.\n",
|
||
|
"\n",
|
||
|
"The idea is to plot the mean-squared-error for the training and test set as a function of *Number of Training Points*"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 27,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"from sklearn.learning_curve import learning_curve\n",
|
||
|
"\n",
|
||
|
"def plot_learning_curve(degree=3):\n",
|
||
|
" train_sizes = np.linspace(0.05, 1, 20)\n",
|
||
|
" N_train, val_train, val_test = learning_curve(PolynomialRegression(degree),\n",
|
||
|
" X, y, train_sizes, cv=5,\n",
|
||
|
" scoring=rms_error)\n",
|
||
|
" plot_with_err(N_train, val_train, label='training scores')\n",
|
||
|
" plot_with_err(N_train, val_test, label='validation scores')\n",
|
||
|
" plt.xlabel('Training Set Size'); plt.ylabel('rms error')\n",
|
||
|
" plt.ylim(0, 3)\n",
|
||
|
" plt.xlim(5, 80)\n",
|
||
|
" plt.legend()"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Let's see what the learning curves look like for a linear model:"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 28,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAfUAAAFkCAYAAAA5cqL3AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmAJGVh//93VfU903PsHLsLLLvAQi3IvQgEkUPwazQY\nj0SNMaJRI0ZjNGpE5Asag+H7M0Zj8Igg/EAlmkjQBIiamKiAXwG5zy1Y2OVednZ2dq4+6/j+Ud09\nP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wfa677mpOO+30eWeA\nq/azn/2UK664koGBAf7jP24C4G//9m/43Of+hoMPXsctt/w7Tz+9hS984W/41KcuYf36w7n99l9y\nxRVf5s/+7KPs3LmTa665nkgkwvvf/24uvvizrF27jptv/jeuv/7bHHPMsfT29vG///dfsXXrFnK5\nbEN+/kqpGmXcLD2xdLOLISLS0k4++VS+/vWvMDExwYMP3s/HPvZJduwY4V/+5Xvceuv/kEp143nz\nX6f0zDNPs2HDUQD09fWxdm04+9rg4BDXXns18XgczysQiew+gxvArl276OrqYnBwEIDjjjueK6/8\nOqeddvpeZ4C79NK/5hvf+Ad27hzl1FNPA2BsbJSDD14HwO/8zu8CsGPHCOvXHw7AsceewD/+41cB\nWL36gErl4plntvLFL14OhJPDrFlzMKee+gqeffZZLrro40QiEc4//72L+8HWSBfK1ShTbEytSkSk\nnZimydlnn8sXv3g5Z5x
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x10a42d400>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"plot_learning_curve(1)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"This shows a typical learning curve: for very few training points, there is a large separation between the training and test error, which indicates **over-fitting**. Given the same model, for a large number of training points, the training and testing errors converge, which indicates potential **under-fitting**.\n",
|
||
|
"\n",
|
||
|
"As you add more data points, the training error will never increase, and the testing error will never decrease (why do you think this is?)\n",
|
||
|
"\n",
|
||
|
"It is easy to see that, in this plot, if you'd like to reduce the MSE down to the nominal value of 1.0 (which is the magnitude of the scatter we put in when constructing the data), then adding more samples will *never* get you there. For $d=1$, the two curves have converged and cannot move lower. What about for a larger value of $d$?"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 29,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|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HEwfZh4PsGYf7TuvjKrnBBiWF1xxd/wile8\nmtNPP5OHHnqAG2+8gSuv/ABXX/13pFJJpqenePnLX8FLX1qezMurrNT2e7/3cq655u959NHfsn79\nBlKpFFCcc/3jH/9nHMcllYrzV3/1HuLxOL/97cN88IPv58orP8AHP/g+Pv3pf+fnP/8J11//r/h8\nPkZHR7nssvfx8MMPcdNNn1u0Aly1T3/6E9xzzy+xbYfzzruA1772T7j//vu49tqP4Louk5OTXHXV\nB3n88V388z9/GFVV8fn8XHrpFbiuy6WX/jWjo2M885nP5hnPeBYf+9iH8TyvVIaryOcLvO99l+F5\nHvl8nne/+7LKXPatJKHeoOrOco2EuhBCdNvLj7+oxbXqlV188cu4/fZbOf30M7nttlv43d99Gfv2\n7eV5z3sBz3nO+UxPT/EXf3FJVajPT8N61113kMtlue66zzI7O8sf/mFxTfZdu3bxF3/xVxx33PH8\n9Kd3ctttt3DppVdwwgkn8jd/czm6Ph9l11xzNZ/61A1MTEzwla98iRtvvIFnPeucJVeAq/bd736L\na6+9jnXr1vGNb9wCwD/+49/zgQ/8PVu3bue22/6Hxx/fxTXX/D3vfe+VHH/8Cfzwh3dy7bUf5S/+\n4q84evQon/nMTei6zpvf/HquuOL9bNu2nVtv/W9uuulzPPnJT2F0dIz/9//+lt27d5HNZtry+Uuo\nN2h+WNssx9XPdJlVTggxtJ7+9LP55Cc/Rjwe59577+Gd73wP09NTfPnLX+Suu75HKBTBcZau+OzZ\n8zgnnXQKAGNjY2zbVlx
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x10a51a9b0>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"plot_learning_curve(3)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"Here we see that by adding more model complexity, we've managed to lower the level of convergence to an rms error of 1.0!\n",
|
||
|
"\n",
|
||
|
"What if we get even more complex?"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 30,
|
||
|
"metadata": {
|
||
|
"collapsed": false
|
||
|
},
|
||
|
"outputs": [
|
||
|
{
|
||
|
"data": {
|
||
|
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAfUAAAFkCAYAAAA5cqL3AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmcXFWd///XvXVr7+ru6i0LCUnIciEEkgACAoOsrqiI\nI24jOm447qOOCHwBx2WYHzqig8sI4ogjghuggMCIIoijyJIECHCzkH3tfan9Lr8/blV1ddLdqe6u\nvT/Px6PTVXWrbp3b3an3Pcs9R3EcByGEEELUP7XaBRBCCCFEaUioCyGEEA1CQl0IIYRoEBLqQggh\nRIOQUBdCCCEahIS6EEII0SC0cu1Y13UPcAuwAnCAjxiGsbFg+xuBawAT+KFhGD8oV1mEEEKI2aCc\nNfWLANswjLOA/wd8NbdB13Uv8A3gQuBVwId1Xe8qY1mEEEKIhle2UDcM49fA5dm7i4H+gs3HAVsM\nwxg0DCMDPA6cXa6yCCGEELNB2ZrfAQzDsHRd/xHwFuDvCzY1A4MF94eBlnKWRQghhGh0ZR8oZxjG\n+3D71W/RdT2YfXgQiBQ8LcLYmvxhTNNycPvm5asOv37x/H3OpT/7J2f9vheqXhb5ki/5kq86+pqS\ncg6Uew+wwDCM64EEYDNawJeA5bquR4EYbtP71ybbX39/vFxFnVRnZ4Tu7uGqvHc1lOt4Y/E0AIOD\ncbq12vh5yu+2cc2mY4XZdbyz6VjBPd6pKGdN/ZfAGl3XHwUeBD4FvEXX9Q9l+9E/AzwE/B9wq2EY\n+8pYFiGEEKLhla2mbhhGAnj7JNvvA+4r1/uL2qJkv0+5LUkIIUTRZPIZIYQQokFIqAshhBANQkJd\nCCGEaBAS6qLCpFddCCHKRUJdVIQif2pCCFF28kkrhBBCN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n\nncG3vvV1HMfJluFa0ukM1113JY7jkE6n+dznrszPZV9KEupCCNGgLll2UYlr1Uf2xje+hQceuI81\na07i/vvv5U1vegu7d+/iggtew6tedS49Pd18/OOXF4T66DSsjz32CKlUkptv/hEDAwO84x3umuzb\ntm3j4x//NMccs4wnnniU+++/lyuuuJrly1fwL/9yFZo2GmU33HA93/verXR0dPCLX9zJbbfdyhln\nnDXuCnCFHn74IW666Wba29v57W/vBeBrX/s3vvSlf+Pooxdz//2/YceObdxww7/xhS9cw7Jly3n8\n8Ue56aYb+fjHP01fXx8//OHtaJrGhz/8Pq6++ossWrSY++77Nbff/mNOOOFEWlpa+X//71/Zvn0b\nyWSiLD9/CXVRUdL4LkRjO/XU0/nud7/F0NAQzz67ns985vP09HTz85/fwWOP/YFQqAnLssZ97c6d\nOzj2WHca6dbWVhYtcldf6+jo5Ec/uhW/349lpdG0w1dwAxgYGCAcDtPR0QHA6tVruPnm73LGGWcd\ncQW4a6/9Mt/73n/S19fL6aefAUB/fy9HH70YgDe84U0A9PR0s2zZcgBOPHEt//Vf3wZg3rz5+ZOL\nnTu38/WvXw+4i8MsXHg0p59+Jrt27eLKKz+LpmlcdtkHpvaDLZIMlBMVIc3vQswOqqpy7rkX8PWv\nX8/ZZ5+DoijceedPWLXqBK655suce+75OI497msXL16SX2ltaGiIXbt2AvCtb32dD3zgcq6++ous\nWLEiPzZHVUdXhAP3RCAWi9Hb2wPA+vXP5JdNnWxWy0wmwyOPPMy//uu/8Z//+V888MB97N+/n/b2\nTnbv3gXAT3/6Yx577I90dHSydeuW/P5zS8uq6micLly4iGuu+RI33fR9Lr/8Y5x5prsQTHt7B9/4\nxre57LL3c/PN35nqj7Y
|
||
|
"text/plain": [
|
||
|
"<matplotlib.figure.Figure at 0x109465e48>"
|
||
|
]
|
||
|
},
|
||
|
"metadata": {},
|
||
|
"output_type": "display_data"
|
||
|
}
|
||
|
],
|
||
|
"source": [
|
||
|
"plot_learning_curve(10)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"For an even more complex model, we still converge, but the convergence only happens for *large* amounts of training data.\n",
|
||
|
"\n",
|
||
|
"So we see the following:\n",
|
||
|
"\n",
|
||
|
"- you can **cause the lines to converge** by adding more points or by simplifying the model.\n",
|
||
|
"- you can **bring the convergence error down** only by increasing the complexity of the model.\n",
|
||
|
"\n",
|
||
|
"Thus these curves can give you hints about how you might improve a sub-optimal model. If the curves are already close together, you need more model complexity. If the curves are far apart, you might also improve the model by adding more data.\n",
|
||
|
"\n",
|
||
|
"To make this more concrete, imagine some telescope data in which the results are not robust enough. You must think about whether to spend your valuable telescope time observing *more objects* to get a larger training set, or *more attributes of each object* in order to improve the model. The answer to this question has real consequences, and can be addressed using these metrics."
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"## Summary\n",
|
||
|
"\n",
|
||
|
"We've gone over several useful tools for model validation\n",
|
||
|
"\n",
|
||
|
"- The **Training Score** shows how well a model fits the data it was trained on. This is not a good indication of model effectiveness\n",
|
||
|
"- The **Validation Score** shows how well a model fits hold-out data. The most effective method is some form of cross-validation, where multiple hold-out sets are used.\n",
|
||
|
"- **Validation Curves** are a plot of validation score and training score as a function of **model complexity**:\n",
|
||
|
" + when the two curves are close, it indicates *underfitting*\n",
|
||
|
" + when the two curves are separated, it indicates *overfitting*\n",
|
||
|
" + the \"sweet spot\" is in the middle\n",
|
||
|
"- **Learning Curves** are a plot of the validation score and training score as a function of **Number of training samples**\n",
|
||
|
" + when the curves are close, it indicates *underfitting*, and adding more data will not generally improve the estimator.\n",
|
||
|
" + when the curves are far apart, it indicates *overfitting*, and adding more data may increase the effectiveness of the model.\n",
|
||
|
" \n",
|
||
|
"These tools are powerful means of evaluating your model on your data."
|
||
|
]
|
||
|
}
|
||
|
],
|
||
|
"metadata": {
|
||
|
"kernelspec": {
|
||
|
"display_name": "Python 2",
|
||
|
"language": "python",
|
||
|
"name": "python2"
|
||
|
},
|
||
|
"language_info": {
|
||
|
"codemirror_mode": {
|
||
|
"name": "ipython",
|
||
|
"version": 2
|
||
|
},
|
||
|
"file_extension": ".py",
|
||
|
"mimetype": "text/x-python",
|
||
|
"name": "python",
|
||
|
"nbconvert_exporter": "python",
|
||
|
"pygments_lexer": "ipython2",
|
||
|
"version": "2.7.9"
|
||
|
}
|
||
|
},
|
||
|
"nbformat": 4,
|
||
|
"nbformat_minor": 0
|
||
|
}
|