Regression Week 3: Assessing Fit (polynomial regression)

In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will:

  • Write a function to take an SArray and a degree and return an SFrame where each column is the SArray to a polynomial value up to the total degree e.g. degree = 3 then column 1 is the SArray column 2 is the SArray squared and column 3 is the SArray cubed
  • Use matplotlib to visualize polynomial regressions
  • Use matplotlib to visualize the same polynomial degree on different subsets of the data
  • Use a validation set to select a polynomial degree
  • Assess the final fit using test data

We will continue to use the House data from previous notebooks.

Fire up graphlab create


In [1]:
import graphlab

Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers up to the maximal degree.

The easiest way to apply a power to an SArray is to use the .apply() and lambda x: functions. For example to take the example array and compute the third power we can do as follows: (note running this cell the first time may take longer than expected since it loads graphlab)


In [2]:
tmp = graphlab.SArray([1., 2., 3.])
tmp_cubed = tmp.apply(lambda x: x**3)
print tmp
print tmp_cubed


[INFO] 1450435124 : INFO:     (initialize_globals_from_environment:282): Setting configuration variable GRAPHLAB_FILEIO_ALTERNATIVE_SSL_CERT_FILE to /home/zax/anaconda/lib/python2.7/site-packages/certifi/cacert.pem
1450435124 : 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 iliassweb@gmail.com and will expire on September 22, 2016. For commercial licensing options, visit https://dato.com/buy/.

[INFO] Start server at: ipc:///tmp/graphlab_server-12095 - Server binary: /home/zax/anaconda/lib/python2.7/site-packages/graphlab/unity_server - Server log: /tmp/graphlab_server_1450435124.log
[INFO] GraphLab Server Version: 1.7.1
[1.0, 2.0, 3.0]
[1.0, 8.0, 27.0]

We can create an empty SFrame using graphlab.SFrame() and then add any columns to it with ex_sframe['column_name'] = value. For example we create an empty SFrame and make the column 'power_1' to be the first power of tmp (i.e. tmp itself).


In [3]:
ex_sframe = graphlab.SFrame()
ex_sframe['power_1'] = tmp
print ex_sframe


+---------+
| power_1 |
+---------+
|   1.0   |
|   2.0   |
|   3.0   |
+---------+
[3 rows x 1 columns]

Polynomial_sframe function

Using the hints above complete the following function to create an SFrame consisting of the powers of an SArray up to a specific degree:


In [4]:
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 > 1
    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
            poly_sframe[name] = feature**power

    return poly_sframe

To test your function consider the smaller tmp variable and what you would expect the outcome of the following call:


In [5]:
print polynomial_sframe(tmp, 3)


+---------+---------+---------+
| power_1 | power_2 | power_3 |
+---------+---------+---------+
|   1.0   |   1.0   |   1.0   |
|   2.0   |   4.0   |   8.0   |
|   3.0   |   9.0   |   27.0  |
+---------+---------+---------+
[3 rows x 3 columns]

Visualizing polynomial regression

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


In [6]:
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 [8]:
sales = sales.sort(['sqft_living', 'price'])

Let's start with a degree 1 polynomial using 'sqft_living' (i.e. a line) to predict 'price' and plot what it looks like.


In [9]:
poly1_data = polynomial_sframe(sales['sqft_living'], 1)
poly1_data['price'] = sales['price'] # add price to the data since it's the target

NOTE: for all the models in this notebook use validation_set = None to ensure that all results are consistent across users.


In [10]:
model1 = graphlab.linear_regression.create(poly1_data, target = 'price', features = ['power_1'], validation_set = None)


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 21613
PROGRESS: Number of features          : 1
PROGRESS: Number of unpacked features : 1
PROGRESS: Number of coefficients    : 2
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 1.105339     | 4362074.696077     | 261440.790724 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:

In [11]:
#let's take a look at the weights before we plot
model1.get("coefficients")


Out[11]:
name index value
(intercept) None -43579.0852515
power_1 None 280.622770886
[2 rows x 3 columns]

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

In [13]:
plt.plot(poly1_data['power_1'],poly1_data['price'],'.',
        poly1_data['power_1'], model1.predict(poly1_data),'-')


Out[13]:
[<matplotlib.lines.Line2D at 0x7f216a4f8310>,
 <matplotlib.lines.Line2D at 0x7f216a4f8410>]

Let's unpack that plt.plot() command. The first pair of SArrays we passed are the 1st power of sqft and the actual price we then ask it to print these as dots '.'. The next pair we pass is the 1st power of sqft and the predicted values from the linear model. We ask these to be plotted as a line '-'.

We can see, not surprisingly, that the predicted values all fall on a line, specifically the one with slope 280 and intercept -43579. What if we wanted to plot a second degree polynomial?


In [19]:
poly2_data = polynomial_sframe(sales['sqft_living'], 2)
my_features = poly2_data.column_names() # get the name of the features
poly2_data['price'] = sales['price'] # add price to the data since it's the target
model2 = graphlab.linear_regression.create(poly2_data, target = 'price', features = my_features, validation_set = None)


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 21613
PROGRESS: Number of features          : 2
PROGRESS: Number of unpacked features : 2
PROGRESS: Number of coefficients    : 3
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.016080     | 5913020.984255     | 250948.368758 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:

In [15]:
model2.get("coefficients")


Out[15]:
name index value
(intercept) None 199222.496445
power_1 None 67.9940640677
power_2 None 0.0385812312789
[3 rows x 3 columns]

In [20]:
plt.plot(poly2_data['power_1'],poly2_data['price'],'.',
        poly2_data['power_1'], model2.predict(poly2_data),'-')


Out[20]:
[<matplotlib.lines.Line2D at 0x7f216a223310>,
 <matplotlib.lines.Line2D at 0x7f216a2234d0>]

The resulting model looks like half a parabola. Try on your own to see what the cubic looks like:


In [21]:
poly3_data = polynomial_sframe(sales['sqft_living'], 3)
my_features = poly3_data.column_names() # get the name of the features
poly3_data['price'] = sales['price'] # add price to the data since it's the target
model3 = graphlab.linear_regression.create(poly3_data, target = 'price', features = my_features, validation_set = None)


PROGRESS: Linear regression:
PROGRESS: --------------------------------------------------------
PROGRESS: Number of examples          : 21613
PROGRESS: Number of features          : 3
PROGRESS: Number of unpacked features : 3
PROGRESS: Number of coefficients    : 4
PROGRESS: Starting Newton Method
PROGRESS: --------------------------------------------------------
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | Iteration | Passes   | Elapsed Time | Training-max_error | Training-rmse |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: | 1         | 2        | 0.017263     | 3261066.736007     | 249261.286346 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:

In [22]:
plt.plot(poly3_data['power_1'],poly3_data['price'],'.',
        poly3_data['power_1'], model3.predict(poly3_data),'-')


Out[22]:
[<matplotlib.lines.Line2D at 0x7f216a165a50>,
 <matplotlib.lines.Line2D at 0x7f216a165c10>]

Now try a 15th degree polynomial:


In [38]:
poly15_data = polynomial_sframe(sales['sqft_living'], 15)
my_features = 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_features, 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        | 0.046624     | 2662308.584337     | 245690.511190 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:

In [39]:
plt.plot(poly15_data['power_1'],poly15_data['price'],'.',
        poly15_data['power_1'], model15.predict(poly15_data),'-')


Out[39]:
[<matplotlib.lines.Line2D at 0x7f2169d70110>,
 <matplotlib.lines.Line2D at 0x7f2169d702d0>]

What do you think of the 15th degree polynomial? Do you think this is appropriate? If we were to change the data do you think you'd get pretty much the same curve? Let's take a look.

Changing the data and re-learning

We're going to split the sales data into four subsets of roughly equal size. Then you will estimate a 15th degree polynomial model on all four subsets of the data. Print the coefficients (you should use .print_rows(num_rows = 16) to view all of them) and plot the resulting fit (as we did above). The quiz will ask you some questions about these results.

To split the sales data into four subsets, we perform the following steps:

  • First split sales into 2 subsets with .random_split(0.5, seed=0).
  • Next split the resulting subsets into 2 more subsets each. Use .random_split(0.5, seed=0).

We set seed=0 in these steps so that different users get consistent results. You should end up with 4 subsets (set_1, set_2, set_3, set_4) of approximately equal size.


In [42]:
(temp_1, temp_2) = sales.random_split(0.5, seed=0)
(set_1, set_2) = temp_1.random_split(0.5, seed=0)
(set_3, set_4) = temp_2.random_split(0.5, seed=0)

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


In [47]:
# Set_1
poly15_set_1_data = polynomial_sframe(set_1['sqft_living'], 15)
my_features = poly15_set_1_data.column_names() # get the name of the features
poly15_set_1_data['price'] = set_1['price'] # add price to the data since it's the target
model_set_1 = graphlab.linear_regression.create(poly15_set_1_data, target = 'price', features = my_features, validation_set = None)

model_set_1.get('coefficients').print_rows(num_rows=16)
# Ploting
plt.plot(poly15_set_1_data['power_1'],poly15_set_1_data['price'],'.',
        poly15_set_1_data['power_1'], model_set_1.predict(poly15_set_1_data),'-')


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.014695     | 2195218.932304     | 248858.822200 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
+-------------+-------+--------------------+
|     name    | index |       value        |
+-------------+-------+--------------------+
| (intercept) |  None |   223312.750249    |
|   power_1   |  None |   118.086127587    |
|   power_2   |  None |  -0.0473482011344  |
|   power_3   |  None | 3.25310342469e-05  |
|   power_4   |  None | -3.32372152561e-09 |
|   power_5   |  None | -9.75830457761e-14 |
|   power_6   |  None | 1.15440303426e-17  |
|   power_7   |  None | 1.05145869404e-21  |
|   power_8   |  None | 3.46049616546e-26  |
|   power_9   |  None | -1.09654454168e-30 |
|   power_10  |  None | -2.42031812009e-34 |
|   power_11  |  None | -1.99601206824e-38 |
|   power_12  |  None | -1.07709903827e-42 |
|   power_13  |  None | -2.72862818141e-47 |
|   power_14  |  None | 2.44782693088e-51  |
|   power_15  |  None | 5.01975232933e-55  |
+-------------+-------+--------------------+
[16 rows x 3 columns]

Out[47]:
[<matplotlib.lines.Line2D at 0x7f2169cca550>,
 <matplotlib.lines.Line2D at 0x7f2169cca710>]

In [48]:
# Set_2
poly15_set_2_data = polynomial_sframe(set_2['sqft_living'], 15)
my_features = poly15_set_2_data.column_names() # get the name of the features
poly15_set_2_data['price'] = set_2['price'] # add price to the data since it's the target
model_set_2 = graphlab.linear_regression.create(poly15_set_2_data, target = 'price', features = my_features, validation_set = None)

model_set_2.get('coefficients').print_rows(num_rows=16)
# Ploting
plt.plot(poly15_set_2_data['power_1'],poly15_set_2_data['price'],'.',
        poly15_set_2_data['power_1'], model_set_2.predict(poly15_set_2_data),'-')


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.015174     | 2069212.978547     | 234840.067186 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
+-------------+-------+--------------------+
|     name    | index |       value        |
+-------------+-------+--------------------+
| (intercept) |  None |   89836.5077327    |
|   power_1   |  None |   319.806946764    |
|   power_2   |  None |  -0.103315397042   |
|   power_3   |  None | 1.06682476069e-05  |
|   power_4   |  None | 5.75577097718e-09  |
|   power_5   |  None | -2.5466346476e-13  |
|   power_6   |  None | -1.09641345061e-16 |
|   power_7   |  None | -6.36458441713e-21 |
|   power_8   |  None | 5.52560416991e-25  |
|   power_9   |  None | 1.35082038963e-28  |
|   power_10  |  None |  1.1840818825e-32  |
|   power_11  |  None | 1.98348000558e-37  |
|   power_12  |  None | -9.9253359041e-41  |
|   power_13  |  None | -1.60834847047e-44 |
|   power_14  |  None | -9.12006024287e-49 |
|   power_15  |  None | 1.68636658328e-52  |
+-------------+-------+--------------------+
[16 rows x 3 columns]

Out[48]:
[<matplotlib.lines.Line2D at 0x7f2169bcc890>,
 <matplotlib.lines.Line2D at 0x7f2169bcca50>]

In [50]:
# Set_3
poly15_set_3_data = polynomial_sframe(set_3['sqft_living'], 15)
my_features = poly15_set_3_data.column_names() # get the name of the features
poly15_set_3_data['price'] = set_3['price'] # add price to the data since it's the target
model_set_3 = graphlab.linear_regression.create(poly15_set_3_data, target = 'price', features = my_features, validation_set = None)

model_set_3.get('coefficients').print_rows(num_rows=16)
# Ploting
plt.plot(poly15_set_3_data['power_1'],poly15_set_3_data['price'],'.',
        poly15_set_3_data['power_1'], model_set_3.predict(poly15_set_3_data),'-')


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.020432     | 2269769.506521     | 251460.072754 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
+-------------+-------+--------------------+
|     name    | index |       value        |
+-------------+-------+--------------------+
| (intercept) |  None |   87317.9795547    |
|   power_1   |  None |   356.304911045    |
|   power_2   |  None |  -0.164817442809   |
|   power_3   |  None | 4.40424992697e-05  |
|   power_4   |  None | 6.48234876179e-10  |
|   power_5   |  None | -6.75253226587e-13 |
|   power_6   |  None | -3.36842592661e-17 |
|   power_7   |  None | 3.60999704242e-21  |
|   power_8   |  None | 6.46999725625e-25  |
|   power_9   |  None | 4.23639388865e-29  |
|   power_10  |  None | -3.62149427043e-34 |
|   power_11  |  None | -4.27119527274e-37 |
|   power_12  |  None | -5.61445971705e-41 |
|   power_13  |  None | -3.87452772861e-45 |
|   power_14  |  None | 4.69430359483e-50  |
|   power_15  |  None | 6.39045885992e-53  |
+-------------+-------+--------------------+
[16 rows x 3 columns]

Out[50]:
[<matplotlib.lines.Line2D at 0x7f21698b7e50>,
 <matplotlib.lines.Line2D at 0x7f21698c80d0>]

In [51]:
# Set_4
poly15_set_4_data = polynomial_sframe(set_4['sqft_living'], 15)
my_features = poly15_set_4_data.column_names() # get the name of the features
poly15_set_4_data['price'] = set_4['price'] # add price to the data since it's the target
model_set_4 = graphlab.linear_regression.create(poly15_set_4_data, target = 'price', features = my_features, validation_set = None)

model_set_4.get('coefficients').print_rows(num_rows=16)
# Ploting
plt.plot(poly15_set_4_data['power_1'],poly15_set_4_data['price'],'.',
        poly15_set_4_data['power_1'], model_set_4.predict(poly15_set_4_data),'-')


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.011116     | 2314893.173827     | 244563.136754 |
PROGRESS: +-----------+----------+--------------+--------------------+---------------+
PROGRESS: SUCCESS: Optimal solution found.
PROGRESS:
+-------------+-------+--------------------+
|     name    | index |       value        |
+-------------+-------+--------------------+
| (intercept) |  None |   259020.879454    |
|   power_1   |  None |   -31.7277162076   |
|   power_2   |  None |   0.109702769619   |
|   power_3   |  None | -1.58383847337e-05 |
|   power_4   |  None | -4.47660623786e-09 |
|   power_5   |  None | 1.13976573482e-12  |
|   power_6   |  None | 1.97669120547e-16  |
|   power_7   |  None | -6.15783678661e-21 |
|   power_8   |  None | -4.88012304074e-24 |
|   power_9   |  None | -6.62186781351e-28 |
|   power_10  |  None | -2.70631583161e-32 |
|   power_11  |  None | 6.72370411466e-36  |
|   power_12  |  None | 1.74115646268e-39  |
|   power_13  |  None | 2.09188375728e-43  |
|   power_14  |  None | 4.78015566061e-48  |
|   power_15  |  None | -4.74535333101e-51 |
+-------------+-------+--------------------+
[16 rows x 3 columns]

Out[51]:
[<matplotlib.lines.Line2D at 0x7f216987de10>,
 <matplotlib.lines.Line2D at 0x7f216987dfd0>]

Some questions you will be asked on your quiz:

Quiz Question: Is the sign (positive or negative) for power_15 the same in all four models?

Quiz Question: (True/False) the plotted fitted lines look the same in all four plots

Selecting a Polynomial Degree

Whenever we have a "magic" parameter like the degree of the polynomial there is one well-known way to select these parameters: validation set. (We will explore another approach in week 4).

We split the sales dataset 3-way into training set, test set, and validation set as follows:

  • Split our sales data into 2 sets: training_and_validation and testing. Use random_split(0.9, seed=1).
  • Further split our training data into two sets: training and validation. Use random_split(0.5, seed=1).

Again, we set seed=1 to obtain consistent results for different users.


In [52]:
(training_and_validation, testing) = sales.random_split(0.9, seed=1)
(training, validation) = training_and_validation.random_split(0.5, seed=1)

Next you should write a loop that does the following:

  • For degree in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] (to get this in python type range(1, 15+1))
    • Build an SFrame of polynomial data of train_data['sqft_living'] at the current degree
    • hint: my_features = poly_data.column_names() gives you a list e.g. ['power_1', 'power_2', 'power_3'] which you might find useful for graphlab.linear_regression.create( features = my_features)
    • Add train_data['price'] to the polynomial SFrame
    • Learn a polynomial regression model to sqft vs price with that degree on TRAIN data
    • Compute the RSS on VALIDATION data (here you will want to use .predict()) for that degree and you will need to make a polynmial SFrame using validation data.
  • Report which degree had the lowest RSS on validation data (remember python indexes from 0)

(Note you can turn off the print out of linear_regression.create() with verbose = False)


In [72]:
for degree in xrange(1, 16):
    poly_data = polynomial_sframe(training['sqft_living'], degree)
    my_features = poly_data.column_names() # get the name of the features
    poly_data['price'] = training['price'] # add price to the data since it's the 
    model = graphlab.linear_regression.create(poly_data, target = 'price', features = my_features, validation_set = None, verbose=False)
    validation_data = polynomial_sframe(validation['sqft_living'], degree)
    validation_data['price'] = validation['price']
    residual =validation['price'] - model.predict(validation_data) 
    
    rs = residual.apply(lambda x: x**2)
    
    rss = rs.sum()
    print "RSS ", degree, rss


RSS  1 6.76709775198e+14
RSS  2 6.07090530698e+14
RSS  3 6.16714574533e+14
RSS  4 6.09129230654e+14
RSS  5 5.99177138584e+14
RSS  6 5.89182477809e+14
RSS  7 5.91717038418e+14
RSS  8 6.01558237777e+14
RSS  9 6.12563853988e+14
RSS  10 6.21744288936e+14
RSS  11 6.27012012704e+14
RSS  12 6.27757914772e+14
RSS  13 6.24738503262e+14
RSS  14 6.19369705905e+14
RSS  15 6.13089202414e+14

Quiz Question: Which degree (1, 2, …, 15) had the lowest RSS on Validation data?

Now that you have chosen the degree of your polynomial using validation data, compute the RSS of this model on TEST data. Report the RSS on your quiz.


In [70]:
# RSS on test data
poly_data_selected = polynomial_sframe(training['sqft_living'], 6)

my_features = poly_data_selected.column_names() # get the name of the features
poly_data_selected['price'] = training['price'] # add price to the data since it's the 
model_selected = graphlab.linear_regression.create(poly_data_selected, target = 'price', features = my_features, validation_set = None, verbose=False)
test_data = polynomial_sframe(testing['sqft_living'], 6)
test_data['price'] = testing['price']
residual_1 = testing['price'] - model.predict(test_data) 

rs = residual_1.apply(lambda x: x**2)

rss = rs.sum()
print "RSS ", rss


RSS  1.20430267816e+14

Quiz Question: what is the RSS on TEST data for the model with the degree selected from Validation data? (Make sure you got the correct degree from the previous question)


In [ ]:

Testing other routines


In [68]:
for i in range(1,15+1):
    current_degree = polynomial_sframe(training['sqft_living'], i)
    my_features = current_degree.column_names() # get the name of the features
    current_degree['price'] = training['price'] # add price to the data since it's the target
    model = graphlab.linear_regression.create(current_degree, target = 'price', features = my_features, validation_set = None,verbose = False)
    ##Compute the RSS on VALIDATION data
    validation_data = polynomial_sframe(validation['sqft_living'], i)
    predictions = model.predict(validation_data)
    residuals = validation['price'] - predictions
    rss_1 = sum(residuals * residuals)
    print i
    print rss_1


1
6.76709775198e+14
2
6.07090530698e+14
3
6.16714574533e+14
4
6.09129230654e+14
5
5.99177138584e+14
6
5.89182477809e+14
7
5.91717038418e+14
8
6.01558237777e+14
9
6.12563853988e+14
10
6.21744288936e+14
11
6.27012012704e+14
12
6.27757914772e+14
13
6.24738503262e+14
14
6.19369705905e+14
15
6.13089202414e+14

In [ ]: