Linear regression is the gateway model — most ML courses, every analyst's first model, the foundation of A/B testing analysis, price modelling, demand forecasting, and the "predicted next month sales" sheet your CFO sends you. Worth learning properly.
What is regression?
Regression is the family of methods that estimate the relationship between a dependent variable (y, what you want to predict) and one or more independent variables (x, the inputs).
"Linear" means: we assume the relationship is well-approximated by a straight line — y = β₀ + β₁x + ε.
Simple linear regression
import numpy as npimport matplotlib.pyplot as plt# Marketing spend (x) vs revenue (y) for 10 weeksx = np.array([12, 18, 22, 30, 35, 40, 45, 55, 60, 70])y = np.array([85, 95, 110, 130, 140, 145, 160, 180, 195, 220])# Fit the line: y = β0 + β1 * xslope, intercept = np.polyfit(x, y, 1)print(f"y = {intercept:.1f} + {slope:.2f} * x")# y = 60.4 + 2.27 * x# Predict revenue at ₹50k spendpredicted = intercept + slope * 50print(f"At ₹50k spend → ₹{predicted:.0f}k revenue")# At ₹50k spend → ₹174k revenue
Interpretation:
- β₁ = 2.27 — for every ₹1k more spend, revenue rises by ₹2.27k.
- β₀ = 60.4 — predicted revenue at zero spend (intercept). Often not meaningful, just an anchor.
Multiple regression
More than one input. y = β₀ + β₁x₁ + β₂x₂ + … + βₙxₙ + ε. Each coefficient now means "all else equal":
# House prices: depend on size (sqft) AND number of bedrooms# Coefficients you might fit: β₁ = 1500, β₂ = 25000# Interpretation:# - All else equal, every extra sqft adds ₹1,500 to the price# - All else equal, every extra bedroom adds ₹25,000# "All else equal" is doing a lot of work — beware of correlated inputs!
R², MAE, RMSE
| Metric | Formula | Reading |
|---|---|---|
| R² | 1 − SS_res / SS_tot | 0–1; share of variance the model explains |
| MAE | mean(|y − ŷ|) | avg error in same units as y |
| MSE | mean((y − ŷ)²) | penalises big errors |
| RMSE | √MSE | same units as y; comparable to mean |
The four assumptions
Linear regression has four classical assumptions. Violating them doesn't crash the model — it makes the coefficients and standard errors unreliable.
- Linearity: y is a linear function of x. Check with a scatter plot of residuals vs predictions — should look like a random cloud.
- Independence: observations are independent of each other. Time series usually violate this.
- Homoscedasticity: residual variance is constant across predictions. The "fan shape" in residual plots is the telltale violation.
- Normality of residuals: for hypothesis tests on coefficients. Less critical for prediction.
In Python with scikit-learn
from sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import r2_score, mean_absolute_errorimport numpy as np# Simulated: house price ~ 1500 * sqft + 25000 * bedrooms + noisenp.random.seed(0)n = 200sqft = np.random.normal(1200, 400, n)bedrooms = np.random.choice([1, 2, 3, 4], n)noise = np.random.normal(0, 50_000, n)price = 1500 * sqft + 25_000 * bedrooms + noiseX = np.column_stack([sqft, bedrooms])X_train, X_test, y_train, y_test = train_test_split(X, price, test_size=0.2, random_state=0)model = LinearRegression().fit(X_train, y_train)print(f"Coefficients: {model.coef_}") # ~[1500, 25000]print(f"Intercept: {model.intercept_}")preds = model.predict(X_test)print(f"R² (test): {r2_score(y_test, preds):.3f}")print(f"MAE (test): {mean_absolute_error(y_test, preds):,.0f}")
Key takeaways
- 01Linear regression assumes y ≈ β₀ + β₁x — a straight-line relationship.
- 02In multiple regression, each coefficient is "effect of x_i, all else equal".
- 03R² is variance explained on this data; always validate on held-out data.
- 04Watch for the four assumptions — violations make coefficients & p-values unreliable.
- 05sklearn.LinearRegression fits, predicts, and exposes coefs in 4 lines.
