Simple Linear Regression
Correlation tells you how strongly two variables are linearly related. Simple linear regression goes further: it finds the straight line that best describes the relationship, so you can predict one variable (the response y) from another (the explanatory variable or predictor x).
The model
ŷ = b₀ + b₁ × xb₁is the slope: how muchŷchanges, on average, whenxincreases by one unit.b₀is the intercept: the predictedywhenx = 0(sometimes meaningless ifx = 0is outside the data).ŷ("y-hat") is the predicted value. The differencey − ŷis called the residual.
Least squares
The "best" line minimises the sum of squared residuals, Σ(y − ŷ)². The solution has a simple closed form:
b₁ = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)² (equivalently r × s_y / s_x)
b₀ = ȳ − b₁ × x̄An ice-cream kiosk recorded the day's maximum temperature and the number of cones sold on 12 days:
import statistics
temp = [18, 21, 24, 19, 27, 30, 25, 22, 32, 28, 20, 26]
cones = [112, 140, 168, 130, 205, 230, 182, 151, 251, 214, 128, 190]
mx, my = statistics.mean(temp), statistics.mean(cones)
sxy = sum((x - mx) * (y - my) for x, y in zip(temp, cones))
sxx = sum((x - mx) ** 2 for x in temp)
b1 = sxy / sxx
b0 = my - b1 * mx
print(f"by hand: cones = {b0:.2f} + {b1:.3f} × temp")
fit = statistics.linear_regression(temp, cones)
print(f"statistics: cones = {fit.intercept:.2f} + {fit.slope:.3f} × temp")by hand: cones = -65.80 + 9.899 × temp
statistics: cones = -65.80 + 9.899 × temp
Interpretation: each extra degree Celsius goes with about 10 more cones sold per day, on average. The intercept (about −66 cones at 0 °C) is not meaningful: no day in the data was anywhere near 0 °C, and you can't sell negative cones.
Fitting and plotting with SciPy
scipy.stats.linregress returns the slope, intercept, r, the p-value for H₀: slope = 0 and the slope's standard error:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
temp = np.array([18, 21, 24, 19, 27, 30, 25, 22, 32, 28, 20, 26])
cones = np.array([112, 140, 168, 130, 205, 230, 182, 151, 251, 214, 128, 190])
res = stats.linregress(temp, cones)
print(f"slope = {res.slope:.3f} (SE {res.stderr:.3f}), intercept = {res.intercept:.2f}")
print(f"r = {res.rvalue:.4f}, R² = {res.rvalue**2:.4f}, p-value = {res.pvalue:.2e}")
fig, ax = plt.subplots(figsize=(5.5, 3.5))
ax.scatter(temp, cones, color="#2a78d6", s=40)
xs = np.linspace(17, 33, 2)
ax.plot(xs, res.intercept + res.slope * xs, color="#eb6834", linewidth=2)
ax.set_xlabel("max temperature (°C)")
ax.set_ylabel("cones sold")
plt.tight_layout()
plt.show()slope = 9.899 (SE 0.234), intercept = -65.80
r = 0.9972, R² = 0.9944, p-value = 1.32e-12
R²: how much is explained?
The coefficient of determination R² is the share of the variation in y that the line explains:
R² = 1 − Σ(y − ŷ)² / Σ(y − ȳ)²For simple linear regression, R² = r². Here more than 99% of the day-to-day variation in sales is explained by temperature (R² = 0.9944). The small remainder comes from everything else (weekday, events, chance). Real data is rarely this tidy; an R² of 0.5 can already be useful.
Predictions
from scipy import stats
temp = [18, 21, 24, 19, 27, 30, 25, 22, 32, 28, 20, 26]
cones = [112, 140, 168, 130, 205, 230, 182, 151, 251, 214, 128, 190]
res = stats.linregress(temp, cones)
for t in [23, 29, 40]:
print(f"{t} °C -> predicted {res.intercept + res.slope * t:.0f} cones")23 °C -> predicted 162 cones
29 °C -> predicted 221 cones
40 °C -> predicted 330 cones
The predictions for 23 °C and 29 °C are interpolations inside the observed range (18–32 °C) and are trustworthy. 40 °C is an extrapolation: the line may not hold there (perhaps people stay indoors in extreme heat). Avoid extrapolating far beyond your data.
Checking the residuals
Regression assumes the relationship is linear and the residuals are random noise with constant spread. A residual plot (residuals against x) should look like a shapeless band around 0:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
temp = np.array([18, 21, 24, 19, 27, 30, 25, 22, 32, 28, 20, 26])
cones = np.array([112, 140, 168, 130, 205, 230, 182, 151, 251, 214, 128, 190])
res = stats.linregress(temp, cones)
residuals = cones - (res.intercept + res.slope * temp)
fig, ax = plt.subplots(figsize=(5.5, 3))
ax.axhline(0, color="#52514e", linewidth=1)
ax.scatter(temp, residuals, color="#2a78d6", s=40)
ax.set_xlabel("max temperature (°C)")
ax.set_ylabel("residual (cones)")
plt.tight_layout()
plt.show()
print("residuals:", np.round(residuals, 1).tolist())
print("residuals sum to zero:", bool(np.isclose(residuals.sum(), 0)))residuals: [-0.4, -2.1, -3.8, 7.7, 3.5, -1.2, 0.3, -1.0, 0.0, 2.6, -4.2, -1.6]
residuals sum to zero: True
No pattern is visible, so the straight-line model is adequate. A curved pattern would suggest a non-linear relationship; a funnel shape would suggest the spread grows with x.
Regression with statsmodels
For a full statistical report (confidence intervals for the coefficients and more) use statsmodels:
import numpy as np
import statsmodels.api as sm
temp = np.array([18, 21, 24, 19, 27, 30, 25, 22, 32, 28, 20, 26])
cones = np.array([112, 140, 168, 130, 205, 230, 182, 151, 251, 214, 128, 190])
model = sm.OLS(cones, sm.add_constant(temp)).fit()
print(model.params.round(3))
print(model.conf_int(alpha=0.05).round(3))
print(f"R² = {model.rsquared:.4f}")[-65.802 9.899]
[[-78.699 -52.905]
[ 9.377 10.421]]
R² = 0.9944
The first row is the intercept, the second the slope. With 95% confidence, each extra degree adds between about 9.4 and 10.4 cones.
Test yourself
A regression of weight (kg) on height (cm) gives ŷ = −90 + 0.9x. How do you interpret 0.9?
- 90% of weight is explained by height
- Each extra cm of height goes with about 0.9 kg more weight on average
- The correlation is 0.9
- Weight at 0 cm is 0.9 kg
A simple linear regression has r = −0.6. What is R²?
- −0.36
- 0.36
- 0.6
- −0.6
Why is it risky to predict ice-cream sales at 40 °C from data collected between 18 and 32 °C?
- The slope would change sign
- It is extrapolation: the linear pattern may not hold outside the observed range
- R² becomes negative
- The intercept is not significant