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.
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.
RidgeandLassoshrink coefficients toward zero to control overfitting. Standardize features first so the penalty treats them equally. - New categories in production.
get_dummiesonly knows the categories it saw. In the last section you’ll use scikit-learn’sOneHotEncoderinside 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.
Add channel and objective
DoneThe 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 tabler2_simple: test R² of aLinearRegressionthat uses only theclickscolumn (same split),
rounded to 3 decimals
r2_multi: test R² of aLinearRegressionthat uses every column ofX, rounded to 3 decimals
Need a hint?
- Split once, then fit one model on
X_train[["clicks"]]and another on all ofX_train. model.score(X_test, y_test)returns R² for regression models.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)Let the slope depend on the objective
DoneDifferent objectives convert clicks at different rates, so give each objective its own slope. Add two interaction columns to X:
clicks_x_traffic=clicks * objective_trafficclicks_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 decimalscvr_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?
- Multiplying two columns works element by element:
X["clicks"] * X["objective_traffic"]is the clicks for traffic campaigns and 0 elsewhere. pd.Series(model.coef_, index=X.columns)lets you look coefficients up by name.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
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)daily_stats.csv (1,561 rows)campaigns.csv (40 rows)