Section 2 · Lesson 3

Multiple regression with categorical features

Add more features, one-hot encode categories and use interaction terms to cut prediction error dramatically.

45 min 2 practice tasks
Multiple Regression, Clearly Explained!!! by StatQuest with Josh Starmer on YouTube

The line from the last two lessons uses clicks alone and explains about half the variation in conversions. The residuals pointed at the missing ingredient: campaigns with different objectives convert clicks at very different rates. Multiple regression lets the model use many features at once.

More than one feature

predicted = b0 + b1*x1 + b2*x2 + ... + bk*xk

Each coefficient is the expected change in the prediction for a one-unit increase in that feature holding the other features fixed. That last phrase matters: when features are correlated with each other, a coefficient can look very different from the simple one-feature slope.

Categorical features need encoding

LinearRegression only understands numbers, and channel holds text like "search". Don’t replace categories with 1, 2, 3, 4: that would claim video is “four times” display. Use one-hot encoding instead, with one 0/1 column per category:

X = pd.get_dummies(df[["clicks", "channel", "objective"]],
                   columns=["channel", "objective"], drop_first=True, dtype=int)
# clicks, channel_search, channel_social, channel_video, objective_conversions, objective_traffic

drop_first=True drops one category from each column (display and awareness, alphabetically first). Those become the reference level that the intercept describes, and every dummy coefficient is a difference from it. Keeping all the dummies would make them add up to exactly 1, duplicating the intercept.

Reading the coefficients

With channel and objective added, test R² jumps from 0.50 to 0.74. The objective_conversions coefficient is about +33: at the same number of clicks, a conversions campaign-day is predicted to have 33 more conversions than an awareness one.

But a fixed shift doesn’t match how this business works. A conversions campaign doesn’t get 33 bonus conversions on a slow day; it converts a larger share of every click. The model should let the slope depend on the objective.

Interaction terms

An interaction is the product of two features:

X["clicks_x_traffic"] = X["clicks"] * X["objective_traffic"]
X["clicks_x_conversions"] = X["clicks"] * X["objective_conversions"]

Now the slope on clicks is b_clicks for awareness campaigns, b_clicks + b_clicks_x_traffic for traffic campaigns and b_clicks + b_clicks_x_conversions for conversions campaigns. The fitted slopes come out at about 0.8%, 1.8% and 4.9% of clicks, close to each objective’s real conversion rate.

Features Test R² Test MAE
clicks 0.50 15.0
+ channel and objective dummies 0.74 12.1
+ clicks × objective interactions 0.85 7.4

Two well-chosen interaction columns halved the typical error. Domain knowledge (“conversion rate depends on objective”) beat throwing more raw columns at the model. You’ll see this again in the feature engineering lesson.

Cautions

  • More features, more overfitting risk. Every column gives the model another way to fit noise. Always compare on held-out data, and watch the gap between training and test scores.
  • Correlated features make coefficients unstable. Clicks, impressions and spend move together. Predictions can still be fine, but individual coefficients become hard to interpret.
  • Regularization helps. Ridge and Lasso shrink coefficients toward zero to control overfitting. Standardize features first so the penalty treats them equally.
  • New categories in production. get_dummies only knows the categories it saw. In the last section you’ll use scikit-learn’s OneHotEncoder inside a pipeline, which handles this safely.

Practice

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

1

Add channel and objective

The starter joins each campaign-day to its campaign's channel and objective. Build the features with one-hot encoding:

X = pd.get_dummies(df[["clicks", "channel", "objective"]],
                   columns=["channel", "objective"], drop_first=True, dtype=int)

Split X and y = df["conversions"] with test_size=0.25, random_state=42.

  • X: the one-hot feature table
  • r2_simple: test R² of a LinearRegression that uses only the clicks column (same split),

rounded to 3 decimals

  • r2_multi: test R² of a LinearRegression that uses every column of X, rounded to 3 decimals
Need a hint?
  1. Split once, then fit one model on X_train[["clicks"]] and another on all of X_train.
  2. model.score(X_test, y_test) returns R² for regression models.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

ds = pd.read_csv("daily_stats.csv")
campaigns = pd.read_csv("campaigns.csv")
df = ds.merge(campaigns[["id", "channel", "objective"]], left_on="campaign_id", right_on="id")
y = df["conversions"]

X = None
r2_simple = None
r2_multi = None
print(r2_simple, r2_multi)
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

Let the slope depend on the objective

Different objectives convert clicks at different rates, so give each objective its own slope. Add two interaction columns to X:

  • clicks_x_traffic = clicks * objective_traffic
  • clicks_x_conversions = clicks * objective_conversions

Refit on the same split (test_size=0.25, random_state=42) and create:

  • r2_interact, mae_interact: test R² and test MAE, rounded to 3 decimals
  • cvr_conversions: the model's conversions per click for conversions-objective

campaigns: the clicks coefficient plus the clicks_x_conversions coefficient, rounded to 4 decimals

Need a hint?
  1. Multiplying two columns works element by element: X["clicks"] * X["objective_traffic"] is the clicks for traffic campaigns and 0 elsewhere.
  2. pd.Series(model.coef_, index=X.columns) lets you look coefficients up by name.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

ds = pd.read_csv("daily_stats.csv")
campaigns = pd.read_csv("campaigns.csv")
df = ds.merge(campaigns[["id", "channel", "objective"]], left_on="campaign_id", right_on="id")
y = df["conversions"]
X = pd.get_dummies(df[["clicks", "channel", "objective"]],
                   columns=["channel", "objective"], drop_first=True, dtype=int)

# TODO: add the two interaction columns, split, fit

r2_interact = None
mae_interact = None
cvr_conversions = None
print(r2_interact, mae_interact, cvr_conversions)
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