Skip to main content

16  Regression, classification and prediction

We end by bringing probability and statistics into predictive modeling. Regression estimates a conditional mean of a numerical outcome; probabilistic classification estimates conditional probabilities for a categorical outcome. In both cases the model, estimation criterion and evaluation design are mathematical choices. A low training error is not evidence that every one of those choices is appropriate.

16.1 Linear regression as a conditional model

Suppose \(x_i\) is a known numerical predictor at observation \(i\) and

\[ Y_i=\beta_0+\beta_1 x_i+\epsilon_i, \qquad E[\epsilon_i\mid x_i]=0. \]

The conditional population mean at \(x\) is \(\beta_0+\beta_1x\). Assume independent errors with common variance \(\sigma^2\). Normal errors will be an additional assumption for exact likelihood and interval results, not for the least-squares calculation itself. We treat predictors as fixed, or condition on the entire design when the conditional assumptions hold.

Ordinary least squares chooses parameters minimizing

\[ RSS(b_0,b_1)=\sum_i(y_i-b_0-b_1x_i)^2. \]

Differentiate with respect to \(b_0\):

\[ \sum_i(y_i-b_0-b_1x_i)=0, \quad\text{so }b_0=\bar y-b_1\bar x. \]

Substitution reduces the objective to \(\sum_i[(y_i-\bar y)-b_1(x_i-\bar x)]^2\). Differentiate with respect to \(b_1\) to obtain

\[ \boxed{\widehat\beta_1=\frac{S_{xy}}{S_{xx}}}, \qquad \widehat\beta_0=\bar y-\widehat\beta_1\bar x, \]

where \(S_{xy}=\sum_i(x_i-\bar x)(y_i-\bar y)\) and \(S_{xx}=\sum_i(x_i-\bar x)^2\). When \(S_{xx}>0\) the reduced objective is strictly convex, so these are the unique minimizing coefficients. If all \(x_i\) are equal, the slope and intercept cannot be separately identified.

16.1.1 Example: a small sensor calibration

Suppose \(x=(1,2,3,4)\) represents four controlled input levels and \(y=(2,4,5,9)\) the corresponding readings. Then \(\bar x=2.5\), \(\bar y=5\), and

\[ S_{xx}=5,\qquad S_{xy}=11. \]

The fitted slope is \(2.2\) and intercept \(-0.5\), giving predictions \((1.7,3.9,6.1,8.3)\) and residuals \((.3,.1,-1.1,.7)\). The residuals sum to zero and their weighted sum against \(x\) is zero, as required by the two stationary equations.

Scatterplot with a rising least-squares line, highlighted residuals and nested mean and prediction uncertainty bands.
Figure 16.1: A fitted line, noisy observations and residuals. The band for the conditional mean is narrower than the interval for a future observation.

16.2 Matrix least squares

For \(n\) observations and \(p\) coefficients (including an intercept if desired), let the design matrix \(X\) have \(n\) rows and \(p\) columns, and write

\[ Y=X\beta+\epsilon,\qquad E[\epsilon\mid X]=0, \quad \operatorname{Cov}(\epsilon\mid X)=\sigma^2 I. \]

The gradient of \((y-Xb)^\top(y-Xb)\) is \(-2X^\top(y-Xb)\). Setting it to zero produces the normal equations \(X^\top X\widehat\beta=X^\top y\). If the columns are linearly independent, then for every nonzero \(u\), \(u^\top X^\top Xu=\|Xu\|^2>0\). Thus the Hessian is positive definite and the unique global solution is

\[ \widehat\beta=(X^\top X)^{-1}X^\top Y. \]

Since \(\widehat\beta=\beta+(X^\top X)^{-1}X^\top\epsilon\),

\[ E[\widehat\beta\mid X]=\beta,\qquad \operatorname{Cov}(\widehat\beta\mid X)=\sigma^2(X^\top X)^{-1}. \]

The second identity follows by applying the affine covariance formula from Chapter 6. Near-collinear columns make \(X^\top X\) ill-conditioned and can inflate coefficient uncertainty. In computation use a QR- or SVD-based least-squares solver instead of explicitly inverting the normal equations.

A slope describes the change in modeled conditional mean as a predictor changes, holding other included predictors fixed. Association in observational data does not establish a causal effect without additional design or identification assumptions.

16.3 Gaussian likelihood and inference

If \(\epsilon\mid X\sim N_n(0,\sigma^2 I_n)\), the conditional log likelihood is

\[ \ell(\beta,\sigma^2)=-\frac n2\log(2\pi\sigma^2) -\frac{RSS(\beta)}{2\sigma^2}. \]

For any positive \(\sigma^2\) it is maximized by least squares. Thus least squares is maximum likelihood for the Gaussian-error model. The exact conditional distribution of \(\widehat\beta\) is normal with the preceding mean and covariance.

Let \(H=X(X^\top X)^{-1}X^\top\) be the orthogonal projection onto the column space of \(X\). Residuals equal \((I-H)Y=(I-H)\epsilon\). The matrix \(I-H\) is a symmetric idempotent projection of rank \(n-p\). Rotating to an orthonormal basis adapted to these two orthogonal subspaces, as in Chapter 10, gives

\[ \frac{RSS(\widehat\beta)}{\sigma^2}\sim\chi^2_{n-p}, \qquad RSS(\widehat\beta)\ \perp\ \widehat\beta. \]

For \(n>p\) the residual variance estimate \(s^2=RSS/(n-p)\) is unbiased, and for each coefficient \(j\),

\[ \frac{\widehat\beta_j-\beta_j} {s\sqrt{[(X^\top X)^{-1}]_{jj}}}\sim t_{n-p}. \]

Thus an exact conditional confidence interval is \(\widehat\beta_j\pm t_{n-p,1-\alpha/2}\) times the estimated standard error. Heteroscedastic or dependent errors require different variance estimates; checking residuals may reveal problems, but residual plots alone cannot establish all assumptions.

For a new design row \(x_0^\top\), the fitted mean \(\widehat m=x_0^\top\widehat\beta\) has variance \(\sigma^2 h_0\), where \(h_0=x_0^\top(X^\top X)^{-1}x_0\). A future independent response \(Y_0=x_0^\top\beta+\epsilon_0\) has prediction error variance \(\sigma^2(1+h_0)\), because the future noise and coefficient estimate are independent. Normal theory gives the corresponding intervals

\[ \begin{aligned} \text{Mean: }&\widehat m\pm t_{n-p,1-\alpha/2}\,s\sqrt{h_0},\\ \text{Future observation: }&\widehat m\pm t_{n-p,1-\alpha/2}\,s\sqrt{1+h_0}. \end{aligned} \]

The prediction interval incorporates irreducible individual noise. Extrapolation far beyond the observed design can make \(h_0\) large and can also invalidate the assumed linear relationship.

import numpy as np
from scipy import stats

rng = np.random.default_rng(1600)
x = np.linspace(0,5,30)
y = 1+2*x+rng.normal(0,1,x.size)
X = np.column_stack([np.ones(x.size),x])
b,_,_,_ = np.linalg.lstsq(X,y,rcond=None)
resid = y-X@b
df = len(y)-X.shape[1]
s2 = resid@resid/df
# Solve instead of explicitly forming the matrix inverse.
cov = s2*np.linalg.solve(X.T@X,np.eye(X.shape[1]))
se = np.sqrt(np.diag(cov))
c = stats.t.ppf(.975,df)
print("Coefficients:",b)
print("95% coefficient intervals:",np.column_stack([b-c*se,b+c*se]))

16.4 Logistic regression

For binary outcomes \(Y_i\in\{0,1\}\), suppose

\[ Y_i\mid x_i\sim\operatorname{Bernoulli}(p_i), \qquad p_i=\sigma(x_i^\top\beta),\quad \sigma(z)=\frac1{1+e^{-z}}. \]

The choice ensures probabilities lie strictly between zero and one. Its inverse link is the log odds,

\[ \log\frac{p_i}{1-p_i}=x_i^\top\beta. \]

Holding other inputs fixed, increasing predictor \(j\) by one multiplies the conditional odds by \(e^{\beta_j}\). It does not add a constant to the probability because the sigmoid is nonlinear.

The independent Bernoulli log likelihood is

\[ \begin{aligned} \ell(\beta) &=\sum_i\left[y_i\log p_i+(1-y_i)\log(1-p_i)\right]\\ &=\sum_i[y_i x_i^\top\beta-\log(1+e^{x_i^\top\beta})]. \end{aligned} \]

Using \(\sigma'(z)=\sigma(z)(1-\sigma(z))\),

\[ \nabla\ell=X^\top(y-p),\qquad \nabla^2\ell=-X^\top W X,\quad W_{ii}=p_i(1-p_i). \]

The Hessian is negative semidefinite, because \(u^\top X^\top WXu=\sum_i W_{ii}(x_i^\top u)^2\ge0\). Thus the log likelihood is concave. With full column rank it is strictly concave at finite coefficients, but a finite maximum need not exist: if classes can be perfectly separated by a hyperplane, scaling a separating coefficient vector can drive fitted probabilities toward perfect classification indefinitely. A positive squared-norm penalty (ridge regularization) ensures a finite unique solution when applied to all coefficients; it induces a bias–variance tradeoff.

S-shaped sigmoid curve from probability zero toward one, passing through probability one-half at linear predictor zero.
Figure 16.2: The logistic sigmoid converts any real-valued linear predictor into a conditional probability.

The negative log likelihood per observation is binary cross-entropy (log loss). For a true success probability \(q\) and prediction \(p\), its expected value is \(-q\log p-(1-q)\log(1-p)\). Differentiating with respect to \(p\) yields \((p-q)/[p(1-p)]\), so \(p=q\) uniquely minimizes expected loss for \(0<q<1\). This is why fitted probabilities, rather than just hard classifications, are valuable.

16.5 Evaluating prediction fairly

The training criterion measures how well coefficients fit the training data. To estimate performance on new data, hold out independent test observations or use cross-validation for model selection and a final untouched test set. All learned preprocessing (scaling, imputation, feature selection) must be fit only on training data within each split.

For numeric prediction we may use mean squared error, root mean squared error, or mean absolute error; they emphasize different aspects of error. For binary outcomes accuracy at threshold \(c\) compares \(\mathbf1_{\{\widehat p\ge c\}}\) to labels. It depends on prevalence and threshold. Log loss evaluates the probability estimates themselves, heavily penalizing confident wrong forecasts. The Brier score is the mean squared probability error.

Calibration asks whether events occur with approximately the frequencies predicted. For example, the empirical success fraction among many predictions near .8 should be near .8 if predictions are calibrated in that region. Perfect accuracy is neither required nor guaranteed by calibration. Use bins with enough observations and report uncertainty in small bins.

flowchart TD
    A["Sample"] --> B["Training subset"]
    A --> C["Held-out test subset"]
    B --> D["Fit preprocessing and model"]
    D --> E["Predict test outcomes"]
    C --> E
    E --> F["Evaluate error and calibration"]

If you repeatedly tune your model using the test outcomes, that test set has become part of the training process. Reserve fresh evaluation data or design nested resampling.

16.6 Practice problems

Work in your browser with Google Colab, or download the notebooks for Jupyter.

Practice notebook

Open in Colab Download .ipynb

Worked solutions

Open in Colab Download .ipynb

16.6.1 Exercise 1: Projection geometry

Show that \(H=X(X^\top X)^{-1}X^\top\) is symmetric and idempotent for full column rank \(X\). Why are residuals orthogonal to every design column?

Since \(X^\top X\) is symmetric so is its inverse; transposing \(H\) gives \(H\). Multiplying \(H^2\) cancels the central \(X^\top X\) with an inverse, giving \(H\). Finally \(X^\top(y-Hy)=X^\top y-X^\top X(X^\top X)^{-1}X^\top y=0\), so every design column is orthogonal to the residual vector.

16.6.2 Exercise 2: Odds versus probability

A logistic model has intercept zero and slope \(\log2\). Compute predicted probabilities for \(x=0,1,2\). Does each unit increase double the probability?

The odds are \(e^{x\log2}=2^x\), so the probabilities are \(2^x/(1+2^x)\): \(1/2,2/3,4/5\). Each unit increase doubles the odds, not the probability.

16.6.3 Exercise 3: The irreducible part of prediction error

For a chosen design row with \(h_0=.04\) and residual standard deviation \(s=3\), compare the estimated standard errors of the predicted mean and an independent future observation.

The mean has standard error \(3\sqrt{.04}=.6\). A future observation’s prediction error has standard error \(3\sqrt{1.04}\approx3.06\). Both intervals use the same t critical value, but the future interval is much wider due to new observation noise.

16.6.4 Exercise 4: Fit and examine a regression (Python)

Generate 100 evenly spaced predictor values in \([0,10]\) and responses from \(Y=4+1.5x+\epsilon\), \(\epsilon\sim N(0,2^2)\). Fit a line using NumPy, report coefficients and residual standard deviation, and draw a residual-versus-fitted plot. Then replace the error standard deviation by \(0.5+0.4x\) and repeat. What assumption has changed?

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(1601)
x = np.linspace(0,10,100)
X = np.column_stack([np.ones(x.size),x])
fig,axes = plt.subplots(1,2,figsize=(9,3.3))
for ax,sd,label in zip(axes,[2,.5+.4*x],["Constant variance","Changing variance"]):
    y = 4+1.5*x+rng.normal(0,sd,x.size)
    b = np.linalg.lstsq(X,y,rcond=None)[0]
    fitted = X@b
    resid = y-fitted
    print(label,b,np.sqrt(resid@resid/(x.size-2)))
    ax.scatter(fitted,resid,s=10)
    ax.axhline(0,color="black",linestyle="--")
    ax.set(title=label,xlabel="Fitted",ylabel="Residual")
plt.tight_layout()
plt.show()

The second error model is heteroscedastic: its variance increases with \(x\). Least squares can still estimate the linear mean without bias under the zero conditional mean assumption, but the constant-variance coefficient covariance formula is no longer correct.

16.6.5 Exercise 5: Implement logistic regression (Python)

Generate 1,000 observations using predictors \(x\sim N(0,1)\) and probabilities \(\sigma(-.5+1.2x)\). Split into 700 training and 300 test cases. Minimize the training negative log likelihood with analytic gradient using SciPy. Report test log loss and accuracy, and compare log loss with a constant training-prevalence predictor.

import numpy as np
from scipy.optimize import minimize
from scipy.special import expit

rng = np.random.default_rng(1602)
x = rng.normal(size=1000)
X = np.column_stack([np.ones(x.size),x])
y = rng.binomial(1,expit(X@np.array([-.5,1.2])))
train,test = np.split(rng.permutation(x.size),[700])
Xt,yt = X[train],y[train]
def loss_grad(b):
    z = Xt@b
    return np.sum(np.logaddexp(0,z)-yt*z), Xt.T@(expit(z)-yt)
res = minimize(loss_grad,np.zeros(2),jac=True,method="BFGS")
z = X[test]@res.x
p = expit(z)
logloss = np.mean(np.logaddexp(0,z)-y[test]*z)
base = np.clip(yt.mean(),1e-12,1-1e-12)
base_loss = -np.mean(y[test]*np.log(base)+(1-y[test])*np.log1p(-base))
print("Fit:",res.x,"Converged:",res.success)
print("Accuracy:",np.mean((p>=.5)==y[test]))
print("Log loss:",logloss,"Baseline:",base_loss)
assert np.linalg.norm(loss_grad(res.x)[1])<1e-3

The numerical objective uses \(\log(1+e^z)\) in a stable form. The gradient is exactly the negative score. The model’s test probability loss improves over the constant baseline in this simulated setting; accuracy alone would omit much of that information.

16.6.6 Exercise 6: End-to-end probability model check (Python)

Simulate 10,000 independent feature values and outcomes with the logistic model \(\sigma(0.3-0.9x)\). Compare predictions from the true model and an overly confident model \(\sigma(3(0.3-0.9x))\) using accuracy, Brier score, log loss and a reliability plot. Explain why a common decision threshold can hide miscalibration.

import numpy as np
from scipy.special import expit
import matplotlib.pyplot as plt

rng = np.random.default_rng(1603)
x = rng.normal(size=10_000)
z = .3-.9*x
y = rng.binomial(1,expit(z))
fig,ax = plt.subplots()
ax.plot([0,1],[0,1],"k--",label="Perfect calibration")
for label,zp in [("True",z),("Overconfident",3*z)]:
    p = expit(zp)
    print(label,"accuracy",np.mean((p>=.5)==y),
          "Brier",np.mean((p-y)**2),
          "log loss",np.mean(np.logaddexp(0,zp)-y*zp))
    bins = np.minimum((10*p).astype(int),9)
    means, rates = [],[]
    for j in range(10):
        mask = bins==j
        if mask.sum()>=50:
            means.append(p[mask].mean())
            rates.append(y[mask].mean())
    ax.plot(means,rates,"o-",label=label)
ax.set(xlabel="Mean predicted probability",ylabel="Observed success fraction",
       xlim=(0,1),ylim=(0,1))
ax.legend()
plt.show()

Both scores have the same sign and hence the same decisions at threshold .5. The overconfident model assigns more extreme probabilities than the true data-generating mechanism. Its log loss and Brier score expose degraded probability quality even though accuracy is unchanged.

16.7 Where to go next

You have now connected probability axioms, random variables, transformations and asymptotics to estimation, testing, Bayesian updates, dependent data and prediction. Revisit the practice notebooks without looking at solutions. For further study, the natural next topics are measure-theoretic probability, generalized linear models, multivariate statistical inference, Bayesian computation, stochastic processes, and statistical learning theory.