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:
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.)
In [2]:
import graphlab
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)
QUIZ QUESTION: What's the learned value for the coefficient of feature power_1
?
In [9]:
model15.get('coefficients')
Out[9]:
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),'-')
Out[11]:
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),'-')
Out[12]:
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),'-')
Out[13]:
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),'-')
Out[14]:
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.)
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),'-')
Out[15]:
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),'-')
Out[16]:
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),'-')
Out[17]:
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),'-')
Out[18]:
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.)
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)
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]
In [23]:
validation4 = validation4[5818:7758]
print int(round(train_valid_shuffled[5818:7757+1]['price'].mean(), 0))
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))
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))
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.
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:
sqft_living
inputl2_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)
.)l2_penalty
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)
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),'-')
Out[56]:
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