Lecture 12: September 1st, 2023#

šŸŽƒ šŸ Happy September!#

Remember! Monday is a holiday, so there will be no lecture or discussion :( I’ll post some videos that you can watch on Tuesday so that we don’t get too far behind.

Performance measures for regression#

Let’s consider the following dataset, which only has four points.

import pandas as pd
import altair as alt
import numpy as np
df = pd.DataFrame({
    "x":np.arange(4),
    "y":[0,2,-10,6]},
)
df
x y
0 0 0
1 1 2
2 2 -10
3 3 6
  • Plot df using Altair to see how the data looks.

alt.Chart(df).mark_circle(size=150).encode(
    x="x",
    y="y"
)
  • Our goal is to figure out which of the following linear models best fits our data.

    • Line A: \(f(x) = 2x\)

    • Line B: \(f(x) = 0.6x - 1.4\)

  • Add columns to df corresponding to these lines. Name the new columns ā€œlineAā€ and ā€œlineBā€.

#correct, but overly complicated
df["lineA"] = df["x"].map(lambda x: 2*x)
#better
df["lineA"] = 2*df["x"]
#Now, we do the same thing for line B
df["lineB"] = 0.6*df["x"] - 1.4
df
x y lineA lineB
0 0 0 0 -1.4
1 1 2 2 -0.8
2 2 -10 4 -0.2
3 3 6 6 0.4

Line A and Line B represent two different possible linear models for our data.

  • Plot the data together with these lines, using the color red for Line A and the color black for Line B. Use a base chart so that you are not repeating the same code three times.

The idea of a base chart is that we first include the data that’s common to all of the charts.

base = alt.Chart(df).encode(
    x="x"
)

Notice, base on its own gives an error if we try to see it; it’s not a valid chart (notice it doesn’t have something like mark_cirlce/mark_line etc.)

base
---------------------------------------------------------------------------
SchemaValidationError                     Traceback (most recent call last)
File ~/venv/lib/python3.9/site-packages/altair/vegalite/v5/api.py:2520, in Chart.to_dict(self, *args, **kwargs)
   2518     copy.data = core.InlineData(values=[{}])
   2519     return super(Chart, copy).to_dict(*args, **kwargs)
-> 2520 return super().to_dict(*args, **kwargs)

File ~/venv/lib/python3.9/site-packages/altair/vegalite/v5/api.py:850, in TopLevelMixin.to_dict(self, *args, **kwargs)
    845 kwargs["context"] = context
    847 # TopLevelMixin instance does not necessarily have to_dict defined
    848 # but due to how Altair is set up this should hold.
    849 # Too complex to type hint right now
--> 850 dct = super(TopLevelMixin, copy).to_dict(*args, **kwargs)  # type: ignore[misc]
    852 # TODO: following entries are added after validation. Should they be validated?
    853 if is_top_level:
    854     # since this is top-level we add $schema if it's missing

File ~/venv/lib/python3.9/site-packages/altair/utils/schemapi.py:814, in SchemaBase.to_dict(self, validate, ignore, context)
    807         self.validate(result)
    808     except jsonschema.ValidationError as err:
    809         # We do not raise `from err` as else the resulting
    810         # traceback is very long as it contains part
    811         # of the Vega-Lite schema. It would also first
    812         # show the less helpful ValidationError instead of
    813         # the more user friendly SchemaValidationError
--> 814         raise SchemaValidationError(self, err) from None
    815 return result

SchemaValidationError: '{'data': {'name': 'data-e85beb7529ff9a23a83e49d3894e7618'}, 'encoding': {'x': {'field': 'x', 'type': 'quantitative'}}}' is an invalid value.

'mark' is a required property
alt.Chart(...)
#Notice this is the same as the first plot from today
c1 = base.mark_circle(size=150).encode(y="y")
c1
#Now let's plot lineA
c2 = base.mark_line(color="red").encode(y="lineA")
c2
#Now let's plot lineB
c3 = base.mark_line(color="black").encode(y="lineB")
c3

Now, let’s see these three charts all together:

c1 + c2 + c3
  • Which line fits the data better?

There’s no single correct answer to this question! If you said black or red, we could justify either. It’s going to depend on how we measure ā€œbetterā€.

  • Using scikit-learn, find the line of best fit (Linear Regression) for this data. How does it compare to the above lines?

from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(df[["x"]],df["y"])
LinearRegression()
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
df
x y lineA lineB
0 0 0 0 -1.4
1 1 2 2 -0.8
2 2 -10 4 -0.2
3 3 6 6 0.4

Why did I set a target of ā€œyā€ and not something like ā€œlineAā€? Recall that we already have the equations for lineA and lineB. We want to find the line of best fit for our data, which we do not know the equation for.

#coeff
reg.coef_
array([0.6])
reg.intercept_
-1.4

Notice, this gives us lineB! This is the black line in our above plot, and it definitely appears to be a little worse of a fit than the red line…but sklearn is telling us this is the best line of all possible lines. What’s going on?

Recall, LinearRegression minimizes mean squared error (MSE). So, if we compute the MSE for both of the lines, we should see that line B performs better than line A.

  • Import the mean_squared_error function from sklearn.metrics. Which of our lines fits the data better according to this metric?

Important point: When computing errors (or loss functions), a smaller number is better.

from sklearn.metrics import mean_squared_error
mean_squared_error(df["y"],df["lineA"])
49.0
mean_squared_error(df["y"],df["lineB"])
34.300000000000004

According to MSE, Line B performs better. Recall, this is what ā€˜LinearRegression’ minimizes.

As a reminder, here is how MSE is computed:

df
x y lineA lineB
0 0 0 0 -1.4
1 1 2 2 -0.8
2 2 -10 4 -0.2
3 3 6 6 0.4
#compute MSE for lineA versus y by hand
((df["lineA"] - df["y"])**2).mean()
49.0
#now for lineB
((df["lineB"] - df["y"])**2).mean()
34.300000000000004
  • Import the mean_absolute_error function from sklearn.metrics. Which of our lines fits the data better according to this metric?

MAE works almost exactly the same as MSE, except now we take absolute instead of squaring to deal with possible negative values.

from sklearn.metrics import mean_absolute_error
mean_absolute_error(df["y"],df["lineA"])
3.5
mean_absolute_error(df["y"],df["lineB"])
4.9

Notice now that lineA performs better, since it has a smaller MAE.

#let's do this computation by hand
((df["lineA"] - df["y"]).abs()).mean()
3.5

Question from the chat: Which method for error is more precise?

No good answer; it’s going to depend on what you’re looking for in a model. One comment, is that you might be tempted to think that MAE is beter in this case because it produces smaller numbers than MSE, but this is not the case. There’s no good way to compare these different error measures. Another thing I’ve seen before (and something you can even see in this example) is that MSE tends to be more sensitive to outliers; this might be something to consider, depending on your data.

Main takeaways from this portion of the lecture: different performance measures will lead to different definitions of ā€œbestā€ fit. In theory, the smallest possible MSE/MAE woud be zero, but in this case it’s impossible since no line can go through all 4 data points. This is similar to real life examples as well, we never expect our data to be perfectly linear.

mean_squared_error(df["y"],df["y"])
0.0

More on Polynomial Regression#

In the last lecture, we saw how to fit our data to a degree three polynomial. This took quite a bit of work, so the focus of this portion of the lecture will be on how to automate some of those steps.

Generating Random Data#

deg = 3
rng = np.random.default_rng(seed=27)
m = rng.integers(low=-5, high=5, size=deg+1)
print(m)
df = pd.DataFrame({"x": np.arange(-3, 2, 0.1)})
df["y_true"] = 0
for i in range(len(m)):
    df["y_true"] += m[i]*df["x"]**i

df["y"] = df["y_true"] + rng.normal(scale=5, size=len(df))
[-5  1 -3 -2]
df
x y_true y
0 -3.000000e+00 19.000 23.824406
1 -2.900000e+00 15.648 10.237108
2 -2.800000e+00 12.584 16.919087
3 -2.700000e+00 9.796 8.955196
4 -2.600000e+00 7.272 6.323695
5 -2.500000e+00 5.000 10.602832
6 -2.400000e+00 2.968 0.784105
7 -2.300000e+00 1.164 -5.234227
8 -2.200000e+00 -0.424 -2.771499
9 -2.100000e+00 -1.808 -7.792136
10 -2.000000e+00 -3.000 -12.199286
11 -1.900000e+00 -4.012 -4.739785
12 -1.800000e+00 -4.856 -2.864605
13 -1.700000e+00 -5.544 -16.354306
14 -1.600000e+00 -6.088 -6.015613
15 -1.500000e+00 -6.500 -5.224009
16 -1.400000e+00 -6.792 -5.926045
17 -1.300000e+00 -6.976 -13.326468
18 -1.200000e+00 -7.064 -8.618807
19 -1.100000e+00 -7.068 -7.999078
20 -1.000000e+00 -7.000 -4.835120
21 -9.000000e-01 -6.872 -13.308757
22 -8.000000e-01 -6.696 -4.778936
23 -7.000000e-01 -6.484 -1.524600
24 -6.000000e-01 -6.248 -17.686227
25 -5.000000e-01 -6.000 -4.880304
26 -4.000000e-01 -5.752 -13.385067
27 -3.000000e-01 -5.516 -6.368335
28 -2.000000e-01 -5.304 -8.704742
29 -1.000000e-01 -5.128 1.240175
30 2.664535e-15 -5.000 -4.714457
31 1.000000e-01 -4.932 -0.955557
32 2.000000e-01 -4.936 -10.169895
33 3.000000e-01 -5.024 -2.721364
34 4.000000e-01 -5.208 1.903864
35 5.000000e-01 -5.500 -9.036285
36 6.000000e-01 -5.912 -2.582631
37 7.000000e-01 -6.456 -4.049151
38 8.000000e-01 -7.144 -7.467370
39 9.000000e-01 -7.988 -14.245467
40 1.000000e+00 -9.000 -7.584490
41 1.100000e+00 -10.192 -11.543440
42 1.200000e+00 -11.576 -8.565901
43 1.300000e+00 -13.164 -9.269588
44 1.400000e+00 -14.968 -7.295300
45 1.500000e+00 -17.000 -21.182783
46 1.600000e+00 -19.272 -14.946791
47 1.700000e+00 -21.796 -18.291899
48 1.800000e+00 -24.584 -24.206884
49 1.900000e+00 -27.648 -24.589037

Let’s pick through the above code in a little more depth

  • I’m trying to generate data that fits a cubic polynomial. Notice deg = 3 makes it easy to change the code if I want to pick a polynomial of a different degree.

  • The line m = rng.integers... is picking deg+1 random integers between -5 and 5, these will serve as the coefficients for our cubic polynomial: \(c_3x^3 + c_2x^2 + c_1x + c_0\).

  • Then we create a DataFrame that stores x values.

  • Lines 7-8 of the code build the polynomial for each value of x. The column ā€œy_trueā€ has perfectly cubic data.

  • The last part of the code adds random noise to our data so that it is not perfectly cubic. Notice we use normally distributed random numbers instead of uniformly distributed random numbers (from [0,1]) so that my noise is not all within 1 unit of the actualy data.

Notice, we can improve the code above by using enumerate.

m
array([-5,  1, -3, -2])

Recall that enumerate pairs the values of m with corresponding indices.

list(enumerate(m))
[(0, -5), (1, 1), (2, -3), (3, -2)]
help(enumerate)
Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable, start=0)
 |  
 |  Return an enumerate object.
 |  
 |    iterable
 |      an object supporting iteration
 |  
 |  The enumerate object yields pairs containing a count (from start, which
 |  defaults to zero) and a value yielded by the iterable argument.
 |  
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  __class_getitem__(...) from builtins.type
 |      See PEP 585
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
deg = 3
rng = np.random.default_rng(seed=27)
m = rng.integers(low=-5, high=5, size=deg+1)
print(m)
df = pd.DataFrame({"x": np.arange(-3, 2, 0.1)})
df["y_true"] = 0
for c in enumerate(m):
    df["y_true"] += c[1]*df["x"]**c[0]

df["y"] = df["y_true"] + rng.normal(scale=5, size=len(df))
[-5  1 -3 -2]
for c in enumerate(m):
    print(c)
(0, -5)
(1, 1)
(2, -3)
(3, -2)
  • Plot the noisy data so we have an idea of how it looks. Call the resulting chart c1.

c1 = alt.Chart(df).mark_circle().encode(
    x="x",
    y="y"
)
c1

Notice that our data looks roughly cubic, but not perfectly so. This is a good thing! We’ll see if sklearn can estimate the curve :)

PolynomialFeatures#

  • Demonstrate the PolynomialFeatures class from sklearn.preprocessing by evaluating it on the ā€œxā€ column in df. Use a degree value of 3. Note: this class uses transform rather than predict in the final step.

We still have our usual workflow: import > instantiate > fit > transform

from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=3)
type(poly)
sklearn.preprocessing._polynomial.PolynomialFeatures

This is a new-to-us object from sklearn!

df
x y_true y
0 -3.000000e+00 19.000 23.824406
1 -2.900000e+00 15.648 10.237108
2 -2.800000e+00 12.584 16.919087
3 -2.700000e+00 9.796 8.955196
4 -2.600000e+00 7.272 6.323695
5 -2.500000e+00 5.000 10.602832
6 -2.400000e+00 2.968 0.784105
7 -2.300000e+00 1.164 -5.234227
8 -2.200000e+00 -0.424 -2.771499
9 -2.100000e+00 -1.808 -7.792136
10 -2.000000e+00 -3.000 -12.199286
11 -1.900000e+00 -4.012 -4.739785
12 -1.800000e+00 -4.856 -2.864605
13 -1.700000e+00 -5.544 -16.354306
14 -1.600000e+00 -6.088 -6.015613
15 -1.500000e+00 -6.500 -5.224009
16 -1.400000e+00 -6.792 -5.926045
17 -1.300000e+00 -6.976 -13.326468
18 -1.200000e+00 -7.064 -8.618807
19 -1.100000e+00 -7.068 -7.999078
20 -1.000000e+00 -7.000 -4.835120
21 -9.000000e-01 -6.872 -13.308757
22 -8.000000e-01 -6.696 -4.778936
23 -7.000000e-01 -6.484 -1.524600
24 -6.000000e-01 -6.248 -17.686227
25 -5.000000e-01 -6.000 -4.880304
26 -4.000000e-01 -5.752 -13.385067
27 -3.000000e-01 -5.516 -6.368335
28 -2.000000e-01 -5.304 -8.704742
29 -1.000000e-01 -5.128 1.240175
30 2.664535e-15 -5.000 -4.714457
31 1.000000e-01 -4.932 -0.955557
32 2.000000e-01 -4.936 -10.169895
33 3.000000e-01 -5.024 -2.721364
34 4.000000e-01 -5.208 1.903864
35 5.000000e-01 -5.500 -9.036285
36 6.000000e-01 -5.912 -2.582631
37 7.000000e-01 -6.456 -4.049151
38 8.000000e-01 -7.144 -7.467370
39 9.000000e-01 -7.988 -14.245467
40 1.000000e+00 -9.000 -7.584490
41 1.100000e+00 -10.192 -11.543440
42 1.200000e+00 -11.576 -8.565901
43 1.300000e+00 -13.164 -9.269588
44 1.400000e+00 -14.968 -7.295300
45 1.500000e+00 -17.000 -21.182783
46 1.600000e+00 -19.272 -14.946791
47 1.700000e+00 -21.796 -18.291899
48 1.800000e+00 -24.584 -24.206884
49 1.900000e+00 -27.648 -24.589037
poly.fit(df[["x"]])
PolynomialFeatures(degree=3)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
#gives an error :(
poly.predict(df[["x"]])
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [44], line 2
      1 #gives an error :(
----> 2 poly.predict(df[["x"]])

AttributeError: 'PolynomialFeatures' object has no attribute 'predict'
#notice this result is kind of difficult to understand
poly.transform(df[["x"]])
array([[ 1.00000000e+00, -3.00000000e+00,  9.00000000e+00,
        -2.70000000e+01],
       [ 1.00000000e+00, -2.90000000e+00,  8.41000000e+00,
        -2.43890000e+01],
       [ 1.00000000e+00, -2.80000000e+00,  7.84000000e+00,
        -2.19520000e+01],
       [ 1.00000000e+00, -2.70000000e+00,  7.29000000e+00,
        -1.96830000e+01],
       [ 1.00000000e+00, -2.60000000e+00,  6.76000000e+00,
        -1.75760000e+01],
       [ 1.00000000e+00, -2.50000000e+00,  6.25000000e+00,
        -1.56250000e+01],
       [ 1.00000000e+00, -2.40000000e+00,  5.76000000e+00,
        -1.38240000e+01],
       [ 1.00000000e+00, -2.30000000e+00,  5.29000000e+00,
        -1.21670000e+01],
       [ 1.00000000e+00, -2.20000000e+00,  4.84000000e+00,
        -1.06480000e+01],
       [ 1.00000000e+00, -2.10000000e+00,  4.41000000e+00,
        -9.26100000e+00],
       [ 1.00000000e+00, -2.00000000e+00,  4.00000000e+00,
        -8.00000000e+00],
       [ 1.00000000e+00, -1.90000000e+00,  3.61000000e+00,
        -6.85900000e+00],
       [ 1.00000000e+00, -1.80000000e+00,  3.24000000e+00,
        -5.83200000e+00],
       [ 1.00000000e+00, -1.70000000e+00,  2.89000000e+00,
        -4.91300000e+00],
       [ 1.00000000e+00, -1.60000000e+00,  2.56000000e+00,
        -4.09600000e+00],
       [ 1.00000000e+00, -1.50000000e+00,  2.25000000e+00,
        -3.37500000e+00],
       [ 1.00000000e+00, -1.40000000e+00,  1.96000000e+00,
        -2.74400000e+00],
       [ 1.00000000e+00, -1.30000000e+00,  1.69000000e+00,
        -2.19700000e+00],
       [ 1.00000000e+00, -1.20000000e+00,  1.44000000e+00,
        -1.72800000e+00],
       [ 1.00000000e+00, -1.10000000e+00,  1.21000000e+00,
        -1.33100000e+00],
       [ 1.00000000e+00, -1.00000000e+00,  1.00000000e+00,
        -1.00000000e+00],
       [ 1.00000000e+00, -9.00000000e-01,  8.10000000e-01,
        -7.29000000e-01],
       [ 1.00000000e+00, -8.00000000e-01,  6.40000000e-01,
        -5.12000000e-01],
       [ 1.00000000e+00, -7.00000000e-01,  4.90000000e-01,
        -3.43000000e-01],
       [ 1.00000000e+00, -6.00000000e-01,  3.60000000e-01,
        -2.16000000e-01],
       [ 1.00000000e+00, -5.00000000e-01,  2.50000000e-01,
        -1.25000000e-01],
       [ 1.00000000e+00, -4.00000000e-01,  1.60000000e-01,
        -6.40000000e-02],
       [ 1.00000000e+00, -3.00000000e-01,  9.00000000e-02,
        -2.70000000e-02],
       [ 1.00000000e+00, -2.00000000e-01,  4.00000000e-02,
        -8.00000000e-03],
       [ 1.00000000e+00, -1.00000000e-01,  1.00000000e-02,
        -1.00000000e-03],
       [ 1.00000000e+00,  2.66453526e-15,  7.09974815e-30,
         1.89175293e-44],
       [ 1.00000000e+00,  1.00000000e-01,  1.00000000e-02,
         1.00000000e-03],
       [ 1.00000000e+00,  2.00000000e-01,  4.00000000e-02,
         8.00000000e-03],
       [ 1.00000000e+00,  3.00000000e-01,  9.00000000e-02,
         2.70000000e-02],
       [ 1.00000000e+00,  4.00000000e-01,  1.60000000e-01,
         6.40000000e-02],
       [ 1.00000000e+00,  5.00000000e-01,  2.50000000e-01,
         1.25000000e-01],
       [ 1.00000000e+00,  6.00000000e-01,  3.60000000e-01,
         2.16000000e-01],
       [ 1.00000000e+00,  7.00000000e-01,  4.90000000e-01,
         3.43000000e-01],
       [ 1.00000000e+00,  8.00000000e-01,  6.40000000e-01,
         5.12000000e-01],
       [ 1.00000000e+00,  9.00000000e-01,  8.10000000e-01,
         7.29000000e-01],
       [ 1.00000000e+00,  1.00000000e+00,  1.00000000e+00,
         1.00000000e+00],
       [ 1.00000000e+00,  1.10000000e+00,  1.21000000e+00,
         1.33100000e+00],
       [ 1.00000000e+00,  1.20000000e+00,  1.44000000e+00,
         1.72800000e+00],
       [ 1.00000000e+00,  1.30000000e+00,  1.69000000e+00,
         2.19700000e+00],
       [ 1.00000000e+00,  1.40000000e+00,  1.96000000e+00,
         2.74400000e+00],
       [ 1.00000000e+00,  1.50000000e+00,  2.25000000e+00,
         3.37500000e+00],
       [ 1.00000000e+00,  1.60000000e+00,  2.56000000e+00,
         4.09600000e+00],
       [ 1.00000000e+00,  1.70000000e+00,  2.89000000e+00,
         4.91300000e+00],
       [ 1.00000000e+00,  1.80000000e+00,  3.24000000e+00,
         5.83200000e+00],
       [ 1.00000000e+00,  1.90000000e+00,  3.61000000e+00,
         6.85900000e+00]])
  • To make the result easier to read, put the transformed data into a pandas DataFrame named df_poly.

df_poly = pd.DataFrame(poly.transform(df[["x"]]))
df_poly
0 1 2 3
0 1.0 -3.000000e+00 9.000000e+00 -2.700000e+01
1 1.0 -2.900000e+00 8.410000e+00 -2.438900e+01
2 1.0 -2.800000e+00 7.840000e+00 -2.195200e+01
3 1.0 -2.700000e+00 7.290000e+00 -1.968300e+01
4 1.0 -2.600000e+00 6.760000e+00 -1.757600e+01
5 1.0 -2.500000e+00 6.250000e+00 -1.562500e+01
6 1.0 -2.400000e+00 5.760000e+00 -1.382400e+01
7 1.0 -2.300000e+00 5.290000e+00 -1.216700e+01
8 1.0 -2.200000e+00 4.840000e+00 -1.064800e+01
9 1.0 -2.100000e+00 4.410000e+00 -9.261000e+00
10 1.0 -2.000000e+00 4.000000e+00 -8.000000e+00
11 1.0 -1.900000e+00 3.610000e+00 -6.859000e+00
12 1.0 -1.800000e+00 3.240000e+00 -5.832000e+00
13 1.0 -1.700000e+00 2.890000e+00 -4.913000e+00
14 1.0 -1.600000e+00 2.560000e+00 -4.096000e+00
15 1.0 -1.500000e+00 2.250000e+00 -3.375000e+00
16 1.0 -1.400000e+00 1.960000e+00 -2.744000e+00
17 1.0 -1.300000e+00 1.690000e+00 -2.197000e+00
18 1.0 -1.200000e+00 1.440000e+00 -1.728000e+00
19 1.0 -1.100000e+00 1.210000e+00 -1.331000e+00
20 1.0 -1.000000e+00 1.000000e+00 -1.000000e+00
21 1.0 -9.000000e-01 8.100000e-01 -7.290000e-01
22 1.0 -8.000000e-01 6.400000e-01 -5.120000e-01
23 1.0 -7.000000e-01 4.900000e-01 -3.430000e-01
24 1.0 -6.000000e-01 3.600000e-01 -2.160000e-01
25 1.0 -5.000000e-01 2.500000e-01 -1.250000e-01
26 1.0 -4.000000e-01 1.600000e-01 -6.400000e-02
27 1.0 -3.000000e-01 9.000000e-02 -2.700000e-02
28 1.0 -2.000000e-01 4.000000e-02 -8.000000e-03
29 1.0 -1.000000e-01 1.000000e-02 -1.000000e-03
30 1.0 2.664535e-15 7.099748e-30 1.891753e-44
31 1.0 1.000000e-01 1.000000e-02 1.000000e-03
32 1.0 2.000000e-01 4.000000e-02 8.000000e-03
33 1.0 3.000000e-01 9.000000e-02 2.700000e-02
34 1.0 4.000000e-01 1.600000e-01 6.400000e-02
35 1.0 5.000000e-01 2.500000e-01 1.250000e-01
36 1.0 6.000000e-01 3.600000e-01 2.160000e-01
37 1.0 7.000000e-01 4.900000e-01 3.430000e-01
38 1.0 8.000000e-01 6.400000e-01 5.120000e-01
39 1.0 9.000000e-01 8.100000e-01 7.290000e-01
40 1.0 1.000000e+00 1.000000e+00 1.000000e+00
41 1.0 1.100000e+00 1.210000e+00 1.331000e+00
42 1.0 1.200000e+00 1.440000e+00 1.728000e+00
43 1.0 1.300000e+00 1.690000e+00 2.197000e+00
44 1.0 1.400000e+00 1.960000e+00 2.744000e+00
45 1.0 1.500000e+00 2.250000e+00 3.375000e+00
46 1.0 1.600000e+00 2.560000e+00 4.096000e+00
47 1.0 1.700000e+00 2.890000e+00 4.913000e+00
48 1.0 1.800000e+00 3.240000e+00 5.832000e+00
49 1.0 1.900000e+00 3.610000e+00 6.859000e+00
df
x y_true y
0 -3.000000e+00 19.000 23.824406
1 -2.900000e+00 15.648 10.237108
2 -2.800000e+00 12.584 16.919087
3 -2.700000e+00 9.796 8.955196
4 -2.600000e+00 7.272 6.323695
5 -2.500000e+00 5.000 10.602832
6 -2.400000e+00 2.968 0.784105
7 -2.300000e+00 1.164 -5.234227
8 -2.200000e+00 -0.424 -2.771499
9 -2.100000e+00 -1.808 -7.792136
10 -2.000000e+00 -3.000 -12.199286
11 -1.900000e+00 -4.012 -4.739785
12 -1.800000e+00 -4.856 -2.864605
13 -1.700000e+00 -5.544 -16.354306
14 -1.600000e+00 -6.088 -6.015613
15 -1.500000e+00 -6.500 -5.224009
16 -1.400000e+00 -6.792 -5.926045
17 -1.300000e+00 -6.976 -13.326468
18 -1.200000e+00 -7.064 -8.618807
19 -1.100000e+00 -7.068 -7.999078
20 -1.000000e+00 -7.000 -4.835120
21 -9.000000e-01 -6.872 -13.308757
22 -8.000000e-01 -6.696 -4.778936
23 -7.000000e-01 -6.484 -1.524600
24 -6.000000e-01 -6.248 -17.686227
25 -5.000000e-01 -6.000 -4.880304
26 -4.000000e-01 -5.752 -13.385067
27 -3.000000e-01 -5.516 -6.368335
28 -2.000000e-01 -5.304 -8.704742
29 -1.000000e-01 -5.128 1.240175
30 2.664535e-15 -5.000 -4.714457
31 1.000000e-01 -4.932 -0.955557
32 2.000000e-01 -4.936 -10.169895
33 3.000000e-01 -5.024 -2.721364
34 4.000000e-01 -5.208 1.903864
35 5.000000e-01 -5.500 -9.036285
36 6.000000e-01 -5.912 -2.582631
37 7.000000e-01 -6.456 -4.049151
38 8.000000e-01 -7.144 -7.467370
39 9.000000e-01 -7.988 -14.245467
40 1.000000e+00 -9.000 -7.584490
41 1.100000e+00 -10.192 -11.543440
42 1.200000e+00 -11.576 -8.565901
43 1.300000e+00 -13.164 -9.269588
44 1.400000e+00 -14.968 -7.295300
45 1.500000e+00 -17.000 -21.182783
46 1.600000e+00 -19.272 -14.946791
47 1.700000e+00 -21.796 -18.291899
48 1.800000e+00 -24.584 -24.206884
49 1.900000e+00 -27.648 -24.589037

Notice that this is taking each x value and raising it to the corresponding power. We did this same thing last lecture, but by hand. Appreciate how much time this saved us!

Using Pipeline to combine multiple step#

  • Import the Pipeline class from sklearn.pipeline.

from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In [50], line 1
----> 1 from sklearn.pipeline import pipeline

ImportError: cannot import name 'pipeline' from 'sklearn.pipeline' (/shared-libs/python3.9/py/lib/python3.9/site-packages/sklearn/pipeline.py)
  • Make an instance of this Pipeline class. Pass to the constructor a list of length-2 tuples, where each tuple provides a name for the step (as a string) and the constructor (like PolynomialFeatures(???))

#instantiate
#I think what went wrong in lecture was the indentation
pipe = Pipeline(
    [
        ("poly", PolynomialFeatures(degree=3)), 
        ("reg", LinearRegression())
    ]
)
  Cell In [57], line 3
    ("poly",PolynomialFeatures(degree=3),include_bias=False),
                                                     ^
SyntaxError: invalid syntax
  • Fit this object to the data.

pipe.fit(df[["x"]],df["y"])
Pipeline(steps=[('poly', PolynomialFeatures(degree=3)),
                ('reg', LinearRegression())])
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

First, it fits and transforms using PolynomialFeatures, and then it uses LinearRegression

pipe["reg"].coef_
array([ 0.        ,  3.33524206, -3.03442169, -2.32952623])
pipe["poly"]
PolynomialFeatures(degree=3)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
  • Call the predict method, and add the resulting values to a new column named ā€œpredā€.

df["pred"] = pipe.predict(df[["x"]])
df
x y_true y pred
0 -3.000000e+00 19.000 23.824406 20.317732
1 -2.900000e+00 15.648 10.237108 16.359172
2 -2.800000e+00 12.584 16.919087 12.745261
3 -2.700000e+00 9.796 8.955196 9.462022
4 -2.600000e+00 7.272 6.323695 6.495478
5 -2.500000e+00 5.000 10.602832 3.831652
6 -2.400000e+00 2.968 0.784105 1.456566
7 -2.300000e+00 1.164 -5.234227 -0.643757
8 -2.200000e+00 -0.424 -2.771499 -2.483293
9 -2.100000e+00 -1.808 -7.792136 -4.076020
10 -2.000000e+00 -3.000 -12.199286 -5.435916
11 -1.900000e+00 -4.012 -4.739785 -6.576957
12 -1.800000e+00 -4.856 -2.864605 -7.513120
13 -1.700000e+00 -5.544 -16.354306 -8.258383
14 -1.600000e+00 -6.088 -6.015613 -8.826722
15 -1.500000e+00 -6.500 -5.224009 -9.232116
16 -1.400000e+00 -6.792 -5.926045 -9.488540
17 -1.300000e+00 -6.976 -13.326468 -9.609973
18 -1.200000e+00 -7.064 -8.618807 -9.610391
19 -1.100000e+00 -7.068 -7.999078 -9.503772
20 -1.000000e+00 -7.000 -4.835120 -9.304092
21 -9.000000e-01 -6.872 -13.308757 -9.025330
22 -8.000000e-01 -6.696 -4.778936 -8.681461
23 -7.000000e-01 -6.484 -1.524600 -8.286463
24 -6.000000e-01 -6.248 -17.686227 -7.854314
25 -5.000000e-01 -6.000 -4.880304 -7.398990
26 -4.000000e-01 -5.752 -13.385067 -6.934469
27 -3.000000e-01 -5.516 -6.368335 -6.474728
28 -2.000000e-01 -5.304 -8.704742 -6.033744
29 -1.000000e-01 -5.128 1.240175 -5.625494
30 2.664535e-15 -5.000 -4.714457 -5.263955
31 1.000000e-01 -4.932 -0.955557 -4.963104
32 2.000000e-01 -4.936 -10.169895 -4.736919
33 3.000000e-01 -5.024 -2.721364 -4.599377
34 4.000000e-01 -5.208 1.903864 -4.564455
35 5.000000e-01 -5.500 -9.036285 -4.646130
36 6.000000e-01 -5.912 -2.582631 -4.858379
37 7.000000e-01 -6.456 -4.049151 -5.215179
38 8.000000e-01 -7.144 -7.467370 -5.730508
39 9.000000e-01 -7.988 -14.245467 -6.418343
40 1.000000e+00 -9.000 -7.584490 -7.292661
41 1.100000e+00 -10.192 -11.543440 -8.367438
42 1.200000e+00 -11.576 -8.565901 -9.656653
43 1.300000e+00 -13.164 -9.269588 -11.174282
44 1.400000e+00 -14.968 -7.295300 -12.934302
45 1.500000e+00 -17.000 -21.182783 -14.950692
46 1.600000e+00 -19.272 -14.946791 -17.237426
47 1.700000e+00 -21.796 -18.291899 -19.808484
48 1.800000e+00 -24.584 -24.206884 -22.677842
49 1.900000e+00 -27.648 -24.589037 -25.859478
  • Plot the resulting predictions using a red line. Name the chart c2.

c2 = alt.Chart(df).mark_line(color="red").encode(
    x="x",
    y="pred"
)
  • Plot the true values using a dashed black line, using strokeDash=[10,5] as an argument to mark_line. Name the chart c3.

c3 = alt.Chart(df).mark_line(color="black",strokeDash=[10,5]).encode(
    x="x",
    y="y_true"
)
  • Layer these plots on top of the above scatter plot c1.

c1+c2+c3

Overfitting#

For this portion, we’ll be working with the simulated data in sim_data.csv. The true underlying function is of the form \(f(x) = c_2x^2 + c_1x + c_0\). The true outputs are stored in the ā€œy_trueā€ column. We’ve hidden this true data by adding some random noise to each output and put the result in the ā€œyā€ column.

df = pd.read_csv("sim_data.csv")
df.head()
x y_true y x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
0 -3.329208 -18.207589 -117.484900 -3.329208 11.083626 -36.899694 122.846756 -408.982395 1361.587441 -4533.007730 1.509133e+04 -5.024216e+04 1.672666e+05
1 6.465018 74.160562 73.954907 6.465018 41.796463 270.214901 1746.944309 11294.027098 73016.092970 472050.384357 3.051814e+06 1.973004e+07 1.275550e+08
2 -4.478046 -7.670062 -13.810089 -4.478046 20.052899 -89.797810 402.118751 -1800.706392 8063.646628 -36109.383086 1.616995e+05 -7.240978e+05 3.242544e+06
3 2.043272 -7.925152 19.461182 2.043272 4.174960 8.530580 17.430295 35.614834 72.770792 148.690523 3.038152e+02 6.207771e+02 1.268416e+03
4 4.850593 36.485466 22.375230 4.850593 23.528255 114.125996 553.578791 2685.185564 13024.743051 63177.731115 3.064495e+05 1.486462e+06 7.210222e+06

This is the same type of example that we did in the previous part of lecture with the cubic polynomial. Now, we just have a degree 2 polynomial instead.

Image Source

  • Bias: This is an error caused by overly simplistic assumptions about our data. It fails to capture underlying complexity of our data. In this situation, our model tends to be easy to understand, but somehow fails to capture key aspects/nuances of the data.

  • Variance: These are erros due to our model being too sensitive to noise and random fluctuations in the data. It might learn to model a training set well beause it memorizes the random differences, but struggles with data it has never seen before. Failure to learn underlying patterns of the data.

  • Make a layer chart with the true ā€œyā€ values and the noisy ā€œyā€ values.

c1 = alt.Chart(df).mark_circle(color="red").encode(
    x="x",
    y="y"
)
c2 = alt.Chart(df).mark_circle(color="black").encode(
    x="x",
    y="y_true"
)
c1+c2

Dividing into a training set and a test set#

What is training data? Training data is data that we show to our model for fitting. The reason we use it is to save some data for testing how well our model works; the testing data is something that our model was not fit on – it is brand new!

Key Idea: Fit to a training set, predict or evaluate on a test set.

We partition our data so that some of it is saved for training, and the rest is used for testing.

max_deg = 10
cols = [f"x{i}" for i in range(1, max_deg+1)]
cols
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df[cols],df["y"],train_size=0.24, random_state=6)

This save 24% of the rows of df[cols] for training. The remaining rows will be used to testing.

df[cols]
x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
0 -3.329208 11.083626 -36.899694 122.846756 -408.982395 1361.587441 -4.533008e+03 1.509133e+04 -5.024216e+04 1.672666e+05
1 6.465018 41.796463 270.214901 1746.944309 11294.027098 73016.092970 4.720504e+05 3.051814e+06 1.973004e+07 1.275550e+08
2 -4.478046 20.052899 -89.797810 402.118751 -1800.706392 8063.646628 -3.610938e+04 1.616995e+05 -7.240978e+05 3.242544e+06
3 2.043272 4.174960 8.530580 17.430295 35.614834 72.770792 1.486905e+02 3.038152e+02 6.207771e+02 1.268416e+03
4 4.850593 23.528255 114.125996 553.578791 2685.185564 13024.743051 6.317773e+04 3.064495e+05 1.486462e+06 7.210222e+06
5 -0.578506 0.334669 -0.193608 0.112004 -0.064795 0.037484 -2.168480e-02 1.254479e-02 -7.257238e-03 4.198356e-03
6 -6.557409 42.999609 -281.966007 1848.966339 -12124.427923 79504.828902 -5.213457e+05 3.418677e+06 -2.241766e+07 1.470018e+08
7 -5.656363 31.994443 -180.972185 1023.644381 -5790.104257 32750.931784 -1.852512e+05 1.047848e+06 -5.927008e+06 3.352531e+07
8 0.108538 0.011781 0.001279 0.000139 0.000015 0.000002 1.774525e-07 1.926040e-08 2.090492e-09 2.268986e-10
9 4.556122 20.758251 94.577131 430.904978 1963.255801 8944.833631 4.075376e+04 1.856791e+05 8.459767e+05 3.854373e+06
10 -6.299257 39.680640 -249.958554 1574.553197 -9918.515413 62479.278687 -3.935730e+05 2.479218e+06 -1.561723e+07 9.837695e+07
11 6.449735 41.599085 268.303082 1730.483838 11161.162581 71986.543546 4.642941e+05 2.994574e+06 1.931421e+07 1.245716e+08
12 3.660112 13.396416 49.032378 179.463974 656.858162 2404.174135 8.799545e+03 3.220732e+04 1.178824e+05 4.314626e+05
13 -8.982275 80.681271 -724.701394 6509.467488 -58469.829551 525192.110405 -4.717420e+06 4.237317e+07 -3.806075e+08 3.418721e+09
14 -9.026659 81.480574 -735.497357 6639.083877 -59928.746571 540956.362638 -4.883029e+06 4.407743e+07 -3.978720e+08 3.591455e+09
15 5.481667 30.048674 164.716823 902.922780 4949.522041 27131.631828 1.487266e+05 8.152695e+05 4.469036e+06 2.449777e+07
16 -3.942982 15.547104 -61.301947 241.712453 -953.067768 3757.928725 -1.481744e+04 5.842491e+04 -2.303683e+05 9.083382e+05
17 7.135269 50.912060 363.271234 2592.037885 18494.886953 131965.989144 9.416128e+05 6.718660e+06 4.793945e+07 3.420608e+08
18 4.196026 17.606638 73.877921 309.993714 1300.741838 5457.947214 2.290169e+04 9.609610e+04 4.032218e+05 1.691929e+06
19 -9.924588 98.497442 -977.546500 9701.745999 -96285.829291 955597.159837 -9.483908e+06 9.412388e+07 -9.341407e+08 9.270961e+09
20 -0.690041 0.476157 -0.328568 0.226726 -0.156450 0.107957 -7.449486e-02 5.140454e-02 -3.547126e-02 2.447664e-02
21 4.510288 20.342695 91.751404 413.825225 1866.470799 8418.320181 3.796905e+04 1.712513e+05 7.723927e+05 3.483713e+06
22 -9.336060 87.162025 -813.749934 7597.218586 -70928.092042 662188.955593 -6.182236e+06 5.771773e+07 -5.388562e+08 5.030794e+09
23 4.441058 19.722998 87.590980 388.996638 1727.556699 7672.179799 3.407260e+04 1.513184e+05 6.720137e+05 2.984452e+06
24 -6.563454 43.078928 -282.746563 1855.794057 -12180.418898 79945.618965 -5.247194e+05 3.443972e+06 -2.260435e+07 1.483626e+08
25 0.371593 0.138081 0.051310 0.019066 0.007085 0.002633 9.782985e-04 3.635287e-04 1.350847e-04 5.019650e-05
26 6.520774 42.520497 277.266559 1807.992633 11789.511780 76876.744660 5.012959e+05 3.268837e+06 2.131535e+07 1.389926e+08
27 -2.965964 8.796943 -26.091415 77.386199 -229.524684 680.761955 -2.019115e+03 5.988624e+03 -1.776204e+04 5.268158e+04
28 3.165616 10.021126 31.723040 100.422972 317.900593 1006.351284 3.185722e+03 1.008477e+04 3.192452e+04 1.010608e+05
29 5.222245 27.271843 142.420249 743.753442 3884.062733 20283.527393 1.059256e+05 5.531692e+05 2.888785e+06 1.508594e+07
30 -6.470932 41.872959 -270.957061 1753.344667 -11345.773804 73417.728768 -4.750811e+05 3.074218e+06 -1.989305e+07 1.287266e+08
31 6.893150 47.515521 327.531630 2257.724760 15562.836137 107276.968808 7.394763e+05 5.097321e+06 3.513660e+07 2.422019e+08
32 -3.493023 12.201207 -42.619094 148.869463 -520.004411 1816.387202 -6.344682e+03 2.216212e+04 -7.741278e+04 2.704046e+05
33 -8.747075 76.511319 -669.250243 5853.982010 -51205.219163 447895.887816 -3.917779e+06 3.426911e+07 -2.997544e+08 2.621974e+09
34 -1.384337 1.916390 -2.652930 3.672550 -5.084049 7.038039 -9.743020e+00 1.348763e+01 -1.867143e+01 2.584755e+01
35 4.852230 23.544134 114.241552 554.326269 2689.718466 13051.132219 6.332709e+04 3.072776e+05 1.490982e+06 7.234585e+06
36 3.727977 13.897811 51.810717 193.149152 720.055560 2684.350427 1.000720e+04 3.730660e+04 1.390781e+05 5.184800e+05
37 -2.738399 7.498829 -20.534785 56.232432 -153.986833 421.677380 -1.154721e+03 3.162086e+03 -8.659054e+03 2.371194e+04
38 -1.602675 2.568568 -4.116580 6.597541 -10.573716 16.946233 -2.715931e+01 4.352755e+01 -6.976053e+01 1.118035e+02
39 -8.223553 67.626827 -556.132805 4573.387686 -37609.496782 309283.696327 -2.543411e+06 2.091587e+07 -1.720028e+08 1.414474e+09
40 -0.364001 0.132497 -0.048229 0.017555 -0.006390 0.002326 -8.466826e-04 3.081936e-04 -1.121829e-04 4.083471e-05
41 6.656568 44.309900 294.951869 1963.367222 13069.287756 86996.604895 5.790988e+05 3.854811e+06 2.565981e+07 1.708063e+08
42 -9.804880 96.135668 -942.598671 9242.066675 -90617.352934 888492.254125 -8.711560e+06 8.541580e+07 -8.374916e+08 8.211505e+09
43 1.236174 1.528127 1.889031 2.335171 2.886679 3.568438 4.411211e+00 5.453025e+00 6.740889e+00 8.332913e+00
44 -2.766259 7.652191 -21.167945 58.556028 -161.981161 448.081909 -1.239511e+03 3.428808e+03 -9.484973e+03 2.623790e+04
45 -4.457650 19.870645 -88.576385 394.842539 -1760.069919 7845.776000 -3.497372e+04 1.559006e+05 -6.949505e+05 3.097846e+06
46 4.825670 23.287096 112.375850 542.288824 2616.907175 12628.331726 6.094017e+04 2.940772e+05 1.419120e+06 6.848203e+06
47 -3.012487 9.075077 -27.338548 82.357015 -248.099419 747.396219 -2.251521e+03 6.782678e+03 -2.043273e+04 6.155332e+04
48 3.778329 14.275771 53.938563 203.797646 770.014590 2909.368585 1.099255e+04 4.153348e+04 1.569272e+05 5.929225e+05
49 6.068927 36.831870 223.529915 1356.586642 8233.024737 49965.622715 3.032377e+05 1.840327e+06 1.116881e+07 6.778270e+07
len(df[cols])
50
len(X_train)
12
X_train
x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
13 -8.982275 80.681271 -724.701394 6509.467488 -58469.829551 525192.110405 -4.717420e+06 4.237317e+07 -3.806075e+08 3.418721e+09
11 6.449735 41.599085 268.303082 1730.483838 11161.162581 71986.543546 4.642941e+05 2.994574e+06 1.931421e+07 1.245716e+08
1 6.465018 41.796463 270.214901 1746.944309 11294.027098 73016.092970 4.720504e+05 3.051814e+06 1.973004e+07 1.275550e+08
25 0.371593 0.138081 0.051310 0.019066 0.007085 0.002633 9.782985e-04 3.635287e-04 1.350847e-04 5.019650e-05
16 -3.942982 15.547104 -61.301947 241.712453 -953.067768 3757.928725 -1.481744e+04 5.842491e+04 -2.303683e+05 9.083382e+05
45 -4.457650 19.870645 -88.576385 394.842539 -1760.069919 7845.776000 -3.497372e+04 1.559006e+05 -6.949505e+05 3.097846e+06
15 5.481667 30.048674 164.716823 902.922780 4949.522041 27131.631828 1.487266e+05 8.152695e+05 4.469036e+06 2.449777e+07
42 -9.804880 96.135668 -942.598671 9242.066675 -90617.352934 888492.254125 -8.711560e+06 8.541580e+07 -8.374916e+08 8.211505e+09
20 -0.690041 0.476157 -0.328568 0.226726 -0.156450 0.107957 -7.449486e-02 5.140454e-02 -3.547126e-02 2.447664e-02
35 4.852230 23.544134 114.241552 554.326269 2689.718466 13051.132219 6.332709e+04 3.072776e+05 1.490982e+06 7.234585e+06
9 4.556122 20.758251 94.577131 430.904978 1963.255801 8944.833631 4.075376e+04 1.856791e+05 8.459767e+05 3.854373e+06
10 -6.299257 39.680640 -249.958554 1574.553197 -9918.515413 62479.278687 -3.935730e+05 2.479218e+06 -1.561723e+07 9.837695e+07
y_train
13      2.574974
11    130.940520
1      73.954907
25      1.134863
16    -35.901888
45    -26.760377
15     24.441828
42    131.476240
20     61.591699
35    -13.988943
9       1.089803
10     -7.251101
Name: y, dtype: float64
X_test
x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
49 6.068927 36.831870 223.529915 1356.586642 8233.024737 49965.622715 3.032377e+05 1.840327e+06 1.116881e+07 6.778270e+07
40 -0.364001 0.132497 -0.048229 0.017555 -0.006390 0.002326 -8.466826e-04 3.081936e-04 -1.121829e-04 4.083471e-05
38 -1.602675 2.568568 -4.116580 6.597541 -10.573716 16.946233 -2.715931e+01 4.352755e+01 -6.976053e+01 1.118035e+02
23 4.441058 19.722998 87.590980 388.996638 1727.556699 7672.179799 3.407260e+04 1.513184e+05 6.720137e+05 2.984452e+06
7 -5.656363 31.994443 -180.972185 1023.644381 -5790.104257 32750.931784 -1.852512e+05 1.047848e+06 -5.927008e+06 3.352531e+07
0 -3.329208 11.083626 -36.899694 122.846756 -408.982395 1361.587441 -4.533008e+03 1.509133e+04 -5.024216e+04 1.672666e+05
6 -6.557409 42.999609 -281.966007 1848.966339 -12124.427923 79504.828902 -5.213457e+05 3.418677e+06 -2.241766e+07 1.470018e+08
34 -1.384337 1.916390 -2.652930 3.672550 -5.084049 7.038039 -9.743020e+00 1.348763e+01 -1.867143e+01 2.584755e+01
14 -9.026659 81.480574 -735.497357 6639.083877 -59928.746571 540956.362638 -4.883029e+06 4.407743e+07 -3.978720e+08 3.591455e+09
31 6.893150 47.515521 327.531630 2257.724760 15562.836137 107276.968808 7.394763e+05 5.097321e+06 3.513660e+07 2.422019e+08
48 3.778329 14.275771 53.938563 203.797646 770.014590 2909.368585 1.099255e+04 4.153348e+04 1.569272e+05 5.929225e+05
24 -6.563454 43.078928 -282.746563 1855.794057 -12180.418898 79945.618965 -5.247194e+05 3.443972e+06 -2.260435e+07 1.483626e+08
19 -9.924588 98.497442 -977.546500 9701.745999 -96285.829291 955597.159837 -9.483908e+06 9.412388e+07 -9.341407e+08 9.270961e+09
3 2.043272 4.174960 8.530580 17.430295 35.614834 72.770792 1.486905e+02 3.038152e+02 6.207771e+02 1.268416e+03
41 6.656568 44.309900 294.951869 1963.367222 13069.287756 86996.604895 5.790988e+05 3.854811e+06 2.565981e+07 1.708063e+08
28 3.165616 10.021126 31.723040 100.422972 317.900593 1006.351284 3.185722e+03 1.008477e+04 3.192452e+04 1.010608e+05
43 1.236174 1.528127 1.889031 2.335171 2.886679 3.568438 4.411211e+00 5.453025e+00 6.740889e+00 8.332913e+00
30 -6.470932 41.872959 -270.957061 1753.344667 -11345.773804 73417.728768 -4.750811e+05 3.074218e+06 -1.989305e+07 1.287266e+08
47 -3.012487 9.075077 -27.338548 82.357015 -248.099419 747.396219 -2.251521e+03 6.782678e+03 -2.043273e+04 6.155332e+04
17 7.135269 50.912060 363.271234 2592.037885 18494.886953 131965.989144 9.416128e+05 6.718660e+06 4.793945e+07 3.420608e+08
21 4.510288 20.342695 91.751404 413.825225 1866.470799 8418.320181 3.796905e+04 1.712513e+05 7.723927e+05 3.483713e+06
29 5.222245 27.271843 142.420249 743.753442 3884.062733 20283.527393 1.059256e+05 5.531692e+05 2.888785e+06 1.508594e+07
39 -8.223553 67.626827 -556.132805 4573.387686 -37609.496782 309283.696327 -2.543411e+06 2.091587e+07 -1.720028e+08 1.414474e+09
18 4.196026 17.606638 73.877921 309.993714 1300.741838 5457.947214 2.290169e+04 9.609610e+04 4.032218e+05 1.691929e+06
22 -9.336060 87.162025 -813.749934 7597.218586 -70928.092042 662188.955593 -6.182236e+06 5.771773e+07 -5.388562e+08 5.030794e+09
44 -2.766259 7.652191 -21.167945 58.556028 -161.981161 448.081909 -1.239511e+03 3.428808e+03 -9.484973e+03 2.623790e+04
37 -2.738399 7.498829 -20.534785 56.232432 -153.986833 421.677380 -1.154721e+03 3.162086e+03 -8.659054e+03 2.371194e+04
5 -0.578506 0.334669 -0.193608 0.112004 -0.064795 0.037484 -2.168480e-02 1.254479e-02 -7.257238e-03 4.198356e-03
32 -3.493023 12.201207 -42.619094 148.869463 -520.004411 1816.387202 -6.344682e+03 2.216212e+04 -7.741278e+04 2.704046e+05
27 -2.965964 8.796943 -26.091415 77.386199 -229.524684 680.761955 -2.019115e+03 5.988624e+03 -1.776204e+04 5.268158e+04
46 4.825670 23.287096 112.375850 542.288824 2616.907175 12628.331726 6.094017e+04 2.940772e+05 1.419120e+06 6.848203e+06
12 3.660112 13.396416 49.032378 179.463974 656.858162 2404.174135 8.799545e+03 3.220732e+04 1.178824e+05 4.314626e+05
2 -4.478046 20.052899 -89.797810 402.118751 -1800.706392 8063.646628 -3.610938e+04 1.616995e+05 -7.240978e+05 3.242544e+06
8 0.108538 0.011781 0.001279 0.000139 0.000015 0.000002 1.774525e-07 1.926040e-08 2.090492e-09 2.268986e-10
36 3.727977 13.897811 51.810717 193.149152 720.055560 2684.350427 1.000720e+04 3.730660e+04 1.390781e+05 5.184800e+05
4 4.850593 23.528255 114.125996 553.578791 2685.185564 13024.743051 6.317773e+04 3.064495e+05 1.486462e+06 7.210222e+06
33 -8.747075 76.511319 -669.250243 5853.982010 -51205.219163 447895.887816 -3.917779e+06 3.426911e+07 -2.997544e+08 2.621974e+09
26 6.520774 42.520497 277.266559 1807.992633 11789.511780 76876.744660 5.012959e+05 3.268837e+06 2.131535e+07 1.389926e+08
50*0.24
12.0

Performing Polynomial Regression for Each Degree#

#not doing anything yet, just showing how degree changes
for i in range(1,max_deg+1):
    sub_cols = cols[:i]
    reg = LinearRegression()
    print(sub_cols)
['x1']
['x1', 'x2']
['x1', 'x2', 'x3']
['x1', 'x2', 'x3', 'x4']
['x1', 'x2', 'x3', 'x4', 'x5']
['x1', 'x2', 'x3', 'x4', 'x5', 'x6']
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8']
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9']
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10']

Evaluating the Performance, Part 1#

mse_training_dict = {}
for i in range(1,max_deg+1):
    sub_cols = cols[:i]
    reg = LinearRegression()
    reg.fit(X_train[sub_cols],y_train)
    mse_training_dict[i] = mean_squared_error(reg.predict(X_train[sub_cols]),y_train)
mse_training_dict
{1: 3006.2441403930584,
 2: 1845.1659476797647,
 3: 1820.05419658703,
 4: 590.386208100543,
 5: 589.0984843939517,
 6: 523.8762601493493,
 7: 373.27949678005854,
 8: 206.85098887525973,
 9: 204.9933133278071,
 10: 101.4717525424262}

Looking at the MSE for each degree, we’d think that degree 10 is the best fit. There is a big issue, however! That is, we are predicting on the training set. This means there’s a huge risk of overfitting.

Evaluating the Performance, Part 2#

To get a meaningful MSE, we should always evaluate on a test set (not use during training).

mse_test_dict = {}
for i in range(1,max_deg+1):
    sub_cols = cols[:i]
    reg = LinearRegression()
    reg.fit(X_train[sub_cols],y_train)
    df[f"Pred{i}"] = reg.predict(df[sub_cols])
    mse_test_dict[i] = mean_squared_error(reg.predict(X_test[sub_cols]),y_test)
mse_test_dict
{1: 4960.848889431734,
 2: 3724.5263419375206,
 3: 3742.5488620098768,
 4: 6252.874102524008,
 5: 6253.4123849934285,
 6: 7016.575636379848,
 7: 5609.641936194314,
 8: 9481.527367001438,
 9: 12142.080032238073,
 10: 103395.23803044269}

Notice now that degree 2 is where we have the smallest MSE (unlike the previous example, where we got 10). This is encouraging, because we know that the true underlying data has degree 2. There is some randomness here, though, if you play around with the random states, we sometimes get degree 3 or 4 as the minimum for MSE.

Plotting the polynomial fits#

Before plotting, we add a column which tells us whether a point was in the training set, or the testing set.

df["In_train"] = "test"
X_train.index
Int64Index([13, 11, 1, 25, 16, 45, 15, 42, 20, 35, 9, 10], dtype='int64')
df.loc[X_train.index,"In_train"] = "train"
13    False
11    False
1     False
25    False
16    False
45    False
15    False
42    False
20    False
35    False
9     False
10    False
Name: In_train, dtype: bool
c = alt.Chart(df).mark_circle().encode(
    x="x", 
    y="y",
    color="In_train"
)
c_true = alt.Chart(df).mark_line(color="black").encode(
    x="x",
    y="y_true",
)
chart_list = []
for i in range(1,max_deg+1):
    c_temp = alt.Chart(df).mark_line(color="red", clip=True).encode(
        x="x",
        y=alt.Y(f"Pred{i}").scale(domain=(-100,300)),
    )
    chart_list.append(c_temp)
all_charts = [c+c_true+d for d in chart_list]
alt.vconcat(*all_charts)

We didn’t get to see these plots during lecture today, but here are some explanations. We’ll go through this all together next lecture. A few comments:

  • Notice that in degree 1, the training and test errors are both high. This is a sign of overfitting, and is exhibited by the line not fitting our data well.

  • In degree 2 and 3, the red curve matches the secret underlying polynomial (black curve) pretty well.

  • In higher degrees, the training errors are smaller, but notice from the plots that the red lines follow the orange point (the training data) very closely.

Created in deepnote.com Created in Deepnote