← Homepage

The Practitioner's Guide to Regression

October 18, 2026

Author: Daniel Jordan Viray

Regression is the first real model most of us learn — and the one that quietly shows up everywhere else. This is the working cheat sheet: fit an OLS model in Python and predict with it, bend variables until the relationship is straight (and bend the answer back to interpret it), judge fit with the right metric, read the three diagnostic plots, tell an outlier from a leverage point from an influential point — then graduate to logistic regression when the answer is yes/no, and grade it with a confusion matrix.

Contents

Part I — Linear regression

Part II — Logistic regression

Part I — Linear regression

Fitting OLS in Python: the 60-second version

A linear regression says: outcome = intercept + slope × predictor + …, and ordinary least squares (OLS) picks the numbers that make the squared prediction errors as small as possible. The running example: predicting the cost of a hospital stay for 120 patients from age and length of stay (numeric) and admission type (categorical).

The fitted model, in words: every extra year of age adds about $51 to the bill; every extra day adds about $954. Admission type enters as comparisons against the reference category (Elective, whose effect is folded into the intercept): an otherwise identical Emergency patient costs about $3,055 more, an Urgent patient about $1,242 more. Model R² = 0.72 — it explains about 0.72 of the variation in cost, as a proportion. And the point of the exercise — a prediction for a new patient, 68 years old, Emergency admission, 5-day stay: $15,247.

Data structure + Python code

Data: one row per patient; the outcome in one column, predictors in the others. Categorical predictors go in as text — C() in the formula tells statsmodels to dummy-code them against a reference level. Predicting needs a small DataFrame with the same columns.

import pandas as pd
from statsmodels.formula.api import ols

# hosp: 120 rows; columns cost, age, los_days, admission (Elective/Emergency/Urgent)
fit = ols("cost ~ age + los_days + C(admission)", data=hosp).fit()
print(fit.summary())        # coefficients, R-squared = 0.72, p-values

new_patient = pd.DataFrame({"age": [68], "los_days": [5], "admission": ["Emergency"]})
fit.predict(new_patient)    # -> $15,247

Transformations: making it linear, and back-transforming to interpret

OLS fits straight lines in the variables you give it — nothing says you must hand it the raw variables. When a relationship bends, transform a variable until the bend straightens (in practice: add a transformed column to your data, and put that column in the formula), fit the line there, then back-transform the answer to say it in original units. Example: drug dose vs symptom reduction, where each doubling of the dose buys roughly the same benefit (diminishing returns). Try it:

How you know which one you need: look at the scatter (and later, at the residual plot). A bend that flattens out is asking you to compress the big end of a variable — log does it strongly, square root gently. A bend that accelerates upward asks for the opposite — stretch it, with a square. And a fan-shaped residual plot (errors growing with the prediction) is the same story told about the outcome: compress y.

TransformationWhat the raw data looks like — reach for it when…What it doesReading the result
log(y)The scatter takes off as x grows — the outcomes fan out into a long upper tail of very large values. Costs are the textbook case. Pulls in a long right tail; effects become multiplicative A one-unit rise in x changes y by about β×100% (exactly: multiplies y by eβ)
sqrt(y)The scatter rises with a spread that grows moderately — counts-like data. Often applied to both sides at once when the predictor is a skewed count too (the course's advertising example square-roots both spend and impressions). A gentler log(y) Square the predictions to get back to original units
1/y (inverse)The scatter crashes: enormous values at small x, collapsing toward zero. The outcome is usually a time or a rate underneath. The strongest tail-pull of the three Signs flip — safest to back-transform predictions (take the reciprocal) and read those
log(x)The scatter rises steeply, then flattens: each extra unit of x buys less than the one before — diminishing returns (dose, spending, days on a therapy). Compresses big x values A 1% rise in x moves y by about β/100; a doubling of x moves y by about 0.69×β
sqrt(x)The same flattening, but gentler. Milder compression of x Slope is per unit of sqrt(x) — back-transform examples rather than quoting the slope
x² (fit x and x²)The scatter curves like a smile (or a frown): the middle is the extreme — risk lowest at middling BMI is the classic shape. Also the geometry of areas. Lets one predictor bend once: a U or an upside-down U No single slope exists; plot the curve and quote values off it
x³ (cubed)The scatter hugs the floor, then takes off like a hockey stick — the geometry of volumes (the course's perch grow in mass at roughly length cubed, and cubing the length straightens the relationship completely). Sharp acceleration As with x²: plot, don't quote a single slope
Back-transformation, the part everyone forgets: a model fitted to log(cost) predicts log-dollars. Exponentiate the prediction to get dollars back. Two consequences: the coefficient reads as a percentage change rather than a dollar change, and the exponentiated prediction lands near the typical (median) patient rather than the mean — a feature for skewed costs, as long as you know it's happening.

Fit metrics: from residuals to a grade, step by step

Every metric in this section is built from one ingredient, in a few mechanical steps. Walk the chain once and the family stops being a list to memorize — including which ones are just rescalings of each other.

Step 1 — residuals. For every patient the model makes a prediction, and the residual is what it missed by: actual − predicted. Three of the cost model's 120 residuals:

Actual costPredictedResidual (actual − predicted)Squared error
Patient 1$12,414$12,343+$715,026
Patient 2$15,637$15,945−$30895,149
Patient 3$15,275$12,429+$2,8468,097,086

Step 2 — square them. Squaring does two jobs. It makes every miss positive (a $2,000 overestimate and a $2,000 underestimate are both just wrong by $2,000). And it punishes big misses disproportionately: one $4,000 miss counts as much as four $2,000 misses. That second property is a choice — one sibling below exists precisely for people who don't want it.

Step 3 — add them up: SSE. The sum of squared errors. For the cost model, SSE ≈ 295 million — in squared dollars, a unit nobody can think in. That's the point: SSE is an ingredient, not a grade. Everything below is a way of turning it into a grade.

Step 4 — average it, then unsquare it: RMSE. Divide SSE by the number of patients (120) and you get the mean squared error (MSE = 2,455,673 squared-dollars). Take the square root and the units come home: RMSE = $1,567 — "our typical prediction is off by about $1,600." This is the number most people picture when they say a model is accurate to within about X.

Step 5 — the fairness tweak: RSE. RMSE divides by n. The residual standard error divides by n − the number of fitted coefficients (120 − 5 here) instead, so every predictor the model uses costs it a little credit — stuffing in junk predictors can't fake a better score. RSE = $1,601, slightly larger than RMSE, exactly as it should be. It's the same "typical error," computed the way regression output reports it (and the one-line shortcut is np.sqrt(fit.mse_resid)).

The siblings — same residuals, different choices along the way:

MetricThe changeCost modelUse it when
MAESkip step 2: average the absolute residuals instead of squaring$1,226 A few huge misses shouldn't dominate the verdict. Diagnostic pairing: if RMSE is much bigger than MAE, a handful of very large misses are running the show.
MAPEDivide each residual by its actual value first, average, as a %10% The audience thinks in percentages, or you're comparing across outcomes with different scales. Breaks down when actuals sit near zero — a $50 error on a $60 bill is 83%.
R² (coefficient of determination)Compare SSE to the outcome's total variation: 1 − SSE/SST0.72 "How much of the variation did we explain?" — the communication number. Adjusted R² (0.71) applies RSE's per-coefficient charge; use it when comparing models with different numbers of predictors.

What gets used in practice: day to day, evaluation usually means RMSE (or MAE) on data the model never trained on — a held-out test set — because in-sample numbers flatter the model. R² is the number you say out loud ("we explain about 0.72 of the variation in cost," as a proportion). RSE is what you read in regression output and use to compare models fitted to the same data. MAPE appears when a business audience wants a percentage and the outcome stays safely away from zero.

Python code: the whole family from one fit
import numpy as np

resid = fit.resid                       # actual - predicted, one per patient
n = len(resid)
k = 4                                   # slopes: age, los_days, Emergency, Urgent
sse = float((resid ** 2).sum())
rmse = np.sqrt(sse / n)                 # $1,567
rse  = np.sqrt(sse / (n - k - 1))       # $1,601  (shortcut: np.sqrt(fit.mse_resid))
mae  = np.abs(resid).mean()             # $1,226
mape = (np.abs(resid) / hosp["cost"]).mean() * 100   # 10%
print(fit.rsquared, fit.rsquared_adj)   # 0.72, 0.71

Diagnostic plots: what you're looking for, and why

Three standard plots, all computed from the cost model's residuals. A good fit's residuals are roughly normally distributed with mean zero — each plot below audits one part of that sentence. This model is well-behaved, so these show what "fine" looks like — each caption names the trouble pattern it's built to catch.

Think of every prediction as an arrow shot at a bullseye. If the misses spray randomly around the target — no pattern to them — your aim is as good as it gets and what's left is noise; no adjustment fixes noise. The dangerous case is missing non-randomly: always low on one side, always high on the other. A repeatable miss is a fixable miss — it means the model is systematically leaving something out. The three plots below are three ways of checking whether your misses are random.

Residuals vs fitted. The residuals should form a formless cloud around zero at every fitted level. A curve in the cloud means a relationship you didn't model — a bend asking for a transformation or an extra term. A funnel (spread widening left to right) means your errors grow with the size of the prediction.

6000800010000120001400016000180002000022000Fitted cost ($)−3000−2000−100001000200030004000Residual ($)Residuals vs fitted

Normal Q-Q plot. Standardized residuals plotted against where they'd sit if they were perfectly normal. On the diagonal line = normal enough. This matters for confidence and prediction intervals and for small samples; big samples and point predictions forgive a lot. Tails that peel away at both ends mean heavier tails than normal — usually a few extreme patients. Said plainly: a good model's errors are mostly ordinary-sized — missing by a typical amount, in a random direction, most of the time. Points peeling away at the ends mean too many of your errors are extreme compared to that picture, and an error pattern is something a model can be adjusted for.

−2−1012Theoretical Quantiles−2−1012Sample QuantilesNormal Q-Q (standardized residuals)

Scale-location plot. In plain terms: are you missing by about the same amount all the way along the axis, or do the misses get bigger at, say, the high end? If the misses grow somewhere, that somewhere is where the model can be changed. Technically, it plots the square root of the absolute standardized residuals against fitted values — the funnel detector with the direction stripped out, so spread is all you see. A flat band means constant error variance (homoscedasticity). A rising trend is the funnel again: bigger predictions, bigger misses — often the cue for log(y).

6000800010000120001400016000180002000022000Fitted cost ($)0.20.40.60.81.01.21.41.6sqrt(|standardized residual|)Scale-location

Outliers, leverage, and influence: three different accusations

These three words get used interchangeably and mean different things. A small clinic dataset (age → cost of stay, 30 patients) with one of each planted in it:

2030405060708090100Age02000400060008000100001200014000Cost ($)outlier(big residual)leverage only(on the trend)influential(pulls the line)Bubble size = Cook's distance

Outlier — a point that doesn't fit the pattern: a big residual. The 52-year-old whose stay cost $12,500 against a predicted ~$6,100 (standardized residual 5.9). Being an outlier is about y disagreeing with the model.

Leverage — a point whose x is unusual: far from the crowd horizontally, so the line has to pass near it, like the long end of a lever. The 96-year-old has the most leverage here (hat value 0.21, vs a typical ~0.07). But he sits right on the trend, so he barely moves anything — leverage is only potential influence.

Influence — leverage × disagreement: a point that actually bends the fit. The 94-year-old with a $2,600 stay has extreme age and sits far off the line; delete him and the slope visibly changes. Cook's distance measures exactly this — one number per point: how much the whole fit would move if that point were removed. Rules of thumb: look closer above 4/n (here 0.13); above 1 (his is 1.33), definitely investigate. Investigating means: check for a data error first, then report the fit with and without the point. It does not mean silently deleting inconvenient patients.

The classic teaching example of all three ideas is a fish dataset, where the single most influential observation is one very short roach — leverage 0.31, Cook's distance 1.07. The smallest fish in the data has the biggest pull on the line.

Python code: hat values and Cook's distance
from statsmodels.formula.api import ols

fit2 = ols("cost ~ age", data=clinic).fit()
summary = fit2.get_influence().summary_frame()
hats = summary["hat_diag"]      # leverage, one value per patient
cooks = summary["cooks_d"]      # Cook's distance, one value per patient
# flag for a closer look: cooks > 4 / len(clinic)

Planted results: the influential patient's Cook's distance is 1.33 — the largest in the dataset. The on-trend 96-year-old's is 0.08 despite his leverage.

Part II — Logistic regression

Read this first: logistic regression [a generalized linear model] is linear regression's sibling, not a different species. If the machinery above — fit a line, read coefficients, grade the fit — is new to you, work through Part I first; everything here builds on it.

Why logistic? The failure of the straight line

New problem: predict whether a patient is readmitted within 30 days (yes/no) from a risk score, for 240 patients (42% were actually readmitted). Fit a straight line to a 0/1 outcome anyway and two things break. The line escapes: it predicts probabilities of 1.2 and −0.1, which don't exist. And it insists the effect of 10 extra risk points is identical everywhere — but probability is squeezed into [0, 1], so real risk has to bend: slow at the bottom, fast in the middle, slow at the top.

020406080100Risk score−0.20.00.20.40.60.81.01.2Readmitted (0/1)Same data, two fitslinear fit (escapes 0-1)logistic fit

The logistic fix is one move: don't put the line on the probability — put it on the log-odds, then squash the result back through the S-curve so every prediction lands inside [0, 1]. The fitted line here is log-odds = -2.62 + 0.046 × risk score. What log-odds, odds, and probability each mean — and why you'd ever want all three — is the next section.

Data structure + Python code

Data: one row per patient; the outcome is 0/1, the predictor is a number. Same formula shape as OLS — logit instead of ols.

from statsmodels.formula.api import logit

# rd: 240 rows; columns score (0-100), readmit (0/1)
lfit = logit("readmit ~ score", data=rd).fit()
print(lfit.summary())       # log-odds = -2.62 + 0.046 * score

One prediction, five languages

Five patients from the readmission model. Every row is the same prediction said five ways — plus what actually happened:

Risk score (x)Actual outcome (y)ProbabilityPredicted responseOddsLog-odds
2000.1500.18-1.70
4010.3100.46-0.78
5500.4800.92-0.09
7010.6511.830.60
8510.7813.651.29

Why each column earns its place:

x — the input. What you know about the patient before deciding anything.

y — what actually happened. The truth you grade against. Note the patient with probability 0.35 who was readmitted: a probability is not a promise, and a "wrong" prediction at 0.35 isn't necessarily a model failure.

Probability — the human language. "About a 1-in-3 chance of coming back." This is the only column you'd say out loud to a clinician, an executive, or a patient.

Predicted response — probability forced into an action. A threshold (here the default 0.5) turns "how likely" into "flag or don't flag." The threshold is not part of the model — it's a decision about which mistake is cheaper, and the next section is about choosing it.

Odds = probability / (1 − probability) — the betting language. Effects multiply on this scale, which is why papers report odds ratios: in this model, every +10 risk points multiplies the odds of readmission by 1.6×, wherever you start from. (Careful: an odds ratio is not a probability ratio — at high base rates they drift apart.)

Log-odds — the model's native language. This is the straight line actually being fitted (-2.62 + 0.046 × score): add a predictor, add a term; effects are additive here. Nobody quotes log-odds to a human — but every other column is a conversion of it, so it's the one to compute in.

The same trade-offs, at a glance:

ScaleEasy to interpret?Changes easy to read?Precise?
ProbabilityYesNo — the same slope means different probability jumps at different starting pointsYes
Predicted responseEasiest of allYesNo — throws away all the gradation
OddsYes, with practiceEffects multiply rather than addYes
Log-oddsNoYes — effects simply addYes
Python code: getting all five from the fit
import numpy as np

patients = pd.DataFrame({"score": [20, 40, 55, 70, 85]})   # the five patients in the table
prob = lfit.predict(patients)                    # probabilities, straight from the fit
log_odds = np.log(prob / (1 - prob))             # invert the squash: back to the line
odds = prob / (1 - prob)
pred = (prob >= 0.5).astype(int)                 # the 0.5 threshold, made explicit (= np.round(prob))

predict() hands back probabilities. The log-odds is one algebra step away — log(p / (1 − p)) — because that formula and the S-curve are exact inverses.

The confusion matrix: where every metric comes from

Force the readmission model's probabilities into yes/no calls and grade them against what actually happened. Four boxes result. The layout matches statsmodels' pred_table(): rows are what actually happened, columns are what the model predicted. Every classification metric you've ever seen is just arithmetic on these four numbers — drag the threshold and watch them move:

Predicted: stayed home
Predicted: flagged
Actually stayed home
True negatives–not flagged, and stayed home
False positives–flagged, but stayed home
Actually readmitted
False negatives–missed: readmitted, never flagged
True positives–flagged, and truly readmitted

The five standard metrics, in words (tap one above to see which boxes it uses):

Accuracy = (TP + TN) / everyone — "overall, how often are we right?" At the 0.50 threshold: 74%. Handle with care: with a rare outcome, a model that flags nobody also scores high accuracy while being useless.

Sensitivity (recall) = TP / (TP + FN) — of the patients who truly were readmitted, how many did we flag? At 0.50: 66%. This is the "don't miss cases" metric.

Specificity = TN / (TN + FP) — of the patients who truly stayed home, how many did we leave alone? At 0.50: 79%.

Precision = TP / (TP + FP) — of the patients we flagged, how many truly were readmitted? At 0.50: 70%. This is the "don't cry wolf" metric — it prices your follow-up team's time.

F1 = the harmonic mean of precision and sensitivity — one number for when both kinds of mistake matter and you refuse to pick a favorite. At 0.50: 68%.

The threshold is a policy decision, not a statistic. Drag it down and you catch more readmissions (sensitivity climbs) but flag more healthy patients (precision falls, follow-up costs climb). Drag it up and the reverse. There is no mathematically best threshold — only the one that matches what a missed readmission costs you versus what a false alarm costs you.
Python code: the matrix at threshold 0.50
conf_matrix = lfit.pred_table()        # rows = actual, columns = predicted; cutoff 0.5
tn = conf_matrix[0, 0]                 # 110
fp = conf_matrix[0, 1]                 # 29
fn = conf_matrix[1, 0]                 # 34
tp = conf_matrix[1, 1]                 # 67

Same four numbers the interactive shows at 0.50 — computed here in Python, there in your browser, from the same probabilities.

Prove it: every coefficient, metric, plot, and table entry on this page was computed by the build script from the toy datasets described, with the decisions asserted in code before the page was written — including the planted outlier, leverage point, and influential point in the clinic data, whose Cook's distances had to rank exactly as the text claims.

Part of the Applied Data Science Lab. Companion: The Practitioner's Guide to Statistical Tests — the hypothesis-testing method bank.