…
…
Statistics and Data Analysis Fundamentals · Lesson 39 / 44 · Regression
PreviewIn this lesson you will
C() and read its coefficient against the reference categoryYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In simple regression, every $100 of advertising was associated with about 163 more visitors on average, but the residual plot showed that the weekend effect was left out. The logistics team asks whether the low satisfaction of Caravan Freight customers comes from the carrier itself or only from slow delivery. In this lesson you will put several explanatory variables in one model and answer both questions.
This is an Advanced lesson. If you understood the one-variable regression in lesson 38, you can follow it easily. If the first read feels hard, you can jump ahead to Unit 8 and come back later.
By the end of the lesson you will produce the two comparisons below yourself and explain each in one sentence. The left columns are one-variable models. The right columns are models with a second explanatory variable added.
| Question | Simple model | Coefficient | Multiple model | Coefficient |
|---|---|---|---|---|
| Advertising and visitors | visitors ~ ad_spend | ad spend 1.627 (R² 0.635) | + weekend | ad spend 1.448, weekend 238 (R² 0.897) |
| Carrier and satisfaction | satisfaction ~ C(carrier) | Caravan −0.53 (p < 0.001) | + delivery_days | Caravan +0.19 (p = 0.12), delivery days −0.45 |
Two sentences:
1. "When we compare the same kind of days, every $100 of daily ad spend is associated with about 145 more visitors on average; the model that ignores weekends found 163."
2. "For packages delivered in the same time, there is no clear satisfaction gap between carriers; Caravan's low score comes together with its slow delivery."
We will build every number in the table step by step.
In lesson 38 you built the visitors ~ ad_spend model and looked at the residuals. A residual is the difference between the observed visitors and the model's estimate. On weekend days the mean residual was +165, and on weekdays it was −66: the model systematically underestimated weekends and overestimated weekdays. When the residuals show a pattern like this, there is something the model does not know. Here we can name it: whether the day is a weekend.
You give the model this information by adding a second explanatory variable to the formula. The equation of one-variable regression was ŷ = a + b × x. In multiple regression, several explanatory variables stand in the same equation:
ŷ = a + b₁ × x₁ + b₂ × x₂
In a statsmodels formula, explanatory variables are added with +: "visitors ~ ad_spend + weekend". Here + does not mean "add the two columns". It means "use both of these variables as explanatory variables". The weekend column has the value 0 (weekday) or 1 (weekend). The coefficient of a 0/1 variable like this answers the question: "At the same ad spend, how many more visitors do weekend days get on average?"
In lesson 37 you saw one more thing: on weekend days, ad spend is also high. Weekend moves together with both advertising and visitors, so it is a confounder. Before building the model, make a prediction.
In the visitors ~ ad_spend model, the ad spend coefficient is 1.627. If we add + weekend to the formula, which way does the ad spend coefficient go?
Let's build the two models side by side:
import pandas as pd import statsmodels.formula.api as smf m = pd.read_csv("marketing.csv") m1 = smf.ols("visitors ~ ad_spend", data=m).fit() m2 = smf.ols("visitors ~ ad_spend + weekend", data=m).fit() print(m1.params.round(4)) print(m2.params.round(4)) print("R²:", round(m1.rsquared, 3), "->", round(m2.rsquared, 3))
OutputIntercept 1200.1417
ad_spend 1.6270
dtype: float64
Intercept 1159.8810
ad_spend 1.4481
weekend 237.9945
dtype: float64
R²: 0.635 -> 0.897Three things changed. First, the ad spend coefficient went down from 1.627 to 1.448. Second, a new coefficient appeared: weekend is about 238. Third, R² went up from 0.635 to 0.897: about 90% of the day-to-day variation in visitors is now explained by the two explanatory variables together.
The rule for reading coefficients is the most important idea of multiple regression: each coefficient is the average change associated with a one-unit increase in that variable, when the other explanatory variables are held constant. People say "holding the others constant" for short.
Why did it go from 163 to 145? The simple model did not know about the weekend. On weekends, both advertising and visitors were high, so the model credited this extra to the only explanatory variable next to it, advertising. In the second model, the weekend has its own coefficient, and advertising keeps only the part that changes together with visitors "within the same kind of day". This is the model version of the "look within groups" idea from lesson 37: compare weekdays and weekends separately and find one shared slope.
The uncertainty of the coefficient also got smaller: m2.conf_int() gives a 95% confidence interval of 1.3496 to 1.5465 for the ad spend coefficient. Each coefficient also has a p-value (m2.pvalues). In the meaning from lesson 28, it answers the question: "If this coefficient were really zero, would we see a value this extreme?"
The model now knows the weekend in its estimates too. For a day with $150 of ad spend, the weekday estimate is 1,160 + 1.448 × 150 ≈ 1,377 visitors, and the weekend estimate adds 238 to that: ≈ 1,615 visitors. The simple model gave both days the same number (1,444). The typical estimate error also got smaller: the standard deviation of the residuals went from 126 visitors to 67 visitors.
Now try it yourself. The cell below has two models. Delete the + weekend part from the second formula and run it again, then add it back and watch how the ad spend coefficient changes.
Try it now· not graded; doesn't affect progress
Let's correct a common misunderstanding here: it is wrong to think that adding a variable does not change the coefficients of the others. If the new explanatory variable is related to the old one (here the correlation between weekend and ad spend is r = 0.17), the old coefficient changes. If they are not related at all, it stays almost the same. You will see this in section 7, in an example outside the case.
C() and the reference categoryThe second question is about carriers. Carrier is a string variable: Arrow Express, Caravan Freight, and Gull Post. In lesson 32 you compared the satisfaction means of two carriers, and in lesson 35 you met ANOVA, which tests three groups together. You can ask the same question with regression too.
A string variable cannot go into a regression equation directly, because the equation works with numbers. In a statsmodels formula, a categorical variable is written as C(carrier). C comes from the word "categorical". For each category, statsmodels prepares a 0/1 column (1 in the "Caravan" column if a package went with Caravan, 0 in the others) and leaves one category out as the reference. The reference is the first category in alphabetical order: Arrow Express. Each coefficient is the mean difference of that category from the reference.
import pandas as pd import statsmodels.formula.api as smf s = pd.read_csv("survey.csv") m = smf.ols("satisfaction ~ C(carrier)", data=s).fit() print(m.params.round(3)) print(s.groupby("carrier")["satisfaction"].mean().round(3))
OutputIntercept 4.192
C(carrier)[T.Caravan Freight] -0.530
C(carrier)[T.Gull Post] -0.403
dtype: float64
carrier
Arrow Express 4.192
Caravan Freight 3.662
Gull Post 3.789
Name: satisfaction, dtype: float64Read the coefficient names: C(carrier)[T.Caravan Freight] means "the Caravan Freight category of the carrier variable" (T. means a comparison against the reference). The table has no row for Arrow, because Arrow is the reference; its mean sits in the intercept: 4.192. The Caravan coefficient is −0.530: the satisfaction of Caravan customers is 0.53 points lower than Arrow's on average (3.662 = 4.192 − 0.530). The Gull coefficient is −0.403: Gull is 0.40 points lower than Arrow. Compare with the group means: they are the same numbers. A regression with one categorical explanatory variable is another way of writing a comparison of group means; the ANOVA in lesson 35 uses the same model.
In the satisfaction ~ C(carrier) model, the coefficient C(carrier)[T.Caravan Freight] is −0.53. What does it mean?
Now let's look at a common shortcut: coding categories as numbers. If you say Arrow is 1, Caravan is 2, and Gull is 3, and give this column as if it were a numeric explanatory variable, the model does not give an error. It produces a number:
import pandas as pd import statsmodels.formula.api as smf s = pd.read_csv("survey.csv") s["code"] = s["carrier"].map({"Arrow Express": 1, "Caravan Freight": 2, "Gull Post": 3}) wrong = smf.ols("satisfaction ~ code", data=s).fit() print(wrong.params.round(3))
OutputIntercept 4.337
code -0.218
dtype: float64One slope: "when the code goes up by one, satisfaction drops by 0.218." This sentence has no meaning. The model assumes an order between carriers (Arrow < Caravan < Gull) and equal spacing: it treats Caravan as 0.22 lower than Arrow and Gull as 0.44 lower than Arrow. In the real means, though, Gull is better than Caravan. If you had given the codes in another order, you would get a very different slope. Categorical variables always go in with C(); each category gets its own coefficient.
Match the coefficients of the two models in this lesson with the correct interpretation.
For each row, pick its match from the list, then check.
Caravan's satisfaction is 0.53 points lower than Arrow's. The logistics team asks: is this gap caused by the carrier itself (rude couriers, damaged packages), or because Caravan delivers packages later? In the second case, the fix is not changing the carrier but shortening the delivery time. First look at the mean delivery time of the carriers, then at the model that includes delivery time:
import pandas as pd import statsmodels.formula.api as smf s = pd.read_csv("survey.csv") print(s.groupby("carrier")["delivery_days"].mean().round(2)) m3 = smf.ols("satisfaction ~ delivery_days + C(carrier)", data=s).fit() print(pd.DataFrame({"coef": m3.params.round(3), "p": m3.pvalues.round(4)}))
Outputcarrier
Arrow Express 2.29
Caravan Freight 3.89
Gull Post 3.12
Name: delivery_days, dtype: float64
coef p
Intercept 5.221 0.0000
C(carrier)[T.Caravan Freight] 0.186 0.1156
C(carrier)[T.Gull Post] -0.031 0.7562
delivery_days -0.449 0.0000Caravan packages are delivered in 3.89 days on average, and Arrow packages in 2.29 days. When delivery time enters the model, the picture changes:
Interpretation: Caravan customers are less satisfied because Caravan's deliveries take longer. The path of the effect is like a chain of arrows: carrier → delivery time → satisfaction. An in-between variable that an effect passes through is called a mediator. When you add the mediator to the model, the coefficient of the first variable gets smaller or disappears, because now the comparison is made "at the same delivery time", and the path that carries the carrier's effect is held fixed.
You can see the same result with the method of lesson 37, by looking within groups. Let's take only the packages delivered in 3 days:
import pandas as pd s = pd.read_csv("survey.csv") three_days = s[s["delivery_days"] == 3] print(three_days.groupby("carrier")["satisfaction"].agg(["mean", "count"]).round(2))
Output mean count
carrier
Arrow Express 3.83 46
Caravan Freight 4.17 18
Gull Post 4.00 36Among packages delivered in three days, Caravan's mean (4.17) is even higher than Arrow's (3.83), but there are only 18 Caravan packages, so you should not make too much of this gap. The main message is the same: when the delivery time is the same, no clear gap remains between carriers. The model does this "look within groups" work for all delivery days at once, with one shared delivery slope.
Watch out for one misunderstanding: it is wrong to think that a variable whose coefficient became meaningless has no role. The relationship between carrier and satisfaction did not disappear; its path became visible. The carrier affects delivery time (2.29 days against 3.89 days), and delivery time affects satisfaction. For logistics, the result is concrete: the goal may not be "stop working with Caravan" but "bring Caravan's delivery time to Arrow's level".
Follow the estimates of the two models step by step for one customer: a package sent with Caravan and delivered in 4 days.
Run the code line by line: see which line runs next, the variable boxes and the output.
# Model 1: satisfaction ~ C(carrier) intercept1 = 4.192 caravan1 = -0.530 estimate1 = intercept1 + caravan1 # Model 2: satisfaction ~ delivery_days + C(carrier) intercept2 = 5.221 delivery2 = -0.449 caravan2 = 0.186 days = 4 estimate2 = intercept2 + delivery2 * days + caravan2 print("Model 1:", round(estimate1, 2)) print("Model 2:", round(estimate2, 2))
Model 1 gives every Caravan package the same estimate (3.66), because it does not know the delivery time. In model 2, the estimate changes with the delivery time: 5.221 − 0.449 × 4 + 0.186 ≈ 3.61. If the same Caravan package had arrived in 2 days, model 2 would estimate about 4.51. Now choose the formula yourself and compare the coefficients of three models:
Change the formula: how do the Caravan coefficient, the delivery coefficient, and R² change?
Pick a value; predict the output first, then look.
1import pandas as pd2import statsmodels.formula.api as smf3formula = "C(carrier)"4# This box cannot read files: the 300 rows of the survey are built from a count table.5# For each carrier, delivery days go 1, 2, 3, ... in order; each list counts the satisfaction scores 2, 3, 4, 56counts = {7 "Arrow Express": [[0, 0, 5, 23], [1, 5, 19, 21], [1, 12, 27, 6], [2, 2, 4, 2]],8 "Caravan Freight": [[0, 0, 0, 1], [0, 0, 4, 1], [0, 4, 7, 7], [2, 13, 18, 4], [3, 11, 2, 1], [1, 0, 0, 0], [0, 1, 0, 0]],9 "Gull Post": [[0, 0, 2, 0], [0, 0, 16, 6], [0, 7, 22, 7], [3, 12, 8, 0], [1, 5, 1, 0]],10}11rows = []12for carrier, days in counts.items():13 for day, amounts in enumerate(days, start=1):14 for score, amount in zip([2, 3, 4, 5], amounts):15 rows += [(carrier, day, score)] * amount16s = pd.DataFrame(rows, columns=["carrier", "delivery_days", "satisfaction"])17m = smf.ols("satisfaction ~ " + formula, data=s).fit()18caravan = m.params.get("C(carrier)[T.Caravan Freight]")19delivery = m.params.get("delivery_days")20print("satisfaction ~", formula, "| rows:", len(s))21print("Caravan:", "not in model" if caravan is None else round(caravan, 3))22print("Delivery days:", "not in model" if delivery is None else round(delivery, 3))23print("R²:", round(m.rsquared, 3))
satisfaction ~ C(carrier) | rows: 300 Caravan: -0.53 Delivery days: not in model R²: 0.08
Faded lines didn't run with this value. The carrier alone explains only 8% of satisfaction; delivery days alone explain 32%. With both in the model, R² rises only to 0.333, and the Caravan coefficient goes from −0.53 to +0.19: almost all the information the carrier carries is already in the delivery time. The delivery coefficient also grows a little, from −0.415 to −0.449.
Adding explanatory variables is tempting: R² went from 0.635 to 0.897, so wouldn't one more variable make it even better? Be careful here: adding a variable to the model never lowers R². Least squares can give the new variable a zero coefficient and keep the old model exactly, so the new model fits at least as well as the old one. Even a completely meaningless column raises R² a little, by fitting some of the chance fluctuations in the data.
To see this, let's add a column of random numbers to the model. This column cannot have any real relationship with visitors.
If I add a column of completely random numbers to the visitors ~ ad_spend + weekend model, what happens to R²?
import numpy as np import pandas as pd import statsmodels.formula.api as smf m = pd.read_csv("marketing.csv") rng = np.random.default_rng(42) m["random_col"] = rng.normal(size=len(m)) m2 = smf.ols("visitors ~ ad_spend + weekend", data=m).fit() m4 = smf.ols("visitors ~ ad_spend + weekend + random_col", data=m).fit() print("R²:", round(m2.rsquared, 4), "->", round(m4.rsquared, 4)) print("Adjusted R²:", round(m2.rsquared_adj, 4), "->", round(m4.rsquared_adj, 4)) print("Difference:", round(m4.rsquared - m2.rsquared, 5))
OutputR²: 0.8967 -> 0.8967
Adjusted R²: 0.8955 -> 0.895
Difference: 4e-05R² looks the same to four decimal places, but it really went up by 0.00004. Adjusted R² (rsquared_adj) went down from 0.8955 to 0.8950. Adjusted R² takes off a small penalty for every new explanatory variable; if the new variable does not add enough explanation to pay this penalty, it goes down. When you compare two models, look at adjusted R²: here the model with the random column is worse. That is why "R² went up, so the model is better" is wrong.
In Bazaar, adding the weekend changed the ad spend coefficient. Does this always happen? Let's look at rental apartment listings on a real estate site (listings.csv, fictional sample data; 608 listings, six neighborhoods). In lesson 35 you saw a few extreme listings in this file ($29,000 rent, a 1,150 m² apartment). They would distort the slope on their own, so we use the filter from lesson 5 and work with the 604 listings with rent under $10,000 and area under 400 m².
import pandas as pd import statsmodels.formula.api as smf d = pd.read_csv("listings.csv") d = d[(d["rent"] < 10000) & (d["area_m2"] < 400)] r1 = smf.ols("rent ~ area_m2", data=d).fit() r2 = smf.ols("rent ~ area_m2 + C(neighborhood)", data=d).fit() print(len(d)) print("area_m2 coefficient:", round(r1.params["area_m2"], 1), "->", round(r2.params["area_m2"], 1)) print("R²:", round(r1.rsquared, 3), "->", round(r2.rsquared, 3)) print(r2.params.round(1)) print(d.groupby("neighborhood")["area_m2"].mean().round(1))
Output604
area_m2 coefficient: 13.1 -> 13.4
R²: 0.435 -> 0.73
Intercept -216.2
C(neighborhood)[T.Harborside] 1020.7
C(neighborhood)[T.Midtown] 481.1
C(neighborhood)[T.Old Town] 945.2
C(neighborhood)[T.Riverside] 549.5
C(neighborhood)[T.Southgate] 160.2
area_m2 13.4
dtype: float64
neighborhood
Eastfield 106.8
Harborside 100.2
Midtown 106.3
Old Town 105.1
Riverside 105.1
Southgate 103.5
Name: area_m2, dtype: float64The neighborhood explains rent very well: R² went from 0.435 to 0.73. The reference neighborhood is Eastfield, the first one alphabetically; an apartment of the same size costs $1,021 more on average in Harborside than in Eastfield, and $160 more in Southgate. Eastfield is the cheapest neighborhood and Harborside the most expensive, so the gap between them is about $1,021 for the same size. But the area coefficient hardly changed: from $13.1 to $13.4 per m². Why? The last table gives the answer: the mean apartment size of the six neighborhoods is very close (100–107 m²). Neighborhood is not related to area, so there was no "neighborhood share" written into the area coefficient.
The rule is: if the added explanatory variable is related to the first one, the first coefficient changes. In Bazaar, weekend was related to ad spend (ad spend is high on weekends), and the coefficient went from 1.627 to 1.448. Here neighborhood is not related to area; the coefficient stayed in place, but the estimates got much better. You do not judge whether a variable is important by asking "did it change the other coefficient?", but by its own coefficient and the explanatory power of the model.
A real estate site wants to show a rent suggestion of "about $13 per square meter" to people who post a listing. It has two models: rent ~ area_m2 (slope $13.1 per m², R² 0.44) and rent ~ area_m2 + C(neighborhood) (slope $13.4 per m², R² 0.73). What do you recommend?
Pick an option and see what happens. There are no points; you can try the other options too.
Multiple regression is a powerful tool, but you should not use it without knowing three limits.
The last point is the most important: a controlled model does not prove causation. Saying "we accounted for the weekend, so advertising increases visitors" is one step too far. Multiple regression does the best we can do with observational data: it holds constant the confounders we measured. The strongest evidence for causation is an experiment where advertising is assigned at random; you will see this with the A/B test in lesson 42. Until then, keep saying "associated" in your sentences.
The order of the work you did in this lesson is the same in every multiple regression analysis. Put the steps in order:
Put the steps of a multiple regression analysis in the correct order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You have finished Unit 7: you saw a relationship with the scatter plot and r (36), learned how a confounder can mislead a relationship (37), read the slope with its unit (38), and in this lesson held the confounder fixed inside the model with a second explanatory variable. In the unit task G7 ("Relationship or cause?"), you will use all of these on data you have not seen before, city bike rentals. In Unit 8 we move from analysis to decision: the conversion funnel, time series, and the A/B test.
predict takes a table that asks for the value of every explanatory variable in a multiple model:
import pandas as pd import statsmodels.formula.api as smf m = pd.read_csv("marketing.csv") model = smf.ols("visitors ~ ad_spend + weekend", data=m).fit() new_days = pd.DataFrame({"ad_spend": [150, 150], "weekend": [0, 1]}) print(model.predict(new_days).round(0).tolist())
Output[1377.0, 1615.0]On a weekday with $150 of ad spend, about 1,377 visitors are expected, and on a weekend about 1,615; the difference between them is exactly the weekend coefficient (238). The estimate is reliable only within the range of the data ($0.50–$354).
To see directly why the coefficient changed, look at the relationship between the two explanatory variables:
import pandas as pd m = pd.read_csv("marketing.csv") print(m.groupby("weekend")["ad_spend"].mean().round(0)) print(round(m["ad_spend"].corr(m["weekend"]), 2))
weekend 0 146.0 1 184.0 Name: ad_spend, dtype: float64 0.17
Coding a categorical variable as 1, 2, 3 and putting it in the model as a numeric explanatory variable. The model gives no error, but it assumes an order and equal spacing between categories that do not exist, and produces one meaningless slope (code −0.218); it even treats Gull as worse than Caravan. The correct way is to write C(carrier) in the formula: each category gets its own coefficient against the reference (Caravan −0.53, Gull −0.40).
C(), and each coefficient is a difference from the reference category; when a mediator (delivery time) is added and the carrier gap disappears, it shows that the effect passes through that variable.Next lesson: Unit 8 starts; we will measure the customer's journey step by step with the conversion funnel and cohorts.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
On weekends the mean ad spend is $184, and on weekdays $146. Because the two explanatory variables are related (r = 0.17), adding the weekend changed the ad spend coefficient. In the apartment example, neighborhood was not related to area, and the coefficient did not change.
If you want to read the coefficients against Caravan instead of Arrow, you can choose the reference with Treatment:
import pandas as pd import statsmodels.formula.api as smf s = pd.read_csv("survey.csv") r = smf.ols("satisfaction ~ C(carrier, Treatment('Caravan Freight'))", data=s).fit() print(r.params.round(3))
OutputIntercept 3.662
C(carrier, Treatment('Caravan Freight'))[T.Arrow Express] 0.530
C(carrier, Treatment('Caravan Freight'))[T.Gull Post] 0.126
dtype: float64The intercept is now Caravan's mean (3.662); Arrow is 0.530 points higher than it, and Gull 0.126. The model is the same; only the point of comparison changed. Whichever category you choose as the reference, the group means and the estimates stay the same.