…
…
Statistics and Data Analysis Fundamentals · Lesson 38 / 44 · Regression
PreviewIn this lesson you will
smf.ols; read the slope with its context and unit ("every $50 of daily spend is associated with 81 more visitors on average") and read R² as the explained shareYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The marketing team likes the strong correlation between ad spend and visitors (r = 0.80), but nobody builds a budget from a correlation coefficient. The team wants concrete numbers: how many more visitors after $50 more spend, and how many visitors to expect on a day with $150 of spend. In this lesson you will build a line that answers these two questions, and you will separate what the line can say from what it cannot.
By the end of this lesson you will be able to produce the chart below and the two sentences under it yourself. The chart has the scatter plot you know from lesson 36, and something new on top of it: a single line that runs through the middle of the points.
In this lesson you will:
statsmodels in one line, make predictions, and read R².In lesson 36 you found a correlation of 0.797 between ad spend and visitors. This number says two things: the relationship goes upward, and the points are fairly close to a line. But it does not answer marketing's question. "How many more visitors if we spend $50 more?" asks for an amount, while r has no unit; it knows neither dollars nor visitors. You also saw this in a block in lesson 36: when you converted the spend to another unit, r did not change, but another number changed, the one called the "slope". In this lesson we will find that number.
Regression builds an equation that predicts one variable from another. The simplest form is a line:
ŷ = a + b × x
Here x is the explanatory variable (ad spend), y is the response variable (visitors), and ŷ ("y hat") is the number of visitors the model predicts. b is the slope and a is the intercept. Because there is only one explanatory variable, this model is called simple linear regression. Remember the layout from lesson 36: the explanatory variable goes on the horizontal axis and the response on the vertical axis. In regression this choice is more than a drawing decision; it decides which variable is predicted from which.
Countless lines can be drawn through a scatter plot. Which one is "best"? When you pick a line, you produce a prediction for every day. The difference between the real number of visitors on that day and the line's prediction is called the residual:
residual = observed − predicted
If the point is above the line, the residual is positive (the model predicted too low). If it is below, the residual is negative (the model predicted too high). A good line should have small residuals. But we cannot simply add the residuals: positives and negatives cancel each other, and even a very bad line can add up to zero. You met the same problem with the standard deviation in lesson 14, and the solution is the same: square first. The least squares method picks the line that makes the sum of the squared residuals as small as possible. Squaring removes the direction and punishes large errors more: an error of 200 visitors counts four times as much as an error of 100, not twice as much.
Try it by hand. In the code below, the spend and visitors of 181 days are ready (the numbers are typed into the code because the block cannot read files). Choose a slope and an intercept; the code calculates the prediction and the residual for every day and prints the sum of the squared residuals in millions. Which of the six combinations gives the smallest sum?
Which slope and intercept give the smallest sum of squared residuals?
Pick a value; predict the output first, then look.
1import numpy as np2# the 181 days of marketing.csv (the numbers are typed in because the block cannot read files)3spend = np.array([266, 147.5, 320.5, 253, 215.5, 256.5, 165.5, 245.5, 241, 323, 236, 193, 190, 143, 205, 208, 292.5, 254, 206, 211, 250.5, 202, 190, 299.5, 246, 212, 147, 209.5, 220, 181, 318.5, 295, 162, 214, 207.5, 289.5, 193.5, 219, 268, 202, 223, 178, 188.5, 297.5, 285.5, 253.5, 213.5, 189.5, 222, 176.5, 238, 284, 222, 248.5, 217, 152, 190.5, 246.5, 261.5, 243.5, 260.5, 275.5, 149.5, 238.5, 270, 158, 286, 156.5, 219.5, 205, 217.5, 162.5, 290.5, 230, 209.5, 220.5, 209.5, 172, 232, 292.5, 174.5, 174.5, 173.5, 210, 209, 226, 213.5, 223.5, 195, 213.5, 207.5, 204.5, 228, 290, 259, 183, 265, 260, 180, 280, 354, 282.5, 241, 201, 197, 175, 211.5, 271, 267.5, 202.5, 191.5, 119, 199, 197, 306.5, 287, 171, 209, 177, 223.5, 37, 45.5, 36, 20, 19.5, 37, 14, 11, 23, 32.5, 18.5, 32, 23.5, 8.5, 33, 22.5, 16.5, 14.5, 24, 44.5, 29, 23, 14.5, 43, 26.5, 28, 24, 13.5, 44, 29.5, 13, 27.5, 18.5, 18.5, 29, 29.5, 34.5, 52, 17, 25, 23, 33.5, 14, 30.5, 26.5, 16, 11, 25.5, 31, 11.5, 29.5, 20, 6, 24.5, 15, 23.5, 32, 20.5, 24, 27, 0.5])4visitors = np.array([1538, 1376, 1747, 1725, 1509, 1591, 1472, 1473, 1547, 1927, 1775, 1438, 1442, 1358, 1378, 1416, 1868, 1792, 1481, 1375, 1415, 1407, 1380, 1875, 1622, 1409, 1359, 1449, 1419, 1460, 1840, 1837, 1483, 1463, 1481, 1435, 1525, 1786, 1799, 1579, 1489, 1404, 1540, 1603, 1963, 1657, 1451, 1379, 1529, 1519, 1382, 1840, 1685, 1595, 1389, 1550, 1409, 1578, 1739, 1676, 1441, 1574, 1444, 1383, 1630, 1627, 1768, 1262, 1504, 1383, 1538, 1371, 1788, 1650, 1532, 1430, 1449, 1471, 1648, 1817, 1647, 1471, 1375, 1483, 1396, 1539, 1793, 1766, 1568, 1426, 1509, 1435, 1468, 1854, 1674, 1518, 1497, 1517, 1477, 1610, 1896, 1906, 1428, 1449, 1502, 1395, 1556, 1749, 1812, 1396, 1486, 1277, 1373, 1377, 1935, 1781, 1464, 1460, 1279, 1513, 1354, 1502, 1340, 1120, 1155, 1214, 1213, 1102, 1328, 1498, 1162, 1203, 1168, 1075, 1228, 1439, 1416, 1207, 1192, 1204, 1192, 1233, 1430, 1396, 1248, 1058, 1219, 1240, 1151, 1514, 1432, 1208, 1098, 1156, 1099, 1314, 1486, 1605, 1262, 1270, 1314, 1133, 1096, 1463, 1448, 1127, 1155, 1187, 1249, 1176, 1461, 1377, 1067, 1174, 1237, 1263, 1123, 1375, 1428, 1320, 1193])5slope = 1.6276intercept = 12007predicted = intercept + slope * spend8residual = visitors - predicted9sum_sq = (residual ** 2).sum()10print("Line: ŷ =", intercept, "+", slope, "× spend")11print("Residual of the first day:", round(residual[0]))12print("Sum of squared residuals:", round(sum_sq / 1_000_000, 2), "million")
Line: ŷ = 1200 + 1.627 × spend Residual of the first day: -95 Sum of squared residuals: 2.84 million
Faded lines didn't run with this value. The smallest sum (2.84 million) is at slope 1.627 and intercept 1,200: the least squares line. When the slope gets smaller, the line has to start higher to reach the points on the right; when the slope gets bigger, it has to start lower. Slope and intercept are chosen together.
Among the six combinations, the smallest sum is 2.84 million, at slope 1.627 and intercept 1,200. Look closely: with a slope of 1.0, keeping the intercept at 1,200 (5.34) is much better than lowering it to 1,000 (19.72); with a slope of 2.4 it is the other way around. Slope and intercept depend on each other: a steeper line has to start lower on the left to reach the points on the right. Least squares chooses both together, and for this data the answer is unique. This line has one more property: it always passes through the point where the two means meet, that is, (mean spend, mean visitors) = ($157.1, 1,456 visitors).
"The best line passes through most of the points" is a common misunderstanding. The least squares line may not pass exactly through a single point; its goal is not to touch a point but to be as close as possible to all points in total.
For this data the least squares line is ŷ = 1,200 + 1.627 × spend. You must read both numbers with their units.
The slope is 1.627 visitors per dollar: between two days whose spend differs by $1, the number of visitors differs by 1.627 on average. A difference of $1 means little to anyone, so choose a useful scale: $50 × 1.627 = 81.4. So on days with $50 more daily spend, about 81 more visitors are seen on average. The unit of a slope is always "y unit per x unit"; a slope given without its unit (just "1.63") tells the reader nothing.
The intercept is 1,200 visitors: the model's prediction for a day with zero spend. Before you interpret this number, ask a question: are there days close to x = 0 in my data? At Bazaar there are. As you saw in lesson 36, ads were almost switched off in May and June; the lowest spend is $0.50. So "about 1,200 visitors on a day without ads" is a reasonable interpretation that stays inside the data. In section 7 you will see an example where the intercept has no meaning.
Now to the most important word: associated. It is tempting to read the slope as "if we spend $50, 81 visitors will come", but that is a cause-and-effect sentence. Remember the confounder from lesson 37: on weekends more is spent on ads (mean $184 against $146 on weekdays), and more visitors come on weekends anyway. The line cannot separate these two effects; part of the extra visitors on high-spend days may really come from the weekend. This is why a regression sentence is built with "associated". In the next lesson, when you add the weekend to the model, you will see that the slope per $50 drops from 81 to 72, that is, about 9 of the 81 visitors belong to the weekend.
Model: ŷ = 1,200 + 1.627 × spend (spend in dollars, ŷ in visitors). Which sentence describes the slope correctly?
smf.olsIn lesson 31 you used the ready-made tests of the statsmodels library. The formula interface of the same library builds a regression in one line. A formula is a string: "visitors ~ ad_spend". The response stands on the left of the tilde (~) and the explanatory variable on the right; read it as "explain visitors with ad spend". smf.ols defines the model (OLS, "ordinary least squares"), .fit() does the least squares calculation and returns the result as an object. Three attributes and one method of this object are the toolbox of this lesson:
| Name | What it gives |
|---|---|
m.params | The coefficients: Intercept and the slope, named after the explanatory variable |
m.rsquared | R² (section 4) |
m.resid | The residual of every observation (section 5) |
m.predict(new) | Predictions for new x values; new is a DataFrame with the same column name |
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("visitors ~ ad_spend", data=mkt).fit() print(m.params.round(4)) print("R²:", round(m.rsquared, 3)) new = pd.DataFrame({"ad_spend": [150]}) print("Prediction for $150:", round(m.predict(new).iloc[0]))
OutputIntercept 1200.1417
ad_spend 1.6270
dtype: float64
R²: 0.635
Prediction for $150: 1444The intercept is 1,200.14 and the slope is 1.627: the best combination from the trial board in section 1, now with more decimals. predict wants the new values in a DataFrame because the model recognizes columns by name; the column name must be the same as the name in the formula. The answer to marketing's second question is here too: on a day with $150 of spend, about 1,444 visitors.
You can also see where the slope comes from with the numbers of lesson 36. In simple regression, slope = r × (s_y / s_x): the correlation is scaled by the ratio of the standard deviations of the two variables. r had no unit; the ratio s_y / s_x gives it the unit "visitors per dollar".
import pandas as pd mkt = pd.read_csv("marketing.csv") r = mkt["ad_spend"].corr(mkt["visitors"]) s_x = mkt["ad_spend"].std() s_y = mkt["visitors"].std() slope = r * s_y / s_x intercept = mkt["visitors"].mean() - slope * mkt["ad_spend"].mean() print("r:", round(r, 3), "| s_y:", round(s_y), "| s_x:", round(s_x, 1)) print("Slope:", round(slope, 4), "| intercept:", round(intercept, 1))
Outputr: 0.797 | s_y: 208 | s_x: 101.9
Slope: 1.627 | intercept: 1200.10.797 × 208 / 101.9 = 1.627. The intercept formula comes from the property in section 1: because the line passes through the point (x̄, ȳ), a = ȳ − b × x̄. This formula also shows something clearly: if r = 0, the slope is 0 too, and the line is flat and predicts the mean number of visitors for every day. The stronger r is, the more "bold" the predictions of the line are.
Now run it yourself. The cell builds the model and prints the coefficients, R², and the $150 prediction. Then change the response:
Try it now· not graded; doesn't affect progress
In the orders model the slope is 0.0095 orders per dollar, that is, about 0.5 orders per $50 on average; R² is 0.15. Visitors formed a tight band with spend, while orders, as you saw in lesson 36, are a wide cloud. The same tool and the same formula give very different reliability.
The model produces a prediction (m.fittedvalues) and a residual (m.resid) for every day. Let's look at the first three days:
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("visitors ~ ad_spend", data=mkt).fit() mkt["predicted"] = m.fittedvalues mkt["residual"] = m.resid print(mkt[["date", "ad_spend", "visitors", "predicted", "residual"]].head(3).round(1))
Output date ad_spend visitors predicted residual
0 2026-01-01 266.0 1538 1632.9 -94.9
1 2026-01-02 147.5 1376 1440.1 -64.1
2 2026-01-03 320.5 1747 1721.6 25.4On January 1, $266 was spent; the model expected 1,632.9 visitors and 1,538 came: the residual is −94.9 (the point is below the line). On January 3 the expected number is 1,721.6 and the observed number is 1,747: the residual is +25.4. Follow the calculation of a single day line by line:
Run the code line by line: see which line runs next, the variable boxes and the output.
intercept = 1200.14 slope = 1.627 spend = 266 # January 1 observed = 1538 predicted = intercept + slope * spend residual = observed - predicted print("Prediction:", round(predicted)) print("Residual:", round(residual)) if residual > 0: print("The point is above the line: the model predicted too low") else: print("The point is below the line: the model predicted too high")
Change the lines and watch again: if you write spend = 147.5 and observed = 1376, you get the prediction (1,440) and the residual (−64) of January 2.
Two more tools are worth knowing, but we will not use them in this lesson. The SciPy function stats.linregress(x, y) gives the slope, the intercept, and r in one call; it also returns a p-value (the probability of seeing a slope this steep if the true slope were zero; here it is around 10⁻⁴¹). The NumPy call np.polyfit(x, y, 1) gives the same line. We continue with smf.ols, because in the next lesson adding a second variable to the formula will be as easy as adding one + sign.
The number of visitors changes from day to day: between 1,058 and 1,963, with a standard deviation of 208. If we used no model, we would predict the mean (1,456) for every day, and the sum of our squared errors would be 7.79 million. With the line, this sum falls to 2.84 million (the best combination in section 1). R² is the proportion of this drop:
R² = 1 − (sum of squared residuals) / (sum of squared deviations from the mean)
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("visitors ~ ad_spend", data=mkt).fit() remaining = (m.resid ** 2).sum() total = ((mkt["visitors"] - mkt["visitors"].mean()) ** 2).sum() r = mkt["ad_spend"].corr(mkt["visitors"]) print("With the mean:", round(total / 1e6, 2), "million | with the line:", round(remaining / 1e6, 2), "million") print("R² by hand:", round(1 - remaining / total, 3), "| m.rsquared:", round(m.rsquared, 3), "| r²:", round(r ** 2, 3))
OutputWith the mean: 7.79 million | with the line: 2.84 million
R² by hand: 0.635 | m.rsquared: 0.635 | r²: 0.635Three ways, one number: 0.635. You read it like this: about 63% of the day-to-day variability in visitors is explained together with spend; the remaining 37% comes from factors outside the model (weekend, weather, chance). In simple regression R² is always the square of r; 0.797² = 0.635. This is why a "medium" correlation such as r = 0.5 explains only a quarter of the variability.
Here is the same measure for another model: the logistic claim in lesson 36 was between delivery time and satisfaction (r = −0.57). Let's build its regression too:
import pandas as pd import statsmodels.formula.api as smf survey = pd.read_csv("survey.csv") m2 = smf.ols("satisfaction ~ delivery_days", data=survey).fit() print(m2.params.round(3)) print("R²:", round(m2.rsquared, 2))
OutputIntercept 5.160
delivery_days -0.415
dtype: float64
R²: 0.32The slope is −0.415 points per day: orders whose delivery takes one day longer have a satisfaction that is 0.4 points lower on average. The intercept is 5.16 and R² is 0.32: delivery time explains about a third of the differences in satisfaction. It is a weaker model than the ad model, but still useful information.
Next to R², there is one more number worth knowing: the standard deviation of the residuals. In the ad model it is 126 visitors; that is, a prediction is typically off by about ±126 people. Without the model the typical deviation was 208 people. "R² = 0.63" is an abstract ratio; "our predictions are usually off by about 126 visitors" is a sentence the marketing team understands immediately.
Note one misunderstanding here: a high R² does not mean the model is correct. R² only says how much variability is explained; it does not say whether the model misses something systematically. To see that, you have to look at the residuals.
In a good model the residuals are scattered randomly around zero: on some days the model predicts a little too high, on others a little too low, and these errors have no pattern. If you see a pattern in the residuals, the model is missing something. The tool for seeing it is the residual plot: the explanatory variable (or another variable) on the horizontal axis, the residual on the vertical axis, and a zero line in the middle.
Let's show the weekend days in a separate color in Bazaar's residual plot:
The purple points (weekends) are mostly above the zero line, and the open points (weekdays) are mostly below. Let's calculate their means:
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("visitors ~ ad_spend", data=mkt).fit() print("Mean of the residuals (absolute):", round(abs(m.resid.mean()), 6)) print("Standard deviation of the residuals:", round(m.resid.std(), 1)) print(m.resid.groupby(mkt["weekend"]).mean().round(1))
OutputMean of the residuals (absolute): 0.0
Standard deviation of the residuals: 125.7
weekend
0 -66.4
1 164.8
dtype: float64The overall mean of the residuals is zero; this is always true for a least squares line, so "the mean is zero, so the model is good" says nothing. When you split into groups the picture changes: the residuals of weekend days are +165 on average, and those of weekdays are −66. The model underestimates weekends by 165 visitors and overestimates weekdays by 66 visitors, systematically. R² = 0.63 is a nice number, but the model does not know the calendar. This is the trace of the confounder from section 2 in the residuals, and it is the topic of the next lesson: adding the weekend to the model.
Draw the plot yourself. First run it as it is, then change three lines to the satisfaction model:
Try it now· not graded; doesn't affect progress
In the satisfaction model the residuals by carrier are between −0.08 and +0.11; Caravan Freight is a little higher and Gull Post a little lower, but there is no separation as clear as the weekend effect. Something else catches the eye in this plot: because satisfaction is an integer from 1 to 5, the residuals line up in vertical strips at every delivery day. This is not an error; it is the trace of the response being an integer.
There are four typical pictures you may meet in a residual plot. Match each one with what it means:
A residual plot (x on the horizontal axis, residual on the vertical axis) looks like this. What does it say?
For each row, pick its match from the list, then check.
The assumptions of linear regression can be read from these four pictures: the relationship is linear (no U), the observations are independent of each other, the spread of the residuals is the same at every x (no funnel), and the residuals are roughly normally distributed. In this lesson it is enough to check these assumptions by looking at the plot.
The main use of a model is prediction. Let's get predictions for a few spend levels:
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("visitors ~ ad_spend", data=mkt).fit() print("Observed range ($):", mkt["ad_spend"].min(), "-", mkt["ad_spend"].max()) new = pd.DataFrame({"ad_spend": [150, 354, 2500]}) new["predicted"] = m.predict(new).round(0) print(new)
OutputObserved range ($): 0.5 - 354.0
ad_spend predicted
0 150 1444.0
1 354 1776.0
2 2500 5268.0The predictions for $150 (1,444) and for $354 (1,776, the highest spend in the data) stay inside the data. For $2,500 the model says 5,268 visitors. Can we trust this number? No. Bazaar never spent more than $354; $2,500 is seven times the highest observed value. The model assumes "the relationship continues in that region with the same slope", but the data says nothing about it. In reality the return on advertising falls after some point: an ad shown to the same people for the fifth time does not work like the first. A prediction that goes outside the range where the data was observed is called extrapolation, and it is the most common mistake in regression.
Extrapolation can even produce impossible results. The satisfaction model predicts 5.16 − 0.415 × 10 = 1.01 points for a delivery that takes 10 days; for 15 days it gives −1.06, which is not on the 1–5 scale. The longest delivery in the survey was 7 days. The line does not know the limits of the scale; you are the one who knows them.
In Bazaar's data the daily ad spend is between $0.50 and $354. Management is thinking about spending $2,500 a day and asks for the model's prediction (5,268 visitors). What do you say?
Remember the 10 students from lesson 36: you found r = 0.956 between weekly study hours and exam score (fictional sample data). In that lesson we said "r does not tell how many points one more hour of study adds to the score; that is the slope". Now we can find the slope:
import pandas as pd import statsmodels.formula.api as smf students = pd.DataFrame({ "hours": [2, 3, 4, 5, 6, 7, 8, 9, 10, 12], "exam": [52, 58, 55, 64, 61, 72, 70, 79, 74, 88], }) m = smf.ols("exam ~ hours", data=students).fit() print(m.params.round(2)) print("R²:", round(m.rsquared, 3)) new = pd.DataFrame({"hours": [0, 9, 40]}) print(m.predict(new).round(1).tolist())
OutputIntercept 44.93
hours 3.39
dtype: float64
R²: 0.914
[44.9, 75.4, 180.5]The slope is 3.39 points per hour: students who study one more hour per week score 3.4 points higher on average. R² = 0.914 (0.956²): 91% of the differences in scores are explained together with study hours. The prediction for 9 hours is 75.4 points; 9 is between 2 and 12 hours in the data, so it is a reliable prediction.
Look at the intercept: 44.9 points, that is, "the predicted score of a student who does not study at all". But the student who studies least in the data studies 2 hours a week; 0 hours is outside the range. At Bazaar x = 0 was inside the data and we could interpret the intercept; here the intercept is just a number that puts the line in place and has no meaningful interpretation. The "the intercept can always be interpreted" misunderstanding comes from here: first check whether x = 0 is inside the range of the data.
The prediction for 40 hours is 180.5 points. On an exam out of 100 this is impossible, even though R² = 0.91.
A friend sees this model and says: "If I study 40 hours a week I will surely get 100, the model says 180! And R² is 0.91." What do you answer?
Pick an option and see what happens. There are no points; you can try the other options too.
The answers to marketing's two questions are ready: on days with $50 more daily spend, about 81 more visitors are seen on average, and on a day with $150 of spend about 1,444 visitors are expected; predictions are typically off by 126 people and are valid only between $0.50 and $354. But the residual plot gave a warning: the model underestimates weekends by 165 visitors. What happens if we add the weekend to the model? Does the ad slope stay at 81? The next lesson starts with this question.
Let's ask the reverse question on the same data: predicting spend from the number of visitors.
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m1 = smf.ols("visitors ~ ad_spend", data=mkt).fit() m2 = smf.ols("ad_spend ~ visitors", data=mkt).fit() print("Visitors ~ spend slope:", round(m1.params.iloc[1], 4), "visitors per $") print("Spend ~ visitors slope:", round(m2.params.iloc[1], 2), "$ per visitor") print("Inverse of the reverse slope:", round(1 / m2.params.iloc[1], 4)) print("R²:", round(m1.rsquared, 3), round(m2.rsquared, 3))
OutputVisitors ~ spend slope: 1.627 visitors per $
Spend ~ visitors slope: 0.39 $ per visitor
Inverse of the reverse slope: 2.5625
R²: 0.635 0.635The slope of the reverse model is $0.39 per visitor. If you turn this number around to get "visitors per dollar", you find 2.56, not 1.627. The two lines are different, because one minimizes the vertical distances (the errors in visitors) and the other the horizontal distances (the errors in spend). R² is the same in both (0.635), because both are equal to r². Marketing's question is "how many visitors for a given spend?", so the right model is the first.
Reading the slope as cause and effect: "If we spend $50 more, 81 visitors will come." Example 2 showed with numbers why this sentence claims too much: inside similar kinds of days, the difference per $50 is 72 visitors; the rest of the 81 comes from the fact that the days with high spend are already weekend days. In observational data the slope is an association; it does not go into a budget decision as "81 visitors guaranteed".
smf.ols("y ~ x", data=df).fit() and read with params, rsquared, resid, and predict. Slope = r × s_y / s_x (0.797 × 208 / 101.9 = 1.627).Next lesson: you will add a second explanatory variable to the model and see how the ad slope changes when the weekend is taken into account.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
A first look at the weekend confounder: let's fit the model separately for weekdays and weekend days.
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") for value, part in mkt.groupby("weekend"): m = smf.ols("visitors ~ ad_spend", data=part).fit() print("weekend =", value, "| days:", len(part), "| intercept:", round(m.params.iloc[0]), "| per $50:", round(m.params.iloc[1] * 50, 1))
Outputweekend = 0 | days: 129 | intercept: 1160 | per $50: 72.3
weekend = 1 | days: 52 | intercept: 1397 | per $50: 72.5Inside the groups there are 72 visitors per $50; it is almost the same in the two groups. When all days were together we found 81. Where does the difference come from? The weekend line starts 237 visitors above the weekday line, and spend is also higher on weekends. A single line mixes these two effects and gives spend extra credit. In the next lesson you will get the same result with a single model.
The relationship of ads with visitors was strong. Is it the same with orders?
import pandas as pd import statsmodels.formula.api as smf mkt = pd.read_csv("marketing.csv") m = smf.ols("orders ~ ad_spend", data=mkt).fit() print("Orders per $50:", round(m.params.iloc[1] * 50, 2)) print("R²:", round(m.rsquared, 2)) print("Standard deviation of the residuals:", round(m.resid.std(), 2), "| mean orders:", round(mkt["orders"].mean(), 2))
OutputOrders per $50: 0.47
R²: 0.15
Standard deviation of the residuals: 2.29 | mean orders: 4.89There are about 0.47 orders per $50 on average, and R² is 0.15. The standard deviation of the residuals is 2.3 orders and the mean number of orders is 4.9: a prediction is off by almost half as much as the average from one day to the next. The slope is different from zero, but the model is weak for planning orders. A slope "existing" does not mean that a prediction is "useful".