Statistics for analysis · lesson 10 of 13
Parts in this lesson
Asmf.ols("kilos ~ rain_mm", data=df).fit()a regression from a formula
Bmodel.params, model.conf_int(), model.rsquaredthe coefficients, their intervals, and R²
C"kilos ~ rain_mm + weekend + C(store)"several predictors, and a category as C(…)
Dmodel.resid, model.predict(new)residuals, and predictions for new rows

Linear regression for analysis

Last updated

Lesson 8.9 found that correlation says how tightly two things move together, but not by how much. A regression says by how much: each extra millimetre of rain comes with so many fewer kilos sold, give or take so much. In this lesson you'll fit lines with statsmodels, read their coefficients as “for each extra…”, add more predictors to compare like with like, check the fit with a residual plot, and see what happens when a line is asked about weather it has never seen.

By the end of this lesson you can

  • Fit a linear regression with statsmodels and read its coefficients
  • Give a coefficient with its confidence interval, and say what R² means
  • Use several predictors, and read each coefficient with the others held fixed
  • Check a fit with a residual plot, and avoid extrapolating

A line through the data

Back to rain and the Batangas store (8.6): one row per day, with the kilos sold and the millimetres of rain. A linear regression fits the straight line

yˆ=b0+b1x

where x is the rain, yˆ ("y-hat") is the kilos the line predicts, b0 is the intercept (the prediction when x=0) and b1 is the slope. Of all straight lines, it picks the one that makes the squared gaps between the real kilos and the line's as small as possible: least squares. Run the cells.

rain_regression.ipynb
  • smf.ols("kilos ~ rain_mm", data=bat) reads as "kilos explained by rain". ols stands for ordinary least squares; .fit() finds the line.
  • model.params: intercept 62.417, slope −0.238.
  • The second cell finds the same numbers with matrices (2.11): βˆ=(X⊤X)−1X⊤y, where X has a column of ones (for the intercept) and a column of rain.

Read a coefficient as "for each extra…": for each extra millimetre of rain, the store sold 0.238 kg less, about 2.4 kg less for 10 mm. And on a dry day, the line expects 62.4 kg.

How sure, and how much it explains

A slope from 60 days is an estimate, like a mean. model.conf_int() (third cell in step 1) gives 95% intervals: the slope is between −0.459 and −0.017 kg per mm. Both ends are below 0, so the data are fairly sure that rain lowers sales, but not by how much: anywhere from almost nothing to nearly half a kilo per millimetre.

R2 says how much of the variation in kilos the line accounts for:

R2=1−∑i(yi−yˆi)2∑i(yi−y¯)2

The top is the squared gaps left over around the line; the bottom, the squared gaps around the plain mean. Here R2=0.074: rain accounts for about 7% of the day-to-day ups and downs. Rain matters, but most of what makes one day busier than another is something else.

A low R2 doesn't make the slope wrong, and a high one doesn't make it right. They answer different questions: the slope says how much sales move with rain; R2 says how much of the story rain is.

Several predictors

Saturdays are busy and Batangas is the biggest store. To compare like with like, put those in the model too. Run the cells: all four stores, 240 store-days.

rain_regression.ipynb
  • weekend is True or False; statsmodels turns it into a column of 1s and 0s, named weekend[T.True]. Its coefficient, 9.87, says: on a weekend day, with the same rain at the same store, about 9.9 kg more.
  • C(store) makes a column per store except the first in alphabetical order, Batangas, which becomes the baseline. Lipa's −16.01 means 16 kg a day less than Batangas, with the same rain on the same kind of day.
  • Rain is now −0.22 kg per mm (interval −0.28 to −0.15): close to before, and narrower, because the model no longer has to explain store size and weekends as noise.
  • R2=0.809: store, weekend and rain together account for 81% of the variation.

Each coefficient is read with the others held fixed. That's the point of several predictors: it separates the effect of rain from the effects of things that happen to go with it. It only works for the things you put in the model, though: 8.11 is about the ones you didn't.

Residual plots

A residual is what the line gets wrong for one row: yi−yˆi. If the line has the right shape, the residuals are just noise: a shapeless band around 0. If they curve, the line is the wrong shape. Try it:

Residual checkDistance and delivery cost
pesosdistance (km)residual (data − fit)

R² = 0.921. The residuals make a U: the fit is too high in the middle and too low at both ends. A straight line is the wrong shape for this data, however high R² is.

For distance and cost, the straight line has a high R2, yet the residuals make a clear U: too high in the middle, too low at both ends. A curve fixes it. The residuals show what R2 can't. Now the Batangas fit:

rain_regression.ipynb

The residuals have no curve, but they're spread widely: rain leaves most of each day unexplained. Much of that spread is weekends against weekdays. Adding weekend lifts R2 from 0.074 to 0.475, and the typical residual drops from 10.4 to 7.8 kg. When residuals are widely spread or fall into groups, look for the variable that explains them.

Wrong way: 300 mm of rain

A typhoon is coming, with 300 mm of rain forecast. How much rice should the Batangas store stock? Use the model. Run the cell.

rain_regression.ipynb

−8.9 kg. The store will buy back rice from its customers.

The line was fitted to days with 0 to 39.8 mm of rain. Inside that range it's a reasonable summary; outside it, there's no data to say whether sales keep falling in a straight line, level off, or collapse because the store shuts. Predicting outside the range of the data is called extrapolation, and a regression gives no warning when you do it. It prints a number either way.

The check: before using a prediction, compare the new x with the range of x the model was fitted on (bat["rain_mm"].describe()). Inside the range, give the prediction with its interval. Outside it, say the data can't answer, and look for other evidence: here, what happened during past typhoons (5.6).

Check what you learned

A model gives kilos = 40 + 2.5 × customers_per_hour. What does 2.5 mean?
A regression has R² = 0.05 and a slope whose 95% interval is 1.2 to 3.0. What can you say?
A residual plot shows the residuals falling, then rising, in a U. What should you do?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis