Section 2 · Lesson 1

Linear regression: fitting a line

Fit a least-squares line with scikit-learn, read its slope and intercept, and use residuals to see what it misses.

35 min 2 practice tasks
The Main Ideas of Fitting a Line to Data (The Main Ideas of Least Squares and Linear Regression.) by StatQuest with Josh Starmer on YouTube

Regression predicts a number. The simplest regression model, and still one of the most useful, is a straight line.

The model

With one feature, linear regression predicts

predicted = intercept + slope * x

For our ad data, x is a campaign-day’s clicks and the prediction is its conversions. The slope is how many extra conversions each extra click brings, on average. The intercept is the prediction when x is 0.

Least squares

Many lines could be drawn through a cloud of points. Linear regression chooses the one that minimizes the sum of squared residuals, where a residual is the vertical miss for one point:

residual = actual - predicted

Squaring makes misses above and below the line count equally, and makes big misses count much more than small ones. There’s a closed-form solution, so fitting is instant even on large data.

In scikit-learn

from sklearn.linear_model import LinearRegression

X = ds[["clicks"]]          # 2-D: a DataFrame with one column
y = ds["conversions"]       # 1-D
model = LinearRegression().fit(X, y)
model.coef_, model.intercept_
model.predict(pd.DataFrame({"clicks": [1000]}))

The double brackets matter: scikit-learn always expects X to be a table, even with one feature. coef_ holds one slope per feature.

Reading the result

On daily_stats, the fitted slope is about 0.028: roughly 2.8 conversions per 100 clicks. The intercept is about 6.5, so a day with 1,000 clicks is predicted to bring about 34 conversions.

Don’t read too much into the intercept. No campaign-day has zero clicks and six conversions; the intercept just positions the line. Predictions far outside the range of the training data (extrapolation) are risky in general, because the straight-line pattern may not continue.

If you took the statistics course, you’ve met this relationship before: clicks and conversions have a correlation of about 0.68. For a one-feature regression, R² (next lesson) equals the squared correlation, so the line explains roughly 0.68² ≈ 47% of the variation in conversions.

Residuals tell you what’s missing

Residuals are where the model’s blind spots show up. Look for patterns:

  • Groups with consistent misses. Average the residuals by campaign and some campaigns are under-predicted day after day while others are over-predicted. The line uses one conversion rate for everyone, but a conversions-objective campaign converts about 5.6% of its clicks while an awareness campaign converts under 1%. A feature the model doesn’t have is driving the errors, and you’ll add it in the multiple regression lesson.
  • Errors that grow with the prediction. Big campaigns have bigger misses in absolute terms. That’s common with counts and money, and it’s one reason to also look at errors in relative terms.
  • Curves. If residuals are positive at both ends and negative in the middle, the relationship isn’t straight. Adding a transformed feature (such as a log or a square) can fix it.

A residual plot is often more informative than any single score. Least squares guarantees the residuals average to zero overall, so a zero mean tells you nothing. The useful information is in where the errors are.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Clicks to conversions

Using every row of daily_stats.csv, fit a LinearRegression that predicts conversions from clicks.

  • model: the fitted model
  • slope, intercept: from model.coef_[0] and model.intercept_, rounded to 4 decimals
  • pred_1000: the predicted conversions for a campaign-day with 1,000 clicks, rounded to 2

decimals. Predict from a DataFrame with a clicks column: pd.DataFrame({"clicks": [1000]})

Need a hint?
  1. LinearRegression().fit(X, y) returns the fitted model, so you can create and fit in one line.
  2. model.predict(...) returns an array; take its first element with [0].
Python 3
import pandas as pd
from sklearn.linear_model import LinearRegression

ds = pd.read_csv("daily_stats.csv")
X = ds[["clicks"]]      # double brackets: X must be 2-D
y = ds["conversions"]

model = None
slope = None
intercept = None
pred_1000 = None
print(slope, intercept, pred_1000)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Who does the line miss?

Add two columns to ds:

  • predicted: the model's prediction for each row
  • residual: conversions - predicted

Then create:

  • mean_residual: the mean residual, rounded to 4 decimals (least squares makes this essentially 0)
  • most_under: the campaign_id with the largest average residual (the line

under-predicts it most)

  • most_over: the campaign_id with the most negative average residual

Afterwards, look both campaigns up in campaigns.csv. What objective does each have?

Need a hint?
  1. ds.groupby("campaign_id")["residual"].mean() gives one average residual per campaign.
  2. .idxmax() and .idxmin() return the index label (here the campaign_id) of the largest and smallest values.
Python 3
import pandas as pd
from sklearn.linear_model import LinearRegression

ds = pd.read_csv("daily_stats.csv")
model = LinearRegression().fit(ds[["clicks"]], ds["conversions"])

# TODO: add ds["predicted"] and ds["residual"]

mean_residual = None
most_under = None
most_over = None
print(mean_residual, most_under, most_over)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status