Regression Week 4: Ridge Regression (interpretation)

In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see the effect of L2 regularization. In particular, we will:

  • Use a pre-built implementation of regression (GraphLab Create) to run polynomial regression
  • Use matplotlib to visualize polynomial regressions
  • Use a pre-built implementation of regression (GraphLab Create) to run polynomial regression, this time with L2 penalty
  • Use matplotlib to visualize polynomial regressions under L2 regularization
  • Choose best L2 penalty using cross-validation.
  • Assess the final fit using test data.

We will continue to use the House data from previous notebooks. (In the next programming assignment for this module, you will implement your own ridge regression learning algorithm using gradient descent.)

Fire up graphlab create


In [1]:
import pandas as pd
import numpy as np
from sklearn import linear_model
import math

dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int, 'sqft_living15':float, 'grade':int, 'yr_renovated':int, 'price':float, 'bedrooms':float, 'zipcode':str, 'long':float, 'sqft_lot15':float, 'sqft_living':float, 'floors':float, 'condition':int, 'lat':float, 'date':str, 'sqft_basement':int, 'yr_built':int, 'id':str, 'sqft_lot':int, 'view':int}

Polynomial regression, revisited

We build on the material from Week 3, where we wrote the function to produce an SFrame with columns containing the powers of a given input. Copy and paste the function polynomial_sframe from Week 3:


In [2]:
def polynomial_sframe(feature, degree):
    poly_dataset = pd.DataFrame()
    poly_dataset['power_1'] = feature
    if degree > 1:
        for power in range(2, degree + 1):
            column = 'power_' + str(power)
            poly_dataset[column] = feature**power
    features = poly_dataset.columns.values.tolist()
    #poly_dataset['constant'] = 1
    #return (poly_dataset, ['constant'] + features)
    return (poly_dataset, features)

In [3]:
polynomial_sframe(np.array([1, 2, 3]), 3)


Out[3]:
(   power_1  power_2  power_3
 0        1        1        1
 1        2        4        8
 2        3        9       27, ['power_1', 'power_2', 'power_3'])

Let's use matplotlib to visualize what a polynomial regression looks like on the house data.


In [4]:
import matplotlib.pyplot as plt
%matplotlib inline

In [5]:
sales = pd.read_csv('kc_house_data.csv', dtype=dtype_dict)

As in Week 3, we will use the sqft_living variable. For plotting purposes (connecting the dots), you'll need to sort by the values of sqft_living. For houses with identical square footage, we break the tie by their prices.


In [6]:
sales = sales.sort(['sqft_living','price'])


/Users/viktorp/anaconda/envs/dato-env/lib/python2.7/site-packages/ipykernel/__main__.py:1: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
  if __name__ == '__main__':

Let us revisit the 15th-order polynomial model using the 'sqft_living' input. Generate polynomial features up to degree 15 using polynomial_sframe() and fit a model with these features. When fitting the model, use an L2 penalty of 1e-5:


In [7]:
l2_small_penalty = 1.5e-5

Note: When we have so many features and so few data points, the solution can become highly numerically unstable, which can sometimes lead to strange unpredictable results. Thus, rather than using no regularization, we will introduce a tiny amount of regularization (l2_penalty=1e-5) to make the solution numerically stable. (In lecture, we discussed the fact that regularization can also help with numerical stability, and here we are seeing a practical example.)

With the L2 penalty specified above, fit the model and print out the learned weights.

Hint: make sure to add 'price' column to the new SFrame before calling graphlab.linear_regression.create(). Also, make sure GraphLab Create doesn't create its own validation set by using the option validation_set=None in this call.


In [8]:
poly_data, features = polynomial_sframe(sales['sqft_living'],15)
print(poly_data['power_1'].mean())
model = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model.fit(poly_data[features], sales['price'])
print(model.coef_)
print(model.intercept_)
plt.plot(poly_data['power_1'], sales['price'], '.',
        poly_data['power_1'], model.predict(poly_data[features]), '-')


2079.89973627
[  1.24873306e+02  -4.77376011e-02   3.01446238e-05  -2.44419942e-09
  -1.94153675e-13   8.54085686e-18   1.51142121e-21   8.27979094e-26
   6.52603100e-31  -3.27895017e-34  -3.87962315e-38  -2.72437650e-42
  -1.07790800e-46   3.78242694e-51   1.39790296e-54]
220664.375055
Out[8]:
[<matplotlib.lines.Line2D at 0x10877c9d0>,
 <matplotlib.lines.Line2D at 0x10877ca50>]

QUIZ QUESTION: What's the learned value for the coefficient of feature power_1?

Observe overfitting

Recall from Week 3 that the polynomial fit of degree 15 changed wildly whenever the data changed. In particular, when we split the sales data into four subsets and fit the model of degree 15, the result came out to be very different for each subset. The model had a high variance. We will see in a moment that ridge regression reduces such variance. But first, we must reproduce the experiment we did in Week 3.

First, split the data into split the sales data into four subsets of roughly equal size and call them set_1, set_2, set_3, and set_4. Use .random_split function and make sure you set seed=0.


In [9]:
set_1 = pd.read_csv('wk3_kc_house_set_1_data.csv', dtype=dtype_dict)
set_2 = pd.read_csv('wk3_kc_house_set_2_data.csv', dtype=dtype_dict)
set_3 = pd.read_csv('wk3_kc_house_set_3_data.csv', dtype=dtype_dict)
set_4 = pd.read_csv('wk3_kc_house_set_4_data.csv', dtype=dtype_dict)
l2_small_penalty=1e-9

Next, fit a 15th degree polynomial on set_1, set_2, set_3, and set_4, using 'sqft_living' to predict prices. Print the weights and make a plot of the resulting model.

Hint: When calling graphlab.linear_regression.create(), use the same L2 penalty as before (i.e. l2_small_penalty). Also, make sure GraphLab Create doesn't create its own validation set by using the option validation_set = None in this call.


In [10]:
sales_subset = set_1
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model1 = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model1.fit(poly_data[features], sales_subset['price'])
print(model1.coef_)
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model1.predict(poly_data[features]))


[  5.44669410e+02  -3.55447618e-01   1.22446389e-04  -1.17175339e-08
  -3.90511951e-13  -1.39076896e-17   1.47860334e-20   6.87491898e-25
  -7.57204214e-29  -1.04097311e-32  -3.71843942e-37   3.39989379e-41
   5.56591837e-45   2.53761456e-49  -3.35152918e-53]
Out[10]:
[<matplotlib.lines.Line2D at 0x10ba52150>,
 <matplotlib.lines.Line2D at 0x10ba52810>]

In [11]:
sales_subset = set_2
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model2 = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model2.fit(poly_data[features], sales_subset['price'])
print(model2.coef_)
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model2.predict(poly_data[features]))


[  8.59362615e+02  -8.18118226e-01   4.28879944e-04  -9.12770494e-08
  -2.69604812e-12   3.73980362e-15  -1.42711957e-19  -6.30794601e-23
  -1.44559730e-27   7.44321374e-31   9.25865888e-35   3.28018266e-41
  -1.29543515e-42  -1.38781257e-46   1.66546446e-50]
Out[11]:
[<matplotlib.lines.Line2D at 0x10d6fae50>,
 <matplotlib.lines.Line2D at 0x10d6faed0>]

In [12]:
sales_subset = set_3
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model3 = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model3.fit(poly_data[features], sales_subset['price'])
print(model3.coef_)
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model3.predict(poly_data[features]))


[ -7.55395946e+02   9.75579521e-01  -4.58945993e-04   7.77958050e-08
   7.15013612e-12  -2.88602034e-15  -2.13677766e-20   3.38085308e-23
   2.19178079e-27  -1.97067831e-31  -4.15992981e-35  -1.80196287e-39
   3.19071183e-43   5.08456902e-47  -3.93304253e-51]
Out[12]:
[<matplotlib.lines.Line2D at 0x10d7ba390>,
 <matplotlib.lines.Line2D at 0x10d7baa50>]

In [13]:
sales_subset = set_4
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model4 = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model4.fit(poly_data[features], sales_subset['price'])
print(model4.coef_)
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model4.predict(poly_data[features]))


[  1.11944573e+03  -9.83760236e-01   3.38770913e-04   3.60377178e-08
  -4.37814031e-11   5.77191760e-15   7.66795182e-19  -9.49297887e-23
  -1.96030806e-26  -2.10872512e-32   3.31004985e-34   3.47733772e-38
  -2.43039122e-42  -8.79553274e-46   6.44569638e-50]
Out[13]:
[<matplotlib.lines.Line2D at 0x10dbfefd0>,
 <matplotlib.lines.Line2D at 0x10dc0b710>]

The four curves should differ from one another a lot, as should the coefficients you learned.

QUIZ QUESTION: For the models learned in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answering this question, negative numbers are considered "smaller" than positive numbers. So -5 is smaller than -3, and -3 is smaller than 5 and so forth.)


In [14]:
power1_coefs = [model1.coef_[0],model2.coef_[0],model3.coef_[0],model4.coef_[0]]
print(power1_coefs)
print(power1_coefs.index(min(power1_coefs)))
print(power1_coefs.index(max(power1_coefs)))


[544.66940984204723, 859.36261531389493, -755.39594635524691, 1119.4457269385798]
2
3

Ridge regression comes to rescue

Generally, whenever we see weights change so much in response to change in data, we believe the variance of our estimate to be large. Ridge regression aims to address this issue by penalizing "large" weights. (Weights of model15 looked quite small, but they are not that small because 'sqft_living' input is in the order of thousands.)

With the argument l2_penalty=1e5, fit a 15th-order polynomial model on set_1, set_2, set_3, and set_4. Other than the change in the l2_penalty parameter, the code should be the same as the experiment above. Also, make sure GraphLab Create doesn't create its own validation set by using the option validation_set = None in this call.


In [15]:
l2_large_penalty=1.23e2
power_1_coef = []

In [16]:
sales_subset = set_1
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model1 = linear_model.Ridge(alpha=l2_large_penalty, normalize=True)
model1.fit(poly_data[features], sales_subset['price'])
print(model1.coef_)
power_1_coef.append(model1.coef_[0])
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model1.predict(poly_data[features]))


[  2.32806803e+00   3.53621608e-04   3.31969692e-08   2.00082477e-12
   1.11492559e-16   6.57786122e-21   4.12939525e-25   2.70393755e-29
   1.81614763e-33   1.23824277e-37   8.51872481e-42   5.89455598e-46
   4.09542560e-50   2.85464889e-54   1.99547476e-58]
Out[16]:
[<matplotlib.lines.Line2D at 0x10de0e4d0>,
 <matplotlib.lines.Line2D at 0x10de0ec10>]

In [17]:
sales_subset = set_2
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model2 = linear_model.Ridge(alpha=l2_large_penalty, normalize=True)
model2.fit(poly_data[features], sales_subset['price'])
print(model2.coef_)
power_1_coef.append(model2.coef_[0])
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model2.predict(poly_data[features]))


[  2.09756903e+00   3.90817483e-04   6.67189944e-08   8.90002997e-12
   9.72639877e-16   9.69733682e-20   9.50564475e-24   9.44491031e-28
   9.57191338e-32   9.86945155e-36   1.03101115e-39   1.08729784e-43
   1.15453748e-47   1.23211305e-51   1.31986696e-55]
Out[17]:
[<matplotlib.lines.Line2D at 0x10e950850>,
 <matplotlib.lines.Line2D at 0x10e950f90>]

In [18]:
sales_subset = set_3
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model3 = linear_model.Ridge(alpha=l2_large_penalty, normalize=True)
model3.fit(poly_data[features], sales_subset['price'])
print(model3.coef_)
power_1_coef.append(model3.coef_[0])
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model3.predict(poly_data[features]))


[  2.28906258e+00   4.12472190e-04   6.08835345e-08   6.58572163e-12
   6.15278155e-16   5.64446634e-20   5.28834396e-24   5.07091402e-28
   4.94657273e-32   4.88043809e-36   4.85009106e-40   4.84161534e-44
   4.84635021e-48   4.85883628e-52   4.87558469e-56]
Out[18]:
[<matplotlib.lines.Line2D at 0x10eb41c50>,
 <matplotlib.lines.Line2D at 0x10eb41d50>]

In [19]:
sales_subset = set_4
poly_data, features = polynomial_sframe(sales_subset['sqft_living'],15)
model4 = linear_model.Ridge(alpha=l2_large_penalty, normalize=True)
model4.fit(poly_data[features], sales_subset['price'])
print(model4.coef_)
power_1_coef.append(model4.coef_[0])
plt.plot(poly_data['power_1'], sales_subset['price'], '.',
        poly_data['power_1'], model4.predict(poly_data[features]))


[  2.08596194e+00   4.05035772e-04   7.46864647e-08   1.13096608e-11
   1.45864442e-15   1.73561251e-19   2.01609632e-23   2.34605255e-27
   2.75636073e-31   3.27043069e-35   3.91046855e-39   4.70118041e-43
   5.67212304e-47   6.85958087e-51   8.30843630e-55]
Out[19]:
[<matplotlib.lines.Line2D at 0x10ed53810>,
 <matplotlib.lines.Line2D at 0x10ed53f50>]

These curves should vary a lot less, now that you applied a high degree of regularization.

QUIZ QUESTION: For the models learned with the high level of regularization in each of these training sets, what are the smallest and largest values you learned for the coefficient of feature power_1? (For the purpose of answering this question, negative numbers are considered "smaller" than positive numbers. So -5 is smaller than -3, and -3 is smaller than 5 and so forth.)


In [20]:
power1_coefs = [model1.coef_[0],model2.coef_[0],model3.coef_[0],model4.coef_[0]]
print(power1_coefs)
print(power1_coefs.index(min(power1_coefs)))
print(power1_coefs.index(max(power1_coefs)))


[2.3280680295793248, 2.0975690277785488, 2.2890625811892025, 2.0859619409193062]
3
0

Selecting an L2 penalty via cross-validation

Just like the polynomial degree, the L2 penalty is a "magic" parameter we need to select. We could use the validation set approach as we did in the last module, but that approach has a major disadvantage: it leaves fewer observations available for training. Cross-validation seeks to overcome this issue by using all of the training set in a smart way.

We will implement a kind of cross-validation called k-fold cross-validation. The method gets its name because it involves dividing the training set into k segments of roughtly equal size. Similar to the validation set method, we measure the validation error with one of the segments designated as the validation set. The major difference is that we repeat the process k times as follows:

Set aside segment 0 as the validation set, and fit a model on rest of data, and evalutate it on this validation set
Set aside segment 1 as the validation set, and fit a model on rest of data, and evalutate it on this validation set
...
Set aside segment k-1 as the validation set, and fit a model on rest of data, and evalutate it on this validation set

After this process, we compute the average of the k validation errors, and use it as an estimate of the generalization error. Notice that all observations are used for both training and validation, as we iterate over segments of data.

To estimate the generalization error well, it is crucial to shuffle the training data before dividing them into segments. GraphLab Create has a utility function for shuffling a given SFrame. We reserve 10% of the data as the test set and shuffle the remainder. (Make sure to use seed=1 to get consistent answer.)


In [21]:
train_valid_shuffled = pd.read_csv('wk3_kc_house_train_valid_shuffled.csv', dtype=dtype_dict)
test = pd.read_csv('wk3_kc_house_test_data.csv', dtype=dtype_dict)

Once the data is shuffled, we divide it into equal segments. Each segment should receive n/k elements, where n is the number of observations in the training set and k is the number of segments. Since the segment 0 starts at index 0 and contains n/k elements, it ends at index (n/k)-1. The segment 1 starts where the segment 0 left off, at index (n/k). With n/k elements, the segment 1 ends at index (n*2/k)-1. Continuing in this fashion, we deduce that the segment i starts at index (n*i/k) and ends at (n*(i+1)/k)-1.

With this pattern in mind, we write a short loop that prints the starting and ending indices of each segment, just to make sure you are getting the splits right.


In [22]:
n = len(train_valid_shuffled)
k = 10 # 10-fold cross-validation

for i in range(k):
    start = (n*i)/k
    end = (n*(i+1))/k-1
    print(i, (start, end))


(0, (0, 1938))
(1, (1939, 3878))
(2, (3879, 5817))
(3, (5818, 7757))
(4, (7758, 9697))
(5, (9698, 11636))
(6, (11637, 13576))
(7, (13577, 15515))
(8, (15516, 17455))
(9, (17456, 19395))

Let us familiarize ourselves with array slicing with SFrame. To extract a continuous slice from an SFrame, use colon in square brackets. For instance, the following cell extracts rows 0 to 9 of train_valid_shuffled. Notice that the first index (0) is included in the slice but the last index (10) is omitted.


In [23]:
train_valid_shuffled[0:10] # rows 0 to 9


Out[23]:
id date price bedrooms bathrooms sqft_living sqft_lot floors waterfront view ... grade sqft_above sqft_basement yr_built yr_renovated zipcode lat long sqft_living15 sqft_lot15
0 2780400035 20140505T000000 665000 4 2.50 2800 5900 1 0 0 ... 8 1660 1140 1963 0 98115 47.6809 -122.286 2580 5900
1 1703050500 20150321T000000 645000 3 2.50 2490 5978 2 0 0 ... 9 2490 0 2003 0 98074 47.6298 -122.022 2710 6629
2 5700002325 20140605T000000 640000 3 1.75 2340 4206 1 0 0 ... 7 1170 1170 1917 0 98144 47.5759 -122.288 1360 4725
3 0475000510 20141118T000000 594000 3 1.00 1320 5000 1 0 0 ... 7 1090 230 1920 0 98107 47.6674 -122.365 1700 5000
4 0844001052 20150128T000000 365000 4 2.50 1904 8200 2 0 0 ... 7 1904 0 1999 0 98010 47.3107 -122.001 1560 12426
5 2781280290 20150427T000000 305000 3 2.50 1610 3516 2 0 0 ... 8 1610 0 2006 0 98055 47.4491 -122.188 1610 3056
6 2214800630 20141105T000000 239950 3 2.25 1560 8280 2 0 0 ... 7 1560 0 1979 0 98001 47.3393 -122.259 1920 8120
7 2114700540 20141021T000000 366000 3 2.50 1320 4320 1 0 0 ... 6 660 660 1918 0 98106 47.5327 -122.347 1190 4200
8 2596400050 20140730T000000 375000 3 1.00 1960 7955 1 0 0 ... 7 1260 700 1963 0 98177 47.7641 -122.364 1850 8219
9 4140900050 20150126T000000 440000 4 1.75 2180 10200 1 0 2 ... 8 2000 180 1966 0 98028 47.7638 -122.270 2590 10445

10 rows × 21 columns

Now let us extract individual segments with array slicing. Consider the scenario where we group the houses in the train_valid_shuffled dataframe into k=10 segments of roughly equal size, with starting and ending indices computed as above. Extract the fourth segment (segment 3) and assign it to a variable called validation4.


In [24]:
n = len(train_valid_shuffled)
i = 3
print(n)
start = (n*i)/10
end = (n*(i+1))/10
validation4 = train_valid_shuffled[start:end+1]
print(start)
print(end)


19396
5818
7758

To verify that we have the right elements extracted, run the following cell, which computes the average price of the fourth segment. When rounded to nearest whole number, the average should be $536,234.


In [25]:
print(int(round(validation4['price'].mean(), 0)))


536159

After designating one of the k segments as the validation set, we train a model using the rest of the data. To choose the remainder, we slice (0:start) and (end+1:n) of the data and paste them together. SFrame has append() method that pastes together two disjoint sets of rows originating from a common dataset. For instance, the following cell pastes together the first and last two rows of the train_valid_shuffled dataframe.

Extract the remainder of the data after excluding fourth segment (segment 3) and assign the subset to train4.


In [26]:
train4 = train_valid_shuffled[:start].append(train_valid_shuffled[end+1:])
print(len(train4))
print(n - len(train4))


17455
1941

To verify that we have the right elements extracted, run the following cell, which computes the average price of the data with fourth segment excluded. When rounded to nearest whole number, the average should be $539,450.


In [27]:
print(int(round(train4['price'].mean(), 0)))


539459

Now we are ready to implement k-fold cross-validation. Write a function that computes k validation errors by designating each of the k segments as the validation set. It accepts as parameters (i) k, (ii) l2_penalty, (iii) dataframe, (iv) name of output column (e.g. price) and (v) list of feature names. The function returns the average validation error using k segments as validation sets.

  • For each i in [0, 1, ..., k-1]:
    • Compute starting and ending indices of segment i and call 'start' and 'end'
    • Form validation set by taking a slice (start:end+1) from the data.
    • Form training set by appending slice (end+1:n) to the end of slice (0:start).
    • Train a linear model using training set just formed, with a given l2_penalty
    • Compute validation error using validation set just formed

In [43]:
def k_fold_cross_validation(k, l2_penalty, data, output_name, features_list):
    validation_errors = []
    for i in range(k):
        n = len(data)
        start = (n*i)/k 
        end = (n*(i+1))/k
        validation_set = data[start:end + 1]
        training_set = data[0:start].append(data[end + 1:n])
        model = linear_model.Ridge(alpha=l2_penalty, normalize=True)
        model.fit(training_set[features_list], training_set[output_name])

        predictons = model.predict(validation_set[features_list])
        errors = predictons - validation_set[output_name]
        validation_errors.append(errors.T.dot(errors))
    return np.array(validation_errors).mean()

Once we have a function to compute the average validation error for a model, we can write a loop to find the model that minimizes the average validation error. Write a loop that does the following:

  • We will again be aiming to fit a 15th-order polynomial model using the sqft_living input
  • For l2_penalty in [10^1, 10^1.5, 10^2, 10^2.5, ..., 10^7] (to get this in Python, you can use this Numpy function: np.logspace(1, 7, num=13).)
    • Run 10-fold cross-validation with l2_penalty
  • Report which L2 penalty produced the lowest average validation error.

Note: since the degree of the polynomial is now fixed to 15, to make things faster, you should generate polynomial features in advance and re-use them throughout the loop. Make sure to use train_valid_shuffled when generating polynomial features!


In [44]:
import sys
validation_errors = []
lowest_error = sys.float_info.max
penalty = 0
for l2_penalty in np.logspace(1, 7, num=13):
    data_poly, features = polynomial_sframe(train_valid_shuffled['sqft_living'], 15)
    data_poly['price'] = train_valid_shuffled['price']
    average_validation_error = k_fold_cross_validation(10, l2_penalty, data_poly, 'price', features)
    print(l2_penalty)
    print(average_validation_error)
    if average_validation_error < lowest_error:
        lowest_error = average_validation_error
        penalty = l2_penalty
    validation_errors.append(average_validation_error)

print('Lowest error is: %s for penalty: %s' % (lowest_error, penalty))


10.0
2.23727424739e+14
31.6227766017
2.4648309358e+14
100.0
2.57439385967e+14
316.227766017
2.62906252956e+14
1000.0
2.65017874562e+14
3162.27766017
2.6573349394e+14
10000.0
2.65964941178e+14
31622.7766017
2.66038658207e+14
100000.0
2.66062022668e+14
316227.766017
2.6606941648e+14
1000000.0
2.66071755142e+14
3162277.66017
2.66072494744e+14
10000000.0
2.66072728633e+14
Lowest error is: 2.23727424739e+14 for penalty: 10.0

QUIZ QUESTIONS: What is the best value for the L2 penalty according to 10-fold validation?

You may find it useful to plot the k-fold cross-validation errors you have obtained to better understand the behavior of the method.


In [45]:
# Plot the l2_penalty values in the x axis and the cross-validation error in the y axis.
# Using plt.xscale('log') will make your plot more intuitive.
plt.plot(np.logspace(1, 7, num=13), validation_errors, '-')
plt.xscale('log')
print(validation_errors)


[223727424739194.31, 246483093579935.44, 257439385967166.31, 262906252955717.81, 265017874561645.31, 265733493939507.84, 265964941178385.19, 266038658206891.59, 266062022667575.0, 266069416480160.91, 266071755141529.19, 266072494744454.91, 266072728632762.69]

Once you found the best value for the L2 penalty using cross-validation, it is important to retrain a final model on all of the training data using this value of l2_penalty. This way, your final model will be trained on the entire dataset.


In [31]:
data_poly, features = polynomial_sframe(train_valid_shuffled['sqft_living'], 15)
model = linear_model.Ridge(normalize=True, alpha=penalty)
model.fit(data_poly[features], train_valid_shuffled['price'])


Out[31]:
Ridge(alpha=10.0, copy_X=True, fit_intercept=True, max_iter=None,
   normalize=True, random_state=None, solver='auto', tol=0.001)

QUIZ QUESTION: Using the best L2 penalty found above, train a model using all training data. What is the RSS on the TEST data of the model you learn with this L2 penalty?


In [32]:
poly_data_test, features = polynomial_sframe(test['sqft_living'], 15)
predictions = model.predict(poly_data_test[features])
test_errors = predictions - test['price']
RSS_test = test_errors.T.dot(test_errors)

In [33]:
RSS_test


Out[33]:
229953745232505.0

In [ ]: