Skip to main content

Data analysis · Intermediate · 20 min

Fit and read a linear regression with statsmodels

By Padding · Updated 18 Nov 2026
Python 3.15 · statsmodels 0.15.0 · pandas 3.1.1 · matplotlib 3.11.2 (checked on python:3.15-slim)

You will fit an ordinary least squares model of maize yield with the statsmodels formula API, read its coefficients, intervals and R-squared, watch a confounder flip a coefficient, check the residuals and write up what the model says without claiming cause.

On this page

A farm survey finds that plots given more fertiliser harvest less maize. Taken at face value, that says fertiliser hurts. It does not, and a linear regression read carefully shows why: the plots that got the most fertiliser were also the ones on the poorest land. This tutorial is about reading a regression well enough to catch that.

You will use statsmodels, the Python library built for explaining data rather than only predicting it. Its summary gives each coefficient with a standard error, a confidence interval and a p-value, which is what you need when the question is "how is yield related to rainfall and fertiliser?" rather than "what will next season's yield be?". For the prediction question, see predict a number with regression in scikit-learn.

The data is generated: 480 maize plots across three invented regions, with seasonal rainfall, fertiliser use and yield. Because you know the recipe behind it, you can check that what the model reports is real. Everything runs offline on a laptop in seconds, in a throwaway folder, ~/maize-regression-demo.

Step 1 · Create the project and install statsmodels

Make the folder and a virtual environment:

Bash
mkdir -p ~/maize-regression-demo
cd ~/maize-regression-demo
python3 -m venv .venv
source .venv/bin/activate

Install pinned versions, so your numbers match the ones in this tutorial. statsmodels needs SciPy and pandas; matplotlib draws the residual plots later:

Bash
pip install --quiet statsmodels==0.15.0 pandas==3.1.1 numpy==2.5.5 scipy==1.18.1 matplotlib==3.11.2

Most of the download is SciPy and NumPy. On prepaid mobile data, run it on Wi-Fi if you can; you only pay for it once per project.

Check it worked

Bash
python -c "import statsmodels, pandas, numpy; print(statsmodels.__version__, pandas.__version__, numpy.__version__)"

The output is 0.15.0 3.1.1 2.5.5. If you see No module named statsmodels, run source .venv/bin/activate again in this terminal.

Step 2 · Generate the plot survey

Each row is one plot: its region, the season's rainfall in millimetres, nitrogen fertiliser in kilograms per hectare, and the yield in tonnes per hectare. The recipe has three features worth knowing before you fit anything:

  • Fertiliser adds 0.015 t/ha per kilogram everywhere.
  • Rainfall helps up to about 1,000 mm, then too much rain starts to cost yield (a curve, not a straight line).
  • Northern plots have poor soil, which costs 2.2 t/ha, and Northern farmers use the most fertiliser, as they might under a subsidy aimed at struggling areas.

Write make_plots.py. The generator is seeded, so you get the same 480 plots every time:

Bash
cat > make_plots.py <<'PY'
import numpy as np
import pandas as pd

rng = np.random.default_rng(2026)
n = 480

region = rng.choice(["Northern", "Central", "Coastal"], size=n, p=[0.40, 0.35, 0.25])
north = region == "Northern"
coast = region == "Coastal"

# Seasonal rainfall in mm: the north is driest, the coast wettest.
rain_mean = np.select([north, coast], [560, 960], default=760)
rainfall_mm = rng.normal(rain_mean, 130).clip(250, 1400).round()

# Fertiliser in kg of nitrogen per hectare: Northern farmers use the most.
fert_mean = np.select([north, coast], [95, 40], default=55)
fertiliser_kg = rng.normal(fert_mean, 20).clip(0, None).round()

# Poor soil in the north. The survey does not record soil.
soil = np.select([north, coast], [-2.2, 0.3], default=0.0)

yield_t = (
    0.9
    + 0.009 * rainfall_mm
    - 0.0000045 * rainfall_mm**2   # too much rain starts to hurt
    + 0.015 * fertiliser_kg
    + soil
    + rng.normal(0, 0.55, size=n)
).round(2)

df = pd.DataFrame({
    "plot_id": [f"P{i:03d}" for i in range(1, n + 1)],
    "region": region,
    "rainfall_mm": rainfall_mm.astype(int),
    "fertiliser_kg": fertiliser_kg.astype(int),
    "yield_t": yield_t,
})
df.to_csv("plots.csv", index=False)
print("rows:", len(df))
print(df.head().to_string(index=False))
PY
python make_plots.py

Soil is in the recipe but not in the file. That is deliberate: real surveys rarely measure everything that matters.

Check it worked

The script prints rows: 480 and five plots. The first, P001, is a Northern plot with 811 mm of rain, 71 kg of fertiliser and a yield of 4.24 t/ha. A file plots.csv now sits in the folder.

Step 3 · Fit a first model and read the summary

The formula API takes a model written as a string: the outcome on the left of ~, the inputs on the right. statsmodels adds an intercept for you.

Rainfall in millimetres gives a coefficient too small to read at three decimal places, so the script rescales it to units of 100 mm first. Write first_model.py:

Bash
cat > first_model.py <<'PY'
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
# Rainfall per 100 mm, so its coefficient is a readable size.
df["rain_100mm"] = df["rainfall_mm"] / 100

model = smf.ols("yield_t ~ rain_100mm + fertiliser_kg", data=df).fit()
print(model.summary(slim=True))
PY
python first_model.py

slim=True keeps the summary to the parts you need most. Read the coefficient table one column at a time:

  • coef is the estimated change in yield for one more unit of that input, holding the other inputs fixed. Each extra 100 mm of rain goes with 0.487 t/ha more maize.
  • std err is how uncertain that estimate is. Small next to the coefficient means well pinned down.
  • t and P>|t| test whether the coefficient could be zero. A p-value of 0.015 says data like this would be unusual if fertiliser had no association with yield at all. It does not say how large or important the association is.
  • [0.025 0.975] is the 95% confidence interval. For fertiliser it runs from −0.007 to −0.001: entirely negative.
  • The Intercept, 1.725, is the predicted yield with zero rain and zero fertiliser. No plot is anywhere near that, so it is a starting point for the line, not a finding.

At the top, R-squared 0.598 says the two inputs account for about 60% of the variation in yield between plots. It says nothing about whether the coefficients are right.

So the first model says fertiliser goes with lower yield. Hold that thought.

Check it worked

The summary shows 480 observations and an R-squared of 0.598. The coefficient table has three rows: Intercept 1.7250, rain_100mm 0.4870, and fertiliser_kg −0.0039 with a 95% interval of −0.007 to −0.001.

Step 4 · Pull the numbers out of the model

The printed summary is for reading. For a report or a chart you want the numbers themselves, and every figure in the summary is an attribute of the results object. Write read_numbers.py:

Bash
cat > read_numbers.py <<'PY'
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
df["rain_100mm"] = df["rainfall_mm"] / 100

model = smf.ols("yield_t ~ rain_100mm + fertiliser_kg", data=df).fit()

ci = model.conf_int()
table = pd.DataFrame({
    "coef": model.params,
    "low": ci[0],
    "high": ci[1],
    "p": model.pvalues,
})
print(table.round(3).to_string())
print(f"n = {int(model.nobs)}, R-squared = {model.rsquared:.3f}")
print(f"typical error = {model.mse_resid ** 0.5:.2f} t/ha")
PY
python read_numbers.py

params, conf_int() and pvalues are pandas objects indexed by term name, so they line up into one table. The last line is the residual standard error: the square root of the residual mean square, roughly how far a typical plot sits from the model's line. At 0.87 t/ha on yields of 3 to 7 t/ha, this model still misses by a lot.

Check it worked

The table has rows Intercept, rain_100mm and fertiliser_kg, with fertiliser at −0.004 (interval −0.007 to −0.001, p 0.015). Below it are n = 480, R-squared = 0.598 and typical error = 0.87 t/ha.

Step 5 · Add region and watch the fertiliser coefficient flip

Region is a category, not a number. Wrap it in C() and statsmodels turns it into indicator columns: one for each region except a reference level, which is the first alphabetically (Central). Each region's coefficient is then its difference from Central, at the same rainfall and fertiliser. Write add_region.py:

Bash
cat > add_region.py <<'PY'
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
df["rain_100mm"] = df["rainfall_mm"] / 100

without = smf.ols("yield_t ~ rain_100mm + fertiliser_kg", data=df).fit()
with_region = smf.ols("yield_t ~ rain_100mm + fertiliser_kg + C(region)", data=df).fit()

print(with_region.summary(slim=True).tables[1])
print()
for name, m in {"without region": without, "with region": with_region}.items():
    low, high = m.conf_int().loc["fertiliser_kg"]
    print(f"{name:<15} fertiliser {m.params['fertiliser_kg']:+.4f}"
          f"  95% CI {low:+.4f} to {high:+.4f}  R-squared {m.rsquared:.3f}")
print()
print(df.groupby("region")[["fertiliser_kg", "yield_t"]].mean().round(1).to_string())
PY
python add_region.py

The fertiliser coefficient changes sign. Without region it is −0.0039; with region it is +0.0163, close to the 0.015 in the recipe, and its interval no longer comes near zero.

The last table shows why. Northern plots use almost twice the fertiliser of Central ones and yield 2.2 t/ha less. Without region in the model, "uses a lot of fertiliser" stands in for "is in the North", and the poor Northern soil gets blamed on the fertiliser. Region here is a confounder: it is related to both the input you care about and the outcome. Once the model compares plots within the same region, the real association shows. Statisticians call the first model's error omitted-variable bias.

The region rows read as differences from Central: Northern plots yield 2.30 t/ha less at the same rainfall and fertiliser. The Coastal interval, −0.026 to 0.294, includes zero, so this data cannot tell Coastal and Central apart. To compare against a different region, name the reference level: C(region, Treatment("Northern")).

Adding region also lifted R-squared from 0.598 to 0.818, but do not read the flip as a reward for higher R-squared. A variable that explains a lot of yield can still be the wrong one to control for. Add a variable because you can explain how it relates to both the input and the outcome, as you can with region and soil here.

Check it worked

The coefficient table has C(region)[T.Coastal] at 0.1337 and C(region)[T.Northern] at −2.2980. The comparison lines show fertiliser at −0.0039 without region and +0.0163 with it, and R-squared rising from 0.598 to 0.818. The last table shows Northern plots at 93.9 kg of fertiliser and 3.6 t/ha.

Step 6 · Check the residuals

A residual is what the model got wrong for one plot: actual yield minus fitted yield. If the model's shape is right, residuals look like structureless noise around zero. Patterns in them point to what the model is missing. Write residuals.py, which draws three plots and also prints the average residual in bands of rainfall:

Bash
cat > residuals.py <<'PY'
import matplotlib
matplotlib.use("Agg")  # write files, no window needed
import matplotlib.pyplot as plt
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
df["rain_100mm"] = df["rainfall_mm"] / 100

model = smf.ols("yield_t ~ rain_100mm + fertiliser_kg + C(region)", data=df).fit()
df["fitted"] = model.fittedvalues
df["residual"] = model.resid

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
axes[0].scatter(df["fitted"], df["residual"], s=8, alpha=0.6)
axes[0].axhline(0, color="black", linewidth=1)
axes[0].set(title="Residuals against fitted", xlabel="fitted yield (t/ha)", ylabel="residual (t/ha)")
axes[1].scatter(df["rainfall_mm"], df["residual"], s=8, alpha=0.6)
axes[1].axhline(0, color="black", linewidth=1)
axes[1].set(title="Residuals against rainfall", xlabel="rainfall (mm)", ylabel="residual (t/ha)")
sm.qqplot(df["residual"], line="s", ax=axes[2])
axes[2].set_title("Normal Q-Q plot")
fig.tight_layout()
fig.savefig("residuals.png", dpi=100)
print("saved residuals.png")

bands = pd.cut(df["rainfall_mm"], [0, 500, 700, 900, 1100, 1500])
print(df.groupby(bands, observed=True)["residual"].agg(["count", "mean"]).round(2).to_string())
PY
python residuals.py

Open residuals.png and read the three panels:

  • Residuals against fitted has two clouds, one for the Northern plots and one for the rest. Both are centred on zero with a similar spread, which is what you want.
  • Residuals against rainfall bends: mostly below zero at the dry end, above it in the middle, and below again for the wettest plots. The band averages make it plain: −0.30 t/ha under 500 mm, +0.16 at 700 to 900 mm, −0.61 above 1,100 mm. A straight line for rainfall is the wrong shape.
  • Normal Q-Q plot has the points on the line, so the residuals are close to normally distributed and the confidence intervals can be trusted on that count.

A pattern against one input is the most useful thing a residual plot shows, because it tells you what to change. A funnel shape (spread growing with the fitted value) would be the other one to look for; it means the standard errors are off.

Check it worked

The script prints saved residuals.png and a table of five rainfall bands. The driest band (0 to 500 mm, 55 plots) averages −0.30, the 700 to 900 mm band (148 plots) +0.16, and the wettest (13 plots) −0.61. The image has three panels, with a visible arch in the middle one.

Step 7 · Let rainfall curve

To let yield rise and then fall with rainfall, add a squared rainfall term. Inside a formula, ** has a meaning of its own, so wrap the arithmetic in I() to make it plain maths. Write curve.py:

Bash
cat > curve.py <<'PY'
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
df["rain_100mm"] = df["rainfall_mm"] / 100

straight = smf.ols("yield_t ~ rain_100mm + fertiliser_kg + C(region)", data=df).fit()
curved = smf.ols(
    "yield_t ~ rain_100mm + I(rain_100mm ** 2) + fertiliser_kg + C(region)", data=df
).fit()

print(curved.summary(slim=True).tables[1])
print()
for name, m in {"straight": straight, "curved": curved}.items():
    print(f"{name:<9} R-squared {m.rsquared:.3f}  AIC {m.aic:.1f}")

b1 = curved.params["rain_100mm"]
b2 = curved.params["I(rain_100mm ** 2)"]
print(f"yield peaks at about {-b1 / (2 * b2) * 100:.0f} mm of rain")

bands = pd.cut(df["rainfall_mm"], [0, 500, 700, 900, 1100, 1500])
print(curved.resid.groupby(bands, observed=True).mean().round(2).to_string())
PY
python curve.py

The squared term is negative (−0.043, interval −0.053 to −0.033), which is the bend. With a curve, the two rainfall coefficients no longer mean anything on their own; the useful number is where the curve peaks, about 1,031 mm, close to the 1,000 mm in the recipe.

AIC (Akaike information criterion) compares models fitted to the same data, rewarding fit and charging for each extra term. Lower is better, and 798.1 against 860.7 is a large gap. The band averages of the residuals are now all within 0.04 of zero.

Fertiliser barely moved (0.0165 against 0.0163). That is a good sign: its estimate does not depend on getting the rainfall shape exactly right.

Check it worked

The table has a row I(rain_100mm ** 2) at −0.0430 and fertiliser_kg at 0.0165. The comparison shows the curved model with R-squared 0.841 and AIC 798.1 against 0.818 and 860.7, a peak at about 1031 mm, and residual band averages between −0.03 and 0.04.

Step 8 · Write up what the model says, and what it does not

A regression write-up should give each finding as a size with an interval, say what was held fixed, and say plainly what the data cannot show. Write write_up.py, which builds the text from the fitted model so nothing is copied by hand:

Bash
cat > write_up.py <<'PY'
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("plots.csv")
df["rain_100mm"] = df["rainfall_mm"] / 100

model = smf.ols(
    "yield_t ~ rain_100mm + I(rain_100mm ** 2) + fertiliser_kg + C(region)", data=df
).fit()
ci = model.conf_int()

fert = model.params["fertiliser_kg"] * 10
fert_low, fert_high = ci.loc["fertiliser_kg"] * 10
north = -model.params["C(region)[T.Northern]"]
north_high, north_low = -ci.loc["C(region)[T.Northern]"]
wet = int((df["rainfall_mm"] > 1100).sum())

lines = [
    "# What the plot survey says about maize yield",
    "",
    f"Ordinary least squares on {int(model.nobs)} plots; R-squared {model.rsquared:.2f}.",
    "",
    f"- Comparing plots with the same rainfall and region, each extra 10 kg/ha of"
    f" fertiliser goes with {fert:.2f} t/ha more maize (95% CI {fert_low:.2f} to {fert_high:.2f}).",
    f"- Northern plots yield {north:.2f} t/ha less than Central plots with the same"
    f" rainfall and fertiliser (95% CI {north_low:.2f} to {north_high:.2f}).",
    f"- Yield rises with rainfall and levels off near 1,000 mm. Only {wet} plots had"
    " more than 1,100 mm, so the shape above that is uncertain.",
    "",
    "These are associations in survey data, not the effect of changing fertiliser."
    " Farmers chose how much to use, and differences the survey did not measure,"
    " such as soil, can still bias every figure here.",
]
text = "\n".join(lines) + "\n"
with open("report.md", "w", encoding="utf-8") as f:
    f.write(text)
print(text, end="")
PY
python write_up.py

Notice the wording. "Goes with" and "comparing plots with the same rainfall and region" describe what the model measured. "Fertiliser raises yield by 0.16 t/ha" would be a causal claim, and survey data alone cannot support it: you saw one hidden variable reverse a coefficient, and there could be others the survey never recorded. A field trial that assigns fertiliser rates at random is what turns an association into an effect.

The 0.16 t/ha is close to the 0.15 in the recipe, but only because this data was built with no other hidden differences between plots. With real data you do not get to check.

When you finish, delete the practice folder with rm -r ~/maize-regression-demo. Check the path first: it removes everything inside it.

Check it worked

report.md exists. It opens with Ordinary least squares on 480 plots; R-squared 0.84., then three bullets: fertiliser at 0.16 t/ha per 10 kg (95% CI 0.14 to 0.19), Northern plots 2.20 t/ha lower (95% CI 2.02 to 2.38), and the note that only 13 plots had more than 1,100 mm. It ends by saying the figures are associations, not effects.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.