Regression Week 2: Multiple Regression (gradient descent)

In the first notebook we explored multiple regression using graphlab create. Now we will use graphlab along with numpy to solve for the regression weights with gradient descent.

In this notebook we will cover estimating multiple regression weights via gradient descent. You will:

  • Add a constant column of 1's to a graphlab SFrame to account for the intercept
  • Convert an SFrame into a Numpy array
  • Write a predict_output() function using Numpy
  • Write a numpy function to compute the derivative of the regression weights with respect to a single feature
  • Write gradient descent function to compute the regression weights given an initial weight vector, step size and tolerance.
  • Use the gradient descent function to estimate regression weights for multiple features

Fire up graphlab create

Make sure you have the latest version of graphlab (>= 1.7)


In [1]:
import graphlab

Load in house sales data

Dataset is from house sales in King County, the region where the city of Seattle, WA is located.


In [2]:
sales = graphlab.SFrame('kc_house_data.gl/')


[INFO] 1448932450 : INFO:     (initialize_globals_from_environment:282): Setting configuration variable GRAPHLAB_FILEIO_ALTERNATIVE_SSL_CERT_FILE to C:\Users\linghao\AppData\Local\Dato\Dato Launcher\lib\site-packages\certifi\cacert.pem
1448932450 : INFO:     (initialize_globals_from_environment:282): Setting configuration variable GRAPHLAB_FILEIO_ALTERNATIVE_SSL_CERT_DIR to 
This non-commercial license of GraphLab Create is assigned to zhanglh13@fudan.edu.cn and will expire on September 21, 2016. For commercial licensing options, visit https://dato.com/buy/.

[INFO] Start server at: ipc:///tmp/graphlab_server-15804 - Server binary: C:\Users\linghao\AppData\Local\Dato\Dato Launcher\lib\site-packages\graphlab\unity_server.exe - Server log: C:\Users\linghao\AppData\Local\Temp\graphlab_server_1448932450.log.0
[INFO] GraphLab Server Version: 1.7.1

If we want to do any "feature engineering" like creating new features or adjusting existing ones we should do this directly using the SFrames as seen in the other Week 2 notebook. For this notebook, however, we will work with the existing features.

Convert to Numpy Array

Although SFrames offer a number of benefits to users (especially when using Big Data and built-in graphlab functions) in order to understand the details of the implementation of algorithms it's important to work with a library that allows for direct (and optimized) matrix operations. Numpy is a Python solution to work with matrices (or any multi-dimensional "array").

Recall that the predicted value given the weights and the features is just the dot product between the feature and weight vector. Similarly, if we put all of the features row-by-row in a matrix then the predicted value for all the observations can be computed by right multiplying the "feature matrix" by the "weight vector".

First we need to take the SFrame of our data and convert it into a 2D numpy array (also called a matrix). To do this we use graphlab's built in .to_dataframe() which converts the SFrame into a Pandas (another python library) dataframe. We can then use Panda's .as_matrix() to convert the dataframe into a numpy matrix.


In [3]:
import numpy as np # note this allows us to refer to numpy as np instead

Now we will write a function that will accept an SFrame, a list of feature names (e.g. ['sqft_living', 'bedrooms']) and an target feature e.g. ('price') and will return two things:

  • A numpy matrix whose columns are the desired features plus a constant column (this is how we create an 'intercept')
  • A numpy array containing the values of the output

With this in mind, complete the following function (where there's an empty line you should write a line of code that does what the comment above indicates)

Please note you will need GraphLab Create version at least 1.7.1 in order for .to_numpy() to work!


In [5]:
def get_numpy_data(data_sframe, features, output):
    data_sframe['constant'] = 1 # this is how you add a constant column to an SFrame
    # add the column 'constant' to the front of the features list so that we can extract it along with the others:
    features = ['constant'] + features # this is how you combine two lists
    # select the columns of data_SFrame given by the features list into the SFrame features_sframe (now including constant):
    features_sframe = data_sframe[features]
    # the following line will convert the features_SFrame into a numpy matrix:
    feature_matrix = features_sframe.to_numpy()
    # assign the column of data_sframe associated with the output to the SArray output_sarray
    output_sarray = data_sframe[output]
    # the following will convert the SArray into a numpy array by first converting it to a list
    output_array = output_sarray.to_numpy()
    return(feature_matrix, output_array)

For testing let's use the 'sqft_living' feature and a constant as our features and price as our output:


In [6]:
(example_features, example_output) = get_numpy_data(sales, ['sqft_living'], 'price') # the [] around 'sqft_living' makes it a list
print example_features[0,:] # this accesses the first row of the data the ':' indicates 'all columns'
print example_output[0] # and the corresponding output


[  1.00000000e+00   1.18000000e+03]
221900.0

Predicting output given regression weights

Suppose we had the weights [1.0, 1.0] and the features [1.0, 1180.0] and we wanted to compute the predicted output 1.0*1.0 + 1.0*1180.0 = 1181.0 this is the dot product between these two arrays. If they're numpy arrayws we can use np.dot() to compute this:


In [7]:
my_weights = np.array([1., 1.]) # the example weights
my_features = example_features[0,] # we'll use the first data point
predicted_value = np.dot(my_features, my_weights)
print predicted_value


1181.0

np.dot() also works when dealing with a matrix and a vector. Recall that the predictions from all the observations is just the RIGHT (as in weights on the right) dot product between the features matrix and the weights vector. With this in mind finish the following predict_output function to compute the predictions for an entire matrix of features given the matrix and the weights:


In [13]:
def predict_output(feature_matrix, weights):
    # assume feature_matrix is a numpy matrix containing the features as columns and weights is a corresponding numpy array
    # create the predictions vector by using np.dot()
    predictions = []
    for col in range(feature_matrix.shape[0]):
        predictions.append(np.dot(feature_matrix[col,], weights))
    return(predictions)

If you want to test your code run the following cell:


In [14]:
test_predictions = predict_output(example_features, my_weights)
print test_predictions[0] # should be 1181.0
print test_predictions[1] # should be 2571.0


1181.0
2571.0

Computing the Derivative

We are now going to move to computing the derivative of the regression cost function. Recall that the cost function is the sum over the data points of the squared difference between an observed output and a predicted output.

Since the derivative of a sum is the sum of the derivatives we can compute the derivative for a single data point and then sum over data points. We can write the squared difference between the observed output and predicted output for a single point as follows:

(w[0]*[CONSTANT] + w[1]*[feature_1] + ... + w[i] *[feature_i] + ... + w[1]*[feature_k] - output)^2

Where we have k features and a constant. So the derivative with respect to weight w[i] by the chain rule is:

2*(w[0]*[CONSTANT] + w[1]*[feature_1] + ... + w[i] *[feature_i] + ... + w[1]*[feature_k] - output)* [feature_i]

The term inside the paranethesis is just the error (difference between prediction and output). So we can re-write this as:

2*error*[feature_i]

That is, the derivative for the weight for feature i is the sum (over data points) of 2 times the product of the error and the feature itself. In the case of the constant then this is just twice the sum of the errors!

Recall that twice the sum of the product of two vectors is just twice the dot product of the two vectors. Therefore the derivative for the weight for feature_i is just two times the dot product between the values of feature_i and the current errors.

With this in mind complete the following derivative function which computes the derivative of the weight given the value of the feature (over all data points) and the errors (over all data points).


In [17]:
def feature_derivative(errors, feature):
    # Assume that errors and feature are both numpy arrays of the same length (number of data points)
    # compute twice the dot product of these vectors as 'derivative' and return the value
    derivative = 2 * np.dot(errors, feature)
    return(derivative)

To test your feature derivartive run the following:


In [87]:
(example_features, example_output) = get_numpy_data(sales, ['sqft_living', 'sqft_living15'], 'price') 
my_weights = np.array([0., 0., 0.]) # this makes all the predictions 0
test_predictions = predict_output(example_features, my_weights) 
# just like SFrames 2 numpy arrays can be elementwise subtracted with '-': 
errors = test_predictions - example_output # prediction errors in this case is just the -example_output
feature = example_features[:,0] # let's compute the derivative with respect to 'constant', the ":" indicates "all rows"
derivative = feature_derivative(errors, feature)
print derivative
print -np.sum(example_output)*2 # should be the same as derivative


-23345850022.0
-23345850022.0

Gradient Descent

Now we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of decrease and we're trying to minimize a cost function.

The amount by which we move in the negative gradient direction is called the 'step size'. We stop when we are 'sufficiently close' to the optimum. We define this by requiring that the magnitude (length) of the gradient vector to be smaller than a fixed 'tolerance'.

With this in mind, complete the following gradient descent function below using your derivative function above. For each step in the gradient descent we update the weight for each feature befofe computing our stopping criteria


In [23]:
from math import sqrt # recall that the magnitude/length of a vector [g[0], g[1], g[2]] is sqrt(g[0]^2 + g[1]^2 + g[2]^2)

In [88]:
def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):
    converged = False 
    weights = np.array(initial_weights) # make sure it's a numpy array
    while not converged:
        # compute the predictions based on feature_matrix and weights using your predict_output() function
        predictions = predict_output(feature_matrix, weights)
        # compute the errors as predictions - output
        errors = predictions - output
        gradient_sum_squares = 0 # initialize the gradient sum of squares
        # while we haven't reached the tolerance yet, update each feature's weight
        for i in range(len(weights)): # loop over each weight
            # Recall that feature_matrix[:, i] is the feature column associated with weights[i]
            # compute the derivative for weight[i]:
            derivative = feature_derivative(errors, feature_matrix[:,i])
            # add the squared value of the derivative to the gradient magnitude (for assessing convergence)
            gradient_sum_squares += derivative ** 2
            # subtract the step size times the derivative from the current weight
            weights[i] -= step_size * derivative
        # compute the square-root of the gradient sum of squares to get the gradient matnigude:
        gradient_magnitude = sqrt(gradient_sum_squares)
        print gradient_magnitude
        if gradient_magnitude < tolerance:
            converged = True
    return(weights)

A few things to note before we run the gradient descent. Since the gradient is a sum over all the data points and involves a product of an error and a feature the gradient itself will be very large since the features are large (squarefeet) and the output is large (prices). So while you might expect "tolerance" to be small, small is only relative to the size of the features.

For similar reasons the step size will be much smaller than you might expect but this is because the gradient has such large values.

Running the Gradient Descent as Simple Regression

First let's split the data into training and test data.


In [20]:
train_data,test_data = sales.random_split(.8,seed=0)

Although the gradient descent is designed for multiple regression since the constant is now a feature we can use the gradient descent function to estimat the parameters in the simple regression on squarefeet. The folowing cell sets up the feature_matrix, output, initial weights and step size for the first model:


In [89]:
# let's test out the gradient descent
simple_features = ['sqft_living']
my_output = 'price'
(simple_feature_matrix, output) = get_numpy_data(train_data, simple_features, my_output)
initial_weights = np.array([-47000., 1.])
step_size = 7e-12
tolerance = 2.5e7
sgd_weights = regression_gradient_descent(simple_feature_matrix, output, initial_weights, step_size, tolerance)


5.05515307744e+13
1.31274510235e+13
3.40899608253e+12
8.852635801e+11
2.2988926572e+11
59698688259.7
15502826422.1
4025844401.51
1045449748.16
271487891.86
70504114.6868
18320016.74

Next run your gradient descent with the above parameters.

How do your weights compare to those achieved in week 1 (don't expect them to be exactly the same)?

Quiz Question: What is the value of the weight for sqft_living -- the second element of ‘simple_weights’ (rounded to 1 decimal place)?


In [90]:
sgd_weights


Out[90]:
array([-46999.88716555,    281.91211912])

Use your newly estimated weights and your predict_output() function to compute the predictions on all the TEST data (you will need to create a numpy array of the test feature_matrix and test output first:


In [32]:
(test_simple_feature_matrix, test_output) = get_numpy_data(test_data, simple_features, my_output)

Now compute your predictions using test_simple_feature_matrix and your weights from above.


In [101]:
predictions = predict_output(test_simple_feature_matrix, sgd_weights)

Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 1 (round to nearest dollar)?


In [102]:
predictions[:1]


Out[102]:
[356134.44317092968]

Now that you have the predictions on test data, compute the RSS on the test data set. Save this value for comparison later. Recall that RSS is the sum of the squared errors (difference between prediction and output).


In [70]:
residuals = [(predictions[i] - test_data[i]['price']) ** 2 for i in range(len(predictions))]

In [71]:
print sum(residuals)


2.75393143376e+14

Running a multiple regression

Now we will use more than one actual feature. Use the following code to produce the weights for a second model with the following parameters:


In [78]:
train_data[:1]


Out[78]:
id date price bedrooms bathrooms sqft_living sqft_lot floors waterfront
7129300520 2014-10-13 00:00:00+00:00 221900.0 3.0 1.0 1180.0 5650 1 0
view condition grade sqft_above sqft_basement yr_built yr_renovated zipcode lat
0 3 7 1180 0 1955 0 98178 47.51123398
long sqft_living15 sqft_lot15 constant
-122.25677536 1340.0 5650.0 1
[1 rows x 22 columns]

In [105]:
model_features = ['sqft_living', 'sqft_living15'] # sqft_living15 is the average squarefeet for the nearest 15 neighbors. 
my_output = 'price'
(feature_matrix, output) = get_numpy_data(train_data, model_features, my_output)
initial_weights = np.array([-100000., 1., 1.])
step_size = 4e-12
tolerance = 1e9
sgd_weights_2 = regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance)


7.30720205489e+13
2.26732209651e+13
7.0607945821e+12
2.27568239427e+12
9.28984105638e+11
6.56307425178e+11
6.10615351821e+11
5.93078765307e+11
5.78705920128e+11
5.64945676163e+11
5.51538681425e+11
5.38452422879e+11
5.25676912708e+11
5.1320454369e+11
5.01028100319e+11
4.89140559101e+11
4.77535065233e+11
4.66204926754e+11
4.55143610499e+11
4.44344738312e+11
4.33802083366e+11
4.23509566576e+11
4.1346125309e+11
4.03651348867e+11
3.9407419734e+11
3.84724276147e+11
3.75596193956e+11
3.66684687348e+11
3.57984617786e+11
3.49490968654e+11
3.41198842358e+11
3.33103457507e+11
3.25200146157e+11
3.17484351114e+11
3.09951623311e+11
3.02597619241e+11
2.9541809845e+11
2.88408921097e+11
2.81566045563e+11
2.74885526122e+11
2.68363510666e+11
2.6199623848e+11
2.55780038082e+11
2.49711325096e+11
2.43786600194e+11
2.3800244707e+11
2.32355530477e+11
2.26842594301e+11
2.21460459683e+11
2.16206023185e+11
2.11076255005e+11
2.06068197225e+11
2.01178962108e+11
1.96405730433e+11
1.91745749866e+11
1.8719633338e+11
1.82754857697e+11
1.78418761783e+11
1.74185545366e+11
1.70052767496e+11
1.66018045138e+11
1.62079051799e+11
1.58233516183e+11
1.54479220884e+11
1.50814001109e+11
1.47235743424e+11
1.43742384541e+11
1.40331910127e+11
1.37002353639e+11
1.33751795195e+11
1.30578360464e+11
1.27480219586e+11
1.24455586117e+11
1.21502715998e+11
1.1861990655e+11
1.15805495494e+11
1.13057859988e+11
1.10375415697e+11
1.07756615874e+11
1.05199950471e+11
1.0270394527e+11
1.00267161028e+11
97888192650.6
95565668382.2
93298249012.9
91084627107.5
88923526251.5
86813700314.9
84753932733.7
82743035808.5
80779850019.8
78863243358.8
76992110675.6
75165373040.8
73381977124.6
71640894588.5
69941121492.5
68281677716.8
66661606395.9
65079973367.3
63535866632.7
62028395832.0
60556691730.4
59119905716.4
57717209313.2
56347793700.5
55010869248.6
53705665062.4
52431428537.5
51187424926.0
49972936913.0
48787264202.4
47629723114.0
46499646188.5
45396381803.0
44319293795.4
43267761097.0
42241177375.0
41238950682.7
40260503117.9
39305270490.1
38372701994.6
37462259895.7
36573419215.8
35705667433.4
34858504186.9
34031440986.6
33224000933.0
32435718441.4
31666138973.8
30914818776.8
30181324625.4
29465233573.7
28766132710.5
28083618921.5
27417298657.0
26766787704.6
26131710967.9
25511702250.0
24906404042.8
24315467320.2
23738551337.5
23175323434.3
22625458843.3
22088640502.6
21564558873.0
21052911759.4
20553404136.9
20065747980.3
19589662098.2
19124871970.9
18671109592.0
18228113313.7
17795627696.4
17373403361.1
16961196845.6
16558770464.0
16165892170.0
15782335422.9
15407879056.9
15042307153.7
14685408917.8
14336978555.2
13996815154.7
13664722572.0
13340509316.2
13023988440.4
12714977432.6
12413298111.7
12118776523.7
11831242842.3
11550531270.3
11276479944.3
11008930841.3
10747729687.6
10492725870.0
10243772348.6
10000725572.3
9763445395.81
9531794999.22
9305640808.63
9084852419.46
8869302521.1
8658866823.56
8453423985.82
8252855545.78
8057045852.07
7865881997.24
7679253752.75
7497053505.37
7319176195.12
7145519254.73
6975982550.45
6810468324.33
6648881137.87
6491127816.97
6337117398.19
6186761076.33
6039972153.21
5896665987.68
5756759946.78
5620173358.17
5486827463.54
5356645373.22
5229552021.85
5105474125.1
4984340137.41
4866080210.72
4750626154.21
4637911394.97
4527870939.63
4420441336.86
4315560640.81
4213168375.35
4113205499.26
4015614372.13
3920338721.13
3827323608.6
3736515400.34
3647861734.68
3561311492.31
3476814766.8
3394322835.79
3313788132.94
3235164220.48
3158405762.43
3083468498.48
3010309218.43
2938885737.33
2869156871.08
2801082412.77
2734623109.42
2669740639.4
2606397590.29
2544557437.34
2484184522.4
2425244033.35
2367701984.03
2311525194.65
2256681272.66
2203138594.06
2150866285.15
2099834204.79
2050012926.95
2001373723.78
1953888549.02
1907530021.87
1862271411.15
1818086619.93
1774950170.46
1732837189.48
1691723393.87
1651585076.68
1612399093.43
1574142848.76
1536794283.43
1500331861.58
1464734558.32
1429981847.59
1396053690.35
1362930523.01
1330593246.15
1299023213.51
1268202221.23
1238112497.38
1208736691.66
1180057865.46
1152059482.05
1124725397.05
1098039849.12
1071987450.91
1046553180.11
1021722370.88
997480705.317

In [106]:
sgd_weights_2


Out[106]:
array([ -9.99999688e+04,   2.45072603e+02,   6.52795277e+01])

Use the above parameters to estimate the model weights. Record these values for your quiz.

Use your newly estimated weights and the predict_output function to compute the predictions on the TEST data. Don't forget to create a numpy array for these features from the test set first!


In [107]:
(test_feature_matrix, test_output) = get_numpy_data(test_data, model_features, my_output)
predictions_2 = predict_output(test_feature_matrix, sgd_weights_2)

Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 2 (round to nearest dollar)?


In [112]:
predictions_2[:1]


Out[112]:
[366651.41203655908]

What is the actual price for the 1st house in the test data set?


In [97]:
test_data[0]['price']


Out[97]:
310000.0

Quiz Question: Which estimate was closer to the true price for the 1st house on the Test data set, model 1 or model 2?

Now use your predictions and the output to compute the RSS for model 2 on TEST data.


In [99]:
residuals_2 = [(predictions_2[i] - test_data[i]['price']) ** 2 for i in range(len(predictions))]
print sum(residuals_2)


2.70263446465e+14

Quiz Question: Which model (1 or 2) has lowest RSS on all of the TEST data?


In [ ]: