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 [2]:
import graphlab

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.


In [3]:
def polynomial_sframe(feature, degree):
    # assume that degree >= 1
    # initialize the SFrame:
    poly_sframe = graphlab.SFrame()
    # and set poly_sframe['power_1'] equal to the passed feature
    poly_sframe['power_1'] = feature

    # first check if degree > 1fea
    if degree > 1:
        # then loop over the remaining degrees:
        # range usually starts at 0 and stops at the endpoint-1. We want it to start at 2 and stop at degree
        for power in range(2, degree+1): 
            # first we'll give the column a name:
            name = 'power_' + str(power)
            # then assign poly_sframe[name] to the appropriate power of feature
            #name = name.apply(lambda name: names**power)
            poly_sframe[name] = feature #poly_sframe.apply(lambda name : name**power)
            tmp = poly_sframe[name]
            tmp_power = tmp.apply(lambda x: x**power)
            poly_sframe[name] = tmp_power
            #print tmp_power

    return poly_sframe

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 = graphlab.SFrame('kc_house_data.gl/')

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'])

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 = 1e-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]:
poly15_data = polynomial_sframe(sales['sqft_living'], 15)
my_features15 = poly15_data.column_names() # get the name of the features
poly15_data['price'] = sales['price'] # add price to the data since it's the target
model15 = graphlab.linear_regression.create(poly15_data, target = 'price', features = my_features15,
                                                                           l2_penalty=l2_small_penalty,
                                                                            validation_set = None)


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 21613
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 1.207924     | 2662555.739474     | 245656.462167 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:

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


In [9]:
model15.get('coefficients')


Out[9]:
name index value
(intercept) None 167924.860299
power_1 None 103.090940454
power_2 None 0.134604569621
power_3 None -0.000129071380882
power_4 None 5.18929047414e-08
power_5 None -7.7716959357e-12
power_6 None 1.71145398227e-16
power_7 None 4.51177396318e-20
power_8 None -4.78837836601e-25
power_9 None -2.33343414208e-28
[16 rows x 3 columns]
Note: Only the head of the SFrame is printed.
You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.

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 [10]:
(semi_split1, semi_split2) = sales.random_split(.5,seed=0)
(set_1, set_2) = semi_split1.random_split(0.5, seed=0)
(set_3, set_4) = semi_split2.random_split(0.5, seed=0)

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 [11]:
poly15_set1 = polynomial_sframe(set_1['sqft_living'], 15)
my_features15 = poly15_set1.column_names() # get the name of the features
poly15_set1['price'] = set_1['price'] # add price to the data since it's the target
modelset1 = graphlab.linear_regression.create(poly15_set1, target = 'price', features = my_features15,
                                                                              l2_penalty=l2_small_penalty,  
                                                                              validation_set = None)


modelset1.get('coefficients')
plt.plot(poly15_set1['power_1'],poly15_set1['price'],'.',
        poly15_set1['power_1'], modelset1.predict(poly15_set1),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5404
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.056511     | 2191984.900346     | 248699.117256 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[11]:
[<matplotlib.lines.Line2D at 0x6468e10>,
 <matplotlib.lines.Line2D at 0x646e350>]

In [12]:
poly15_set2 = polynomial_sframe(set_2['sqft_living'], 15)
my_features15 = poly15_set2.column_names() # get the name of the features
poly15_set2['price'] = set_2['price'] # add price to the data since it's the target
modelset2 = graphlab.linear_regression.create(poly15_set2, target = 'price', features = my_features15,
                                                                              l2_penalty=l2_small_penalty,  
                                                                              validation_set = None)


modelset2.get('coefficients')
plt.plot(poly15_set2['power_1'],poly15_set2['price'],'.',
        poly15_set2['power_1'], modelset2.predict(poly15_set2),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5398
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.102524     | 1975178.189943     | 234533.610637 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[12]:
[<matplotlib.lines.Line2D at 0x6753610>,
 <matplotlib.lines.Line2D at 0x6753a90>]

In [13]:
poly15_set3 = polynomial_sframe(set_3['sqft_living'], 15)
my_features15 = poly15_set3.column_names() # get the name of the features
poly15_set3['price'] = set_3['price'] # add price to the data since it's the target
modelset3 = graphlab.linear_regression.create(poly15_set3, target = 'price', features = my_features15,
                                                                              l2_penalty=l2_small_penalty,  
                                                                              validation_set = None)


modelset3.get('coefficients')
plt.plot(poly15_set3['power_1'],poly15_set3['price'],'.',
        poly15_set3['power_1'], modelset3.predict(poly15_set3),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5409
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.090225     | 2283722.683460     | 251097.728054 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[13]:
[<matplotlib.lines.Line2D at 0x68fca90>,
 <matplotlib.lines.Line2D at 0x68fcf10>]

In [14]:
poly15_set4 = polynomial_sframe(set_4['sqft_living'], 15)
my_features15 = poly15_set4.column_names() # get the name of the features
poly15_set4['price'] = set_4['price'] # add price to the data since it's the target
modelset4 = graphlab.linear_regression.create(poly15_set4, target = 'price', features = my_features15,
                                                                              l2_penalty=l2_small_penalty,  
                                                                              validation_set = None)


modelset4.get('coefficients')
plt.plot(poly15_set4['power_1'],poly15_set4['price'],'.',
        poly15_set4['power_1'], modelset4.predict(poly15_set4),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5402
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.057646     | 2378292.374908     | 244341.293210 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[14]:
[<matplotlib.lines.Line2D at 0x6d80f10>,
 <matplotlib.lines.Line2D at 0x6d85450>]

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.)

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]:
poly15_set1 = polynomial_sframe(set_1['sqft_living'], 15)
my_features15 = poly15_set1.column_names() # get the name of the features
poly15_set1['price'] = set_1['price'] # add price to the data since it's the target
modelset1 = graphlab.linear_regression.create(poly15_set1, target = 'price', features = my_features15,
                                                                              l2_penalty=1e5,  
                                                                              validation_set = None)


modelset1.get('coefficients')
plt.plot(poly15_set1['power_1'],poly15_set1['price'],'.',
        poly15_set1['power_1'], modelset1.predict(poly15_set1),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5404
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.064650     | 5978778.434729     | 374261.720860 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[15]:
[<matplotlib.lines.Line2D at 0x702e890>,
 <matplotlib.lines.Line2D at 0x702ed10>]

In [16]:
poly15_set2 = polynomial_sframe(set_2['sqft_living'], 15)
my_features15 = poly15_set2.column_names() # get the name of the features
poly15_set2['price'] = set_2['price'] # add price to the data since it's the target
modelset2 = graphlab.linear_regression.create(poly15_set2, target = 'price', features = my_features15,
                                                                              l2_penalty=1e5,  
                                                                              validation_set = None)


modelset2.get('coefficients')
plt.plot(poly15_set2['power_1'],poly15_set2['price'],'.',
        poly15_set2['power_1'], modelset2.predict(poly15_set2),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5398
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.071695     | 2984894.541944     | 323238.809634 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[16]:
[<matplotlib.lines.Line2D at 0x72e3a10>,
 <matplotlib.lines.Line2D at 0x72e3e90>]

In [17]:
poly15_set3 = polynomial_sframe(set_3['sqft_living'], 15)
my_features15 = poly15_set3.column_names() # get the name of the features
poly15_set3['price'] = set_3['price'] # add price to the data since it's the target
modelset3 = graphlab.linear_regression.create(poly15_set3, target = 'price', features = my_features15,
                                                                              l2_penalty=1e5,  
                                                                              validation_set = None)


modelset3.get('coefficients')
plt.plot(poly15_set3['power_1'],poly15_set3['price'],'.',
        poly15_set3['power_1'], modelset3.predict(poly15_set3),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5409
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.050573     | 3695342.767093     | 350033.521294 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[17]:
[<matplotlib.lines.Line2D at 0x75709d0>,
 <matplotlib.lines.Line2D at 0x7570e50>]

In [18]:
poly15_set4 = polynomial_sframe(set_4['sqft_living'], 15)
my_features15 = poly15_set4.column_names() # get the name of the features
poly15_set4['price'] = set_4['price'] # add price to the data since it's the target
modelset4 = graphlab.linear_regression.create(poly15_set4, target = 'price', features = my_features15,
                                                                              l2_penalty=1e5,  
                                                                              validation_set = None)


modelset4.get('coefficients')
plt.plot(poly15_set4['power_1'],poly15_set4['price'],'.',
        poly15_set4['power_1'], modelset4.predict(poly15_set4),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 5402
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.060683     | 3601895.280124     | 323111.582889 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[18]:
[<matplotlib.lines.Line2D at 0x7699e10>,
 <matplotlib.lines.Line2D at 0x769e2d0>]

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

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.)

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 [19]:
(train_valid, test) = sales.random_split(.9, seed=1)
train_valid_shuffled = graphlab.toolkits.cross_validation.shuffle(train_valid, random_seed=1)

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 [20]:
n = len(train_valid_shuffled)
k = 10 # 10-fold cross-validation

for i in xrange(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 [21]:
#train_valid_shuffled[0:9] # rows 0 to 1

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 [22]:
n = len(train_valid_shuffled)
k = 10 # 10-fold cross-validation

validation4 =graphlab.SFrame()

for i in xrange(k):
    if i<4:
        start = (n*i)/k
        end = (n*(i+1))/k-1
        validation4 = validation4.append(train_valid_shuffled[start:end+1])
        print i, (start, end)
#validation4 = validation4[:-1]


0 (0, 1938)
1 (1939, 3878)
2 (3879, 5817)
3 (5818, 7757)

In [23]:
validation4 = validation4[5818:7758]
print int(round(train_valid_shuffled[5818:7757+1]['price'].mean(), 0))


536234

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 [24]:
print int(round(validation4['price'].mean(), 0))


536234

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.


In [25]:
n = len(train_valid_shuffled)
first_two = train_valid_shuffled[0:2]
last_two = train_valid_shuffled[n-2:n]
#print first_two.append(last_two)

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


In [26]:
n = len(train_valid_shuffled)
first_segment = train_valid_shuffled[0:5818] ## before the segment 3
last_segment = train_valid_shuffled[7758:n] ## after the segment 3
train4 = first_segment.append(last_segment) ## train4 dataset contain all the data excluding fourth

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))


539450

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 [48]:
def k_fold_cross_validation(k, l2_penalty, data, output_name, features_list):
    n = len(data)
    validation_errors = []
    for i in xrange(k):
        start = (n*i)/k
        end = (n*(i+1))/k-1
        validation_set = data[start:end+1]
        training_set = data[end+1:n].append(data[0:start])
        
        ## train a linear model using training set just formend, with given l2_penalty
        model = graphlab.linear_regression.create(training_set, 
                                                  target = output_name, 
                                                  features = features_list,
                                                  l2_penalty=l2_penalty,
                                                  validation_set = None,
                                                  verbose = False) 

        # predict on validation set 
        pred = model.predict(validation_set)
       
        validation_error = pred - validation_set['price']
        RSS = sum(validation_error * validation_error)
        
        validation_errors.append(RSS)
    
    return sum(validation_errors)/len(validation_errors)

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 [52]:
import numpy as np

poly15_train_valid_shuffled = polynomial_sframe(train_valid_shuffled['sqft_living'], 15)
my_features15 = poly15_train_valid_shuffled.column_names() # get the name of the features
poly15_train_valid_shuffled['price'] = train_valid_shuffled['price'] # add price to the data since it's the target

l2_penalty_list = np.logspace(1, 7, num=13)

min_error = None
best_l2_penalty = None
cross_validation_errors = []

for l2_penalty in l2_penalty_values:
    avg_val_error = k_fold_cross_validation(10, l2_penalty, poly15_train_valid_shuffled, 'price', set15_features)
    print "For l2_penalty: " + str(l2_penalty) + " ---> Avg validation penalty : " + str(avg_val_error)
    cross_validation_errors.append(avg_val_error)
    if min_error is None or avg_val_error < min_error:
        min_error = avg_val_error
        best_l2_penalty = l2_penalty
print "Best l2_penalty --->: " + str(best_l2_penalty)


For l2_penalty: 10.0 ---> Avg validation penalty : 4.91826427769e+14
For l2_penalty: 31.6227766017 ---> Avg validation penalty : 2.87504229919e+14
For l2_penalty: 100.0 ---> Avg validation penalty : 1.60908965822e+14
For l2_penalty: 316.227766017 ---> Avg validation penalty : 1.22090967326e+14
For l2_penalty: 1000.0 ---> Avg validation penalty : 1.21192264451e+14
For l2_penalty: 3162.27766017 ---> Avg validation penalty : 1.2395000929e+14
For l2_penalty: 10000.0 ---> Avg validation penalty : 1.36837175248e+14
For l2_penalty: 31622.7766017 ---> Avg validation penalty : 1.71728094842e+14
For l2_penalty: 100000.0 ---> Avg validation penalty : 2.2936143126e+14
For l2_penalty: 316227.766017 ---> Avg validation penalty : 2.52940568729e+14
For l2_penalty: 1000000.0 ---> Avg validation penalty : 2.58682548441e+14
For l2_penalty: 3162277.66017 ---> Avg validation penalty : 2.62819399742e+14
For l2_penalty: 10000000.0 ---> Avg validation penalty : 2.64889015378e+14
Best l2_penalty --->: 1000.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.

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 [56]:
poly15_sales = polynomial_sframe(sales['sqft_living'], 15)
my_features15 = poly15_sales.column_names() # get the name of the features
poly15_sales['price'] = sales['price'] # add price to the data since it's the target
modelset4 = graphlab.linear_regression.create(poly15_sales, 
                                              target = 'price', 
                                              features = my_features15,
                                              l2_penalty=best_l2_penalty,  
                                              validation_set = None)


modelset4.get('coefficients')
plt.plot(poly15_sales['power_1'],poly15_sales['price'],'.',
        poly15_sales['power_1'], modelset4.predict(poly15_sales),'-')


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 21613
PROGRESS: Number of features          : 15
PROGRESS: Number of unpacked features : 15
PROGRESS: Number of coefficients    : 16
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.171313     | 2437953.424257     | 247969.666907 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
Out[56]:
[<matplotlib.lines.Line2D at 0x7b20510>,
 <matplotlib.lines.Line2D at 0x7b27b90>]

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 [57]:
test_data = polynomial_sframe(test['sqft_living'], 15)
predictions_test = modelset4.predict(test_data)
test_errors = predictions_test - test['price']
RSS_test = sum(test_errors * test_errors)
print RSS_test


1.28492616721e+14

END