Often, we are interested in gradients: how \(Y\) changes with \(X\). The linear model from Simple Regression depicts this as a single constant, \(\hat{B}_{1}\), but the local-regression models from Local Regression do not. A great first step to assess gradients is to plot the predicted values over the explanatory values. A great second step is to compute gradients and summarize them. In any case, we compute confidence intervals to account for variability across samples.
16.1 Applied Methods
LOESS
When \(\hat{X}_{i}\) is unevenly distributed across its range, a fixed bandwidth \(h\) leaves some local fits with many neighbors and others with very few.
ImportantKey Definition
LOESS (locally estimated scatterplot smoothing) fits a local linear (or quadratic) regression at each design point using an adaptive bandwidth: instead of fixing \(h\), it includes a fixed share of the data at each \(x\), set by the parameter span.
LOESS is useful for smoothing data with uneven \(X\): because the share of points in each neighborhood is fixed, the local fit has roughly the same effective sample size everywhere, even where the data are sparse. The span parameter plays the role \(h\) does for fixed-bandwidth methods, so smaller spans mean narrower neighborhoods, more flexibility, and noisier curves, while larger spans pool more data and smooth more aggressively.
A single fitted curve does not show how much that curve would change in another sample, so we draw a region around it.
ImportantKey Definition
A confidence band is a confidence interval drawn at every design point: a region around the fitted curve that captures sample-to-sample variability. A bootstrap confidence band collects the predictions from many resamples and reads off pointwise quantiles at each \(x\).
Confidence bands are useful for showing where a fitted curve is well-supported by the data and where another sample could move it. The width is typically wider at the edges of \(X\) (few neighbors) and narrower in the dense middle, which is itself a quick visual diagnostic. The same bootstrap that produces the band also produces standard errors for any single design point and for the gradient summaries below.
Code
# Same loess fit as above (default span)pred_design <-data.frame(school=unique(dat[, 'school']))preds_lo <-predict(reg_lo, newdata=pred_design)plot(wage ~ school, pch=16, col=grey(0, .1), data=dat,main=NA, xlab='School', ylab='Wage')lo_col <-adjustcolor('#20B2AA', alpha.f=.5) # same teal greenlines(pred_design[, 'school'], preds_lo,col=lo_col, type='o', pch=2)# Boot CI with the same default-span loessboot_lo <-matrix(NA, nrow=nrow(pred_design), ncol=399)for (b in1:399) { xy_b <- dat[sample(nrow(dat), replace=TRUE), ] reg_b <-loess(wage ~ school, data=xy_b) boot_lo[, b] <-predict(reg_b, newdata=pred_design)}boot_cb <-apply(boot_lo, 1, quantile,probs=c(.025, .975), na.rm=TRUE)# Plot CIpolygon(c(pred_design[[1]], rev(pred_design[[1]])),c(boot_cb[1, ], rev(boot_cb[2, ])),col=lo_col,border=NA)
NoteMust Know
Construct a bootstrap confidence band for the following loess regression
A better fit on the data you have is not automatically better, because a model can hit every point in the sample and still predict new observations poorly.
ImportantKey Definition
The bias-variance tradeoff describes two sources of model error: bias (systematic miss from over-smoothing) and variance (sample-to-sample wobble from under-smoothing).
The bias-variance tradeoff is useful for thinking about why a tuning parameter matters and how to set it. For local regressions, the bandwidth \(h\) (equivalently, the LOESS span) is the lever that governs the tradeoff: large \(h\) trades variance down for bias up, small \(h\) does the opposite. A loess fit narrow enough to interpolate every point has \(\hat{MSE}=0\) on the fit data but generalizes poorly because it has just copied the noise.
Wide window (large span, large \(h\)): each local fit uses many observations, so the fitted curve barely changes from sample to sample (low variance). But a nearly flat fit over a wide region cannot follow a relationship that bends, so it is systematically off (high bias).
Narrow window (small span, small \(h\)): each local fit uses few observations, so the fitted curve chases noise and swings from sample to sample (high variance). But a narrow window can track curvature closely (low bias).
With span \(4.0\) the fitted curve is very smooth and stable, and the bootstrap band sits tightly around it. With span \(0.4\) the curve tracks more local variation, and the bootstrap band fans wider, directly displaying the variance penalty for chasing local detail. (school is integer-valued with only \(14\) distinct values, so spans below about \(0.4\) collapse to single-point neighborhoods and loess() cannot fit.) Choosing the span (the bandwidth \(h\)) means trading bias against variance. We make this tradeoff precise in Association and Prediction Are Not Causation, where the bias-variance decomposition gives a formal expression and simulations check both pieces.
Note that the simple linear regression is nested as a special case with \(span \to \infty\).
Model Fit
Each local model produces fitted values \(\hat{y}_{i}\) and residuals \(\hat{E}_{i} = \hat{Y}_{i} - \hat{y}_{i}\). To compare models, we often summarize the residuals with a single number.
The mean squared error averages the squared residuals, \[\begin{aligned}
\hat{MSE} &= \frac{1}{n}\sum_{i=1}^{n} \hat{E}_{i}^2 = \frac{1}{n}\sum_{i=1}^{n} \left(\hat{Y}_{i} - \hat{y}_{i}\right)^2.
\end{aligned}\] Squaring penalizes large misses heavily, and the units are the square of \(\hat{Y}_{i}\) (squared dollars for wages).
The mean absolute percentage error instead averages each residual relative to its observed value, \[\begin{aligned}
\hat{MAPE} &= \frac{100}{n}\sum_{i=1}^{n} \left| \frac{\hat{E}_{i}}{\hat{Y}_{i}} \right|.
\end{aligned}\] MAPE is unit-free, which makes it easy to communicate, but it is undefined when \(\hat{Y}_{i}=0\) and over-weights observations with small \(\hat{Y}_{i}\). MSE is easier to analyze theoretically (formally deriving the bias-variance tradeoff)
NoteMust Know
Suppose three workers have wages \(\hat{Y}=(8, 10, 15)\) and a model predicts \(\hat{y}=(9, 9, 14)\). The residuals are \(\hat{E}=(-1, 1, 1)\), so \[\begin{aligned}
\hat{MSE} &= \frac{(-1)^2 + 1^2 + 1^2}{3} = \frac{3}{3} = 1, \\
\hat{MAPE} &= \frac{100}{3}\left( \frac{1}{8} + \frac{1}{10} + \frac{1}{15} \right) \approx \frac{100}{3}(0.292) \approx 9.7.
\end{aligned}\] The model misses by \(1\) squared-dollar on average, or about \(10\%\) of each wage.
Code
Y <-c(8, 10, 15)y_hat <-c(9, 9, 14)e <- Y - y_hatmean(e^2) # MSE## [1] 1100*mean(abs(e/Y)) # MAPE## [1] 9.722222
We can compute these for the linear, regressogram, and piecewise models on the wage~school data.
Code
library(Ecdat)dat <- Wages1[order(Wages1[, 'school']), c('wage', 'school')]# Three models for wage on schoolingreg_lin <-lm(wage ~ school, data=dat) # globally lineardat[, 'xcf'] <-cut(dat[, 'school'], 3)reg_rgram <-lm(wage ~ xcf, data=dat) # regressogram, 3 binsreg_pw <-lm(wage ~ xcf*school, data=dat) # piecewise, 3 bins# Mean squared error and mean absolute percentage errorfit_stats <-function(model){ e <-resid(model) Y <- dat[, 'wage']c(MSE=mean(e^2), MAPE=100*mean(abs(e/Y)))}round(rbind(Linear =fit_stats(reg_lin),Regressogram =fit_stats(reg_rgram),Piecewise =fit_stats(reg_pw)), 2)## MSE MAPE## Linear 9.83 73.27## Regressogram 10.27 75.88## Piecewise 9.73 72.82
16.2 Relationships
Gradients
Once the fitted curve can bend, “the slope” is no longer a single number; we want the slope locally at each \(x\).
ImportantKey Definition
A gradient\(\hat{B}_{1}(x)\) at the design point \(x\) is the rate of change of the fitted value \(\hat{y}(x)\) with respect to \(\hat{X}_{i}\) in a neighborhood of \(x\).
The gradient is useful as the local analog of the simple-regression slope: for a globally linear model it equals the single coefficient \(\hat{B}_{1}\) everywhere; for a local model it varies with \(x\) and traces out how the marginal relationship changes across the range of \(X\). Three common ways to summarize gradients are:
For all methods, including regressograms, you can approximate gradients with small finite differences. For some small difference \(d\), we can manually compute \[\begin{aligned}
\hat{B}_{1}(x) &= \frac{ \hat{y}(x+\frac{d}{2}) - \hat{y}(x-\frac{d}{2})}{d},
\end{aligned}\]
When using split-sample regressions or local linear regressions, you can use the estimated slope coefficients \(\hat{B}_{1}(x)\) as a gradient estimate.1
More sophisticated methods that are beyond the scope of this class.
NoteMust Know
Suppose a local model predicts wages near \(x=12\) years of schooling: \(\hat{y}(11.5)=9.2\) and \(\hat{y}(12.5)=10.4\) (dollars per hour). With step \(d=1\), the finite-difference gradient at \(x=12\) is \[
\hat{B}_{1}(12) = \frac{\hat{y}(12.5) - \hat{y}(11.5)}{d} = \frac{10.4 - 9.2}{1} = 1.2.
\] Near \(12\) years of schooling, each extra year is associated with about \(\$1.20\) more per hour.
Code
d <-1y_hi <-10.4# prediction at x + d/2y_lo <-9.2# prediction at x - d/2(y_hi - y_lo) / d## [1] 1.2
After computing gradients, you can summarize them in various plots: Histograms and Scatterplots. The confidence band only shows variability across samples, whereas these plots show variability within-sample. You can also plot all Gradients with their CI’s (Chaudhuri and Marron 1999; Henderson et al. 2012).
A different kind of summary collapses the whole gradient curve into a single number for tabular reporting.
ImportantKey Definition
The gradient at the mean (sometimes called the marginal effect at the mean) evaluates the gradient at a single design point: \[\hat{B}_{1}(x=\hat{M}_{X}).\] The mean of the gradients (sometimes called the average effect or mean marginal effect) averages \(\hat{B}_{1}(x)\) across every observation in the dataset: \[\frac{1}{n}\sum_{i=1}^{n} \hat{B}_{1}(x=\hat{X}_{i}).\]
These two summaries are useful for different questions: the gradient at the mean answers “what is the slope at a typical \(X\)?”, while the mean of the gradients answers “what is the average slope across the sample?”. The two coincide for a globally linear model but can differ for any other, sometimes substantially when the relationship bends. You may also be interested in the median of the gradients, or in measures of effect heterogeneity like the interquartile range or standard deviation of the gradients. Such statistics can be presented in tabular form: “mean gradient (sd gradient)” or “mean gradient (estimated SE), sd gradient (estimated SE)”.
TipTest Yourself
These two summaries usually differ. Suppose a local model has gradients \(\hat{B}_{1}(x)\) at schooling levels \(x=(8,10,12,14,16)\) equal to \((0.4, 0.8, 1.2, 0.9, 0.3)\), and the sample mean schooling is \(\hat{M}_{X}=12\).
The marginal effect at the mean is the single gradient at \(x=\hat{M}_{X}\): \(\hat{B}_{1}(12) = 1.2\).
The mean of the gradients averages over all five points: \(\frac{0.4+0.8+1.2+0.9+0.3}{5} = \frac{3.6}{5} = 0.72\).
They differ because the gradient is not constant: here the relationship is steepest near the mean and flatter at the extremes.
Code
grads <-c(0.4, 0.8, 1.2, 0.9, 0.3)grads[3] # marginal effect at the mean (x = 12)## [1] 1.2mean(grads) # mean of the gradients## [1] 0.72
We can test whether the mean gradient is statistically different from zero. We can compute the p-value directly from the bootstrap distribution. Under \(H_0\), the mean gradient equals zero, so we center the bootstrap distribution at zero and ask how often it produces values as extreme as the observed mean gradient.
Code
## P-value via null bootstrap ECDF## Center bootstrap means at zero (impose H0)boot_centered <- boot_stats[, 'Mean SE'] -mean(boot_stats[, 'Mean SE'])## ECDF of centered bootstrap distributionboot_ecdf <-ecdf(boot_centered)## Two-sided p-value: P(|centered mean| >= |observed mean|)p_boot <-1-boot_ecdf(abs(tab_stats['Mean'])) +boot_ecdf(-abs(tab_stats['Mean']))cat('Bootstrap p-value (ECDF):', format.pval(p_boot, digits=3), '\n')## Bootstrap p-value (ECDF): 0.00669
The small p-value indicates that the mean gradient is statistically distinguishable from zero: on average, wages increase with schooling.
We can also use a normal approximation. Under the null hypothesis \(H_0\): the mean gradient equals zero, we use the test statistic \[t = \frac{\text{mean gradient}}{\text{SE(mean gradient)}}\] and the p-value comes from the standard normal distribution.
Code
## P-value for mean gradient## Standard Normal Approximationt_stat <- tab_stats['Mean'] / boot_se['Mean SE']p_val <-2*pnorm(-abs(t_stat))cat('Mean gradient:', round(tab_stats['Mean'], 3), '\n')## Mean gradient: 0.133cat('Bootstrap SE: ', round(boot_se['Mean SE'], 3), '\n')## Bootstrap SE: 0.042cat('t-statistic: ', round(t_stat, 3), '\n')## t-statistic: 3.156cat('p-value: ', format.pval(p_val, digits=3), '\n')## p-value: 0.0016
TipTest Yourself
Compute the t-statistic and p-value using jackknife standard errors instead of the bootstrap.
Comment the script you wrote for this chapter, then restart R and check that it runs from a clean session, then check the script with AI as explained in Working with AI. Write three sentences from memory on the main statistical idea of this chapter, and ask the assistant what is wrong, vague, or missing. Finish with your own questions about whatever you found hardest.
A linear regression has low variance but can have high bias when the true relationship is nonlinear. A loess regression with a small span has low bias but high variance. Explain why increasing the sample size \(n\) helps reduce the standard error for both models, but only helps reduce bias for loess (with an appropriate bandwidth rule).
Using the USArrests dataset, fit a loess regression of Murder on UrbanPop with span = 0.6. Compute the finite-difference gradients \(\hat{B}_{1}(x)\) and report their mean and standard deviation. Compare these to the OLS slope \(\hat{B}_{1}\) from a simple linear regression.
Using the USArrests dataset and the loess fit from the previous question, write R code to construct a bootstrap confidence band with \(B = 399\) replicates. Plot the scatterplot, the loess curve, and the shaded 95% confidence band.
This chapter put inference around the local fits from the previous chapter on the Wages1 data: model-fit metrics (\(\hat{MSE}\) and \(\hat{MAPE}\)) and the bias-variance tradeoff, bootstrap confidence bands for a LOESS fit, gradient summaries (marginal effect at the mean vs mean of the gradients), and hypothesis tests. The small worked example with \(\hat{y}(11.5)=9.2\) and \(\hat{y}(12.5)=10.4\) gave a finite-difference gradient \(\hat{B}_{1}(12)=1.2\) dollars per year of schooling, and the gradient-vector example \((0.4, 0.8, 1.2, 0.9, 0.3)\) at \(x=(8, 10, 12, 14, 16)\) showed the marginal-effect-at-the-mean (\(1.2\)) and the mean-of-the-gradients (\(0.72\)) diverging when the relationship bends. The next chapter separates descriptive and predictive relationships from causal claims.
Chaudhuri, Probal, and J. S. Marron. 1999. “SiZer for Exploration of Structures in Curves.”Journal of the American Statistical Association 94 (447): 807–23. https://doi.org/10.1080/01621459.1999.10474186.
Henderson, Daniel J., Subal C. Kumbhakar, and Christopher F. Parmeter. 2012. “A Simple Method to Visualize Results in Nonlinear Regression Models.”Economics Letters 117 (3): 578–81. https://doi.org/10.1016/j.econlet.2012.07.040.
One benefit of LLLS is that it is theoretically motivated: assuming that \(Y_{i}=M(X_{i}) + \epsilon_{i}\), we can then take a Taylor approximation: \(M(X_{i}) + \epsilon_{i} \approx M(x) + M'(x)[X_{i}-x] + \epsilon_{i} = [M(x) - M'(x)x ] + M'(x)X_{i} + \epsilon_{i} = b_{0}(x,h) + b_{1}(x,h) X_{i}\).↩︎