In this notebook, you will use LASSO to select features, building on a pre-implemented solver for LASSO (using GraphLab Create, though you can use other solvers). You will:
In the second notebook, you will implement your own LASSO solver, using coordinate descent.
In [1]:
import graphlab
In [2]:
sales = graphlab.SFrame('../Data/kc_house_data.gl/')
As in Week 2, we consider features that are some transformations of inputs.
In [3]:
from math import log, sqrt
sales['sqft_living_sqrt'] = sales['sqft_living'].apply(sqrt)
sales['sqft_lot_sqrt'] = sales['sqft_lot'].apply(sqrt)
sales['bedrooms_square'] = sales['bedrooms']*sales['bedrooms']
# In the dataset, 'floors' was defined with type string,
# so we'll convert them to float, before creating a new feature.
sales['floors'] = sales['floors'].astype(float)
sales['floors_square'] = sales['floors']*sales['floors']
Let us fit a model with all the features available, plus the features we just created above.
In [4]:
all_features = ['bedrooms', 'bedrooms_square',
'bathrooms',
'sqft_living', 'sqft_living_sqrt',
'sqft_lot', 'sqft_lot_sqrt',
'floors', 'floors_square',
'waterfront', 'view', 'condition', 'grade',
'sqft_above',
'sqft_basement',
'yr_built', 'yr_renovated']
Applying L1 penalty requires adding an extra parameter (l1_penalty
) to the linear regression call in GraphLab Create. (Other tools may have separate implementations of LASSO.) Note that it's important to set l2_penalty=0
to ensure we don't introduce an additional L2 penalty.
In [5]:
model_all = graphlab.linear_regression.create(sales, target='price', features=all_features,
validation_set=None,
l2_penalty=0., l1_penalty=1e10)
Find what features had non-zero weight.
In [6]:
model_all_mask = model_all["coefficients"]["value"] > 0.0
In [39]:
model_all["coefficients"][model_all_mask].print_rows(num_rows=20)
Note that a majority of the weights have been set to zero. So by setting an L1 penalty that's large enough, we are performing a subset selection.
QUIZ QUESTION: According to this list of weights, which of the features have been chosen?
To find a good L1 penalty, we will explore multiple values using a validation set. Let us do three way split into train, validation, and test sets:
Be very careful that you use seed = 1 to ensure you get the same answer!
In [40]:
(training_and_validation, testing) = sales.random_split(.9,seed=1) # initial train/test split
(training, validation) = training_and_validation.random_split(0.5, seed=1) # split training into train and validate
Next, we write a loop that does the following:
l1_penalty
in [10^1, 10^1.5, 10^2, 10^2.5, ..., 10^7] (to get this in Python, type np.logspace(1, 7, num=13)
.)l1_penalty
on TRAIN data. Specify l1_penalty=l1_penalty
and l2_penalty=0.
in the parameter list..predict()
) for that l1_penalty
l1_penalty
produced the lowest RSS on validation data.When you call linear_regression.create()
make sure you set validation_set = None
.
Note: you can turn off the print out of linear_regression.create()
with verbose = False
In [41]:
import numpy as np
In [42]:
def get_rss(model, data, outcome):
predictions = model.predict(data)
residuals = predictions - outcome
rss = sum(pow(residuals,2))
return(rss)
In [43]:
l1_rss = {}
for l1 in np.logspace(1, 7, num=13):
l1_rss[l1] = get_rss(graphlab.linear_regression.create(training, target='price', features=all_features, validation_set=None,
l2_penalty=0., l1_penalty=l1, verbose=False),
validation,
validation["price"])
min_value = min(l1_rss.values())
min_key = [key for key, value in l1_rss.iteritems() if value == min_value]
print "l1 value " + str(min_key) + " yielded rss of " + str(min_value)
In [44]:
model_best_l1 = graphlab.linear_regression.create(training, target='price', features=all_features, validation_set=None,
l2_penalty=0., l1_penalty=10, verbose=False)
rss_best_l1 = get_rss(model_best_l1,testing,testing["price"])
print rss_best_l1
QUIZ QUESTIONS
l1_penalty
?
###### 10l1_penalty
?
###### 1.56983602382e+14
In [45]:
model_best_l1_mask = model_best_l1["coefficients"]["value"] > 0.0
model_best_l1["coefficients"][model_best_l1_mask].print_rows(num_rows=20)
In [49]:
model_best_l1["coefficients"]["value"].nnz()
Out[49]:
In this section, you are going to implement a simple, two phase procedure to achive this goal:
l1_penalty
values to find a narrow region of l1_penalty
values where models are likely to have the desired number of non-zero weights.l1_penalty
that achieves the desired sparsity. Here, we will again use a validation set to choose the best value for l1_penalty
.
In [46]:
max_nonzeros = 7
In [68]:
l1_penalty_values = np.logspace(8, 10, num=20)
In [69]:
l1_penalty_values
Out[69]:
Now, implement a loop that search through this space of possible l1_penalty
values:
l1_penalty
in np.logspace(8, 10, num=20)
:l1_penalty
on TRAIN data. Specify l1_penalty=l1_penalty
and l2_penalty=0.
in the parameter list. When you call linear_regression.create()
make sure you set validation_set = None
model['coefficients']['value']
gives you an SArray with the parameters you learned. If you call the method .nnz()
on it, you will find the number of non-zero parameters!
In [70]:
l1_penalty_nnz = {}
for l1 in l1_penalty_values:
model_l1_penalty = graphlab.linear_regression.create(training, target='price', features=all_features,
validation_set=None, l2_penalty=0., l1_penalty=l1, verbose=False)
l1_penalty_nnz[l1] = model_l1_penalty["coefficients"]["value"].nnz()
print l1_penalty_nnz
In [76]:
from collections import OrderedDict
sorted_l1_penalty_nnz = OrderedDict(sorted(l1_penalty_nnz.items(), key=lambda t: t[0]))
print sorted_l1_penalty_nnz
In [77]:
l1_penalty_min = float('NaN')
l1_penalty_max = float('NaN')
for i in xrange(1,len(sorted_l1_penalty_nnz)):
if sorted_l1_penalty_nnz.values()[i-1] >= max_nonzeros and sorted_l1_penalty_nnz.values()[i] <= max_nonzeros:
l1_penalty_min = sorted_l1_penalty_nnz.keys()[i-1]
l1_penalty_max = sorted_l1_penalty_nnz.keys()[i]
break
Out of this large range, we want to find the two ends of our desired narrow range of l1_penalty
. At one end, we will have l1_penalty
values that have too few non-zeros, and at the other end, we will have an l1_penalty
that has too many non-zeros.
More formally, find:
l1_penalty
that has more non-zeros than max_nonzero
(if we pick a penalty smaller than this value, we will definitely have too many non-zero weights)l1_penalty_min
(we will use it later)l1_penalty
that has fewer non-zeros than max_nonzero
(if we pick a penalty larger than this value, we will definitely have too few non-zero weights)l1_penalty_max
(we will use it later)Hint: there are many ways to do this, e.g.:
l1_penalty
and inspecting it to find the appropriate boundaries.
In [78]:
print l1_penalty_min
print l1_penalty_max
In [79]:
l1_penalty_values = np.linspace(l1_penalty_min,l1_penalty_max,20)
print l1_penalty_values
l1_penalty
in np.linspace(l1_penalty_min,l1_penalty_max,20)
:l1_penalty
on TRAIN data. Specify l1_penalty=l1_penalty
and l2_penalty=0.
in the parameter list. When you call linear_regression.create()
make sure you set validation_set = None
Find the model that the lowest RSS on the VALIDATION set and has sparsity equal to max_nonzero
.
In [105]:
l1_penalty_rss = {}
for l1 in l1_penalty_values:
l1_penalty_model = graphlab.linear_regression.create(training, target='price', features=all_features, validation_set=None, l2_penalty=0., l1_penalty=l1, verbose=False)
l1_penalty_rss[l1] = (get_rss(l1_penalty_model,validation,validation["price"]), l1_penalty_model["coefficients"])
sorted_l1_penalty_rss = OrderedDict(sorted(l1_penalty_rss.items(), key=lambda t: t[1][0]))
In [106]:
for item in sorted_l1_penalty_rss.items():
if( item[1][1]["value"].nnz() == max_nonzeros):
print ("l1", item[0])
print ("rss", item[1][0])
l1_penalty_model_mask = item[1][1]["value"] > 0.0
item[1][1][l1_penalty_model_mask].print_rows(num_rows=20)
#print ("coefficients", item[1][1])
break
In [ ]: