Lecture 11: August 30th, 2023#

Reminders:

  • Homework 5 and Homework 6 are due Friday at midnight. There are only two homework assignments remaining. They will be released Friday, and are due a week from then.

  • Deadline for EDA outcome quizzes is tonight. ML outcomes will start to be released tonight.

  • Monday is a holiday. No class or discussion :( Maybe I will release some extra videos to help with the missed day..but we will see.

Today:

  • Main focus for today will be getting us all on board for the final project. I’ll also give us some time in lecture to get started thinking about the project and filling out the planning worksheet.

  • With the remaining class time, we’ll finish the notes from Monday about polynomial regression.

Final Project Information#

In this part of the lecture, we went through the information about the final project. Here are some questions from the chat:

  • Tokens cannot be used to extend the deadline of the final project. The Wednesday, September 13 deadline is a hard deadline.

  • Nothing happens with extra tokens, so be sure to use them, if you would like.

  • Something I forgot to put in the project instructions: it can be really fun to use a personal dataset. These can be things like your Spotify listening history, workout information from a smart watch, etc.

  • You can get data from anywhere you’d like! Just be sure to tell me where you found it.

  • Workflow for the project: Pick a dataset > ask an (open-ended) question about the data that you want to know the answer to > Use Math 10 techniques to help answer the question (it’s totally fine if you are unable to answer the question in the end.)

    • The question you ask should have some complexity; it shouldn’t be something that you can easily answer by just glancing at the data for a minute or so.

  • Should claims be statistically significant? Or can we make inferences based on general trends we see in the data/plot? Great question! You can make inferences, but something you could use for your extra portion is to determine whether your claims are statistically significant.

Polynomial Regression#

We’ve already seen examples of performing linear regression with multiple input features. If we can do this, then performing polynomial regression is also possible.

Key Point: Polynomial regression is no more difficult than linear regression.

Think back to the taxis dataset where we performed linear regression on multiple input columns: $\( \text{duration} = c_1*\text{passengers} + c_2*\text{hour} + c_3*\text{distance} + c_0 \)$

Imagine now we want to fit to a degree three polynomial:

\[ y \approx c_0 + c_1x^1 + c_2x^2 + c_3x^3 \]

Imagine now that the difference powers of \(x\) are all just different columns in the data that we’re fitting to.

  • Load the mpg dataset from Seaborn and drop missing values. Name the result df.

import seaborn as sns
df = sns.load_dataset("mpg").dropna().copy()
df.head()
mpg cylinders displacement horsepower weight acceleration model_year origin name
0 18.0 8 307.0 130.0 3504 12.0 70 usa chevrolet chevelle malibu
1 15.0 8 350.0 165.0 3693 11.5 70 usa buick skylark 320
2 18.0 8 318.0 150.0 3436 11.0 70 usa plymouth satellite
3 16.0 8 304.0 150.0 3433 12.0 70 usa amc rebel sst
4 17.0 8 302.0 140.0 3449 10.5 70 usa ford torino

Goal: Find a degree 3 polynomial to model “mpg” as a function of “horsepower”.

Warning 1: The coefficients will not be as nicely/easily interpretable as in linear regression. Warning 2: We will later learn to automate some of the following steps using the scikit-learn class PolynomialFeatures.
  • Create a range object that stores the degrees that we want.

We store the degrees this way so that if we want to try a higher degree polynomial it’s easy to change.

#degree we want
degs = range(1,4)
for x in degs:
    print(x)
1
2
3
  • Add a new column to df for each desired power of horsepower. Call the corresponding columns hd, where d is the degree that we raise horsepower to.

for d in degs:
    df[f"h{d}"] = df["horsepower"]**d
df.head()
mpg cylinders displacement horsepower weight acceleration model_year origin name h1 h2 h3
0 18.0 8 307.0 130.0 3504 12.0 70 usa chevrolet chevelle malibu 130.0 16900.0 2197000.0
1 15.0 8 350.0 165.0 3693 11.5 70 usa buick skylark 320 165.0 27225.0 4492125.0
2 18.0 8 318.0 150.0 3436 11.0 70 usa plymouth satellite 150.0 22500.0 3375000.0
3 16.0 8 304.0 150.0 3433 12.0 70 usa amc rebel sst 150.0 22500.0 3375000.0
4 17.0 8 302.0 140.0 3449 10.5 70 usa ford torino 140.0 19600.0 2744000.0

Sanity check: h1 should be the same as horsepower.

df[["horsepower","h1"]]
horsepower h1
0 130.0 130.0
1 165.0 165.0
2 150.0 150.0
3 150.0 150.0
4 140.0 140.0
... ... ...
393 86.0 86.0
394 52.0 52.0
395 84.0 84.0
396 79.0 79.0
397 82.0 82.0

392 rows Ă— 2 columns

  • Instantiate a new LinearRegression object and fit it to the columns that we just made for input, and mpg for target.

from sklearn.linear_model import LinearRegression
reg = LinearRegression()

This is worth pointing out! At this step, what will be the result of the following code?

reg.coef_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In [13], line 1
----> 1 reg.coef_

AttributeError: 'LinearRegression' object has no attribute 'coef_'

Notice! We haven’t fitted any data yet! reg has no idea what data we’re working with, so coef_ doesn’t exist yet.

pred_col = [f"h{d}" for d in degs]
pred_col
['h1', 'h2', 'h3']
reg.fit(df[pred_col],df["mpg"])
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.

Now, let’s take a look at the coefficients:

reg.coef_
array([-5.68850128e-01,  2.07901126e-03, -2.14662591e-06])

These coefficients might seem really small…however, recall that h2 and h3 are powers of h1, and these end up being pretty big numbers. So, multiplying h3 by \(-2 \times 10^{-6}\) still has some sway on the result/has a meaningful impact from these columns

df[pred_col]
h1 h2 h3
0 130.0 16900.0 2197000.0
1 165.0 27225.0 4492125.0
2 150.0 22500.0 3375000.0
3 150.0 22500.0 3375000.0
4 140.0 19600.0 2744000.0
... ... ... ...
393 86.0 7396.0 636056.0
394 52.0 2704.0 140608.0
395 84.0 7056.0 592704.0
396 79.0 6241.0 493039.0
397 82.0 6724.0 551368.0

392 rows Ă— 3 columns

  • Create a new column in df which stores the predictions.

df["pred"] = reg.predict(df[pred_col])
df[["mpg","pred"]]
mpg pred
0 18.0 17.153421
1 15.0 13.782683
2 18.0 14.890157
3 16.0 14.890157
4 17.0 15.904046
... ... ...
393 27.0 25.774667
394 44.0 36.424392
395 32.0 26.298564
396 28.0 27.662364
397 31.0 26.834765

392 rows Ă— 2 columns

  • Create plots with the true data and the fit data. View them together.

import altair as alt
c1 = alt.Chart(df).mark_circle().encode(
    x="horsepower",
    y="mpg"
)
c2 = alt.Chart(df).mark_circle(color="red").encode(
    x="horsepower",
    y="pred"
)
c1+c2

Warnings about polynomial regression#

We might be pretty impressed by the fit above! It looks like the degree three polynomial fits the data well, but this is in part due to a problem called overfitting. In general, the better a fit appears to be, the worse it will perform on future data. Part of the issue with large degree polynomials is that we have a lot of flexibility/choice in the coefficients.

We have a few minutes left in class, let’s try to see this type of problem in action! After lecture note: I think this was too ambitious of an example for just a few minutes. Lecture 12 has a much more in-depth and careful example.

Here is a relevant quote that you can meditate on:

“We are drowning in information but starved for knowledge.” John Naisbitt, Megatrends, 1982

Created in deepnote.com Created in Deepnote