PS 818 - Data Analysis with Statistical Models
November 23, 2026
\[ \DeclareMathOperator*{\argmin}{arg\,min} \DeclareMathOperator*{\argmax}{arg\,max} \]
atmp is the station’s average temperature for the month and ntmp its “normal” temperature for January (both in degrees C)weather <- read_csv("data/monthly_summary_202501_v2.csv") %>% filter(country == "UNITED_STATES")
weather <- weather %>% filter(atmp > -99999&ntmp > -99999) # Missing obs hard coded as -99999
weather <- weather %>% mutate(deviation = atmp - ntmp)
weather <- weather %>% filter(!(state %in% c("AK", "HI", "AS", "GU", "MP", "UM", "PR", "VI")))# Set boundaries for U.S. (approximate)
lat_min <- 24.396308 # Southernmost point (Florida)
lat_max <- 49.384358 # Northernmost point (Canada border)
lon_min <- -125.0 # Westernmost point (California)
lon_max <- -66.93457 # Easternmost point (Maine)
# Approximate 50 km in degrees (this will vary by latitude, but we'll use an average factor)
lat_interval <- 50 / 110.574 # 1 degree latitude ≈ 110.574 km
lon_interval <- 50 / (111.320 * cos(mean(c(lat_min, lat_max)) * pi / 180)) # Longitude interval varies with latitude
# Create a sequence of points for latitude and longitude
latitudes <- seq(lat_min, lat_max, by = lat_interval)
longitudes <- seq(lon_min, lon_max, by = lon_interval)
# Create a grid of all combinations of latitudes and longitudes
grid_points <- expand.grid(lat = latitudes, lon = longitudes)
# Convert the grid points to an 'sf' object
grid_points_sf <- st_as_sf(grid_points, coords = c("lon", "lat"), crs = st_crs(us_shapefile), remove=F)
# Filter grid points to keep only those within the U.S. boundary
grid_points_within_us <- st_intersection(grid_points_sf, us_shapefile)At the most general level, (nearly) every method we’ve talked about involves finding a function that optimizes some objective
Given a set of \(n\) inputs, \(\{x_i, y_i\}\), we want to find a function that solves
\[\hat{f} = \argmin_{f} \ \mathcal{L}\bigg(f, \{x_i, y_i\}_{i=1}^n\bigg)\]
We started with some severe constraints on the space of functions over which we search.
Linear functions
\[f(x) = \beta_0 + \beta_1x_1 + \beta_2x_2 + \beta_3x_3 + \dotsc\]
We’ve considered relaxations that allow our functions to be more flexible in form
Basis expansions
\[f(X) = \sum_{m=1}^M \beta_m h_m(X)\]
Penalized basis expansions (e.g. smoothing splines)
\[\min_f \sum_{i=1}^N \big(Y_i - f(X_i)\big)^2 + \lambda \int f''(x)^2 \, dx\]
Trees are are also a kind of basis expansion with an adaptively chosen basis: \(h_m(x) = \mathbf{1}(x \in R_m)\)
\[g(x; T, M) = \sum_{m=1}^{|T|} \mu_m \mathbf{1}(x \in R_m)\]
Ensembles of trees
\[f(x) = \sum_{b=1}^B w_b \, g(x; T_b, M_b)\]
One can think of a forest as also a kind of weighted average prediction using “similar” observations (Athey, Tibshirani, and Wager 2019)
\[\hat{f}(x) = \sum_{i=1}^N \alpha_i(x) Y_i, \quad \alpha_i(x) = \frac{1}{B} \sum_{b=1}^B \frac{\mathbf{1}\big(X_i \in L_b(x)\big)}{|L_b(x)|}\]
Can we be more flexible than this while still retaining computational feasibility?
“Kernel methods” consider searching over a space of functions defined implicitly by a positive-definite kernel function.
Example, the Gaussian kernel
\[K(x, x^\prime) = \exp\bigg(-\frac{||x - x^\prime||^2}{2\sigma^2}\bigg)\]
The set of functions we’ll search over is a linear combination of kernels evaluated at the data points.
\[f(x) = \sum_{i=1}^N c_i K(x, x_i)\]
What is this space of functions? How “flexible” is it?
Take any basis expansion \(\phi(x) = \big(h_1(x), \dotsc, h_M(x)\big)\), possibly with more features than observations (\(M > N\)). Row \(i\) of \(\Phi\) is \(\phi(x_i)^\prime\).
\[\hat{\beta} = \argmin_{\beta} \ (\mathbf{y} - \Phi\beta)^\prime(\mathbf{y} - \Phi\beta) + \lambda \beta^\prime\beta\]
Split any \(\beta\) into a combination of the data points plus a leftover \(r\) that is orthogonal to every \(\phi(x_i)\)
\[\beta = \sum_{i=1}^N c_i \phi(x_i) + r\]
So ridge always sets \(r = 0\). The solution is always a combination of the data points: \(\hat{\beta} = \sum_{i=1}^N \hat{c}_i \phi(x_i)\)
The prediction at any \(x\) only needs inner products between \(\phi(x)\) and the data
\[\hat{f}(x) = \phi(x)^\prime\hat{\beta} = \sum_{i=1}^N \hat{c}_i \, \phi(x)^\prime\phi(x_i) = \sum_{i=1}^N \hat{c}_i K(x, x_i)\]
So do the fit and the penalty. With \(\mathbf{K} = \Phi\Phi^\prime\) we get \(\Phi\beta = \mathbf{K}\mathbf{c}\) and \(\beta^\prime\beta = \mathbf{c}^\prime\mathbf{K}\mathbf{c}\)
The kernel trick: we never need \(\phi\) itself, only \(K(x, x^\prime) = \phi(x)^\prime\phi(x^\prime)\)
Representer theorem: this works for any loss function. The penalized solution is always a weighted sum of \(N\) kernels, one centered at each data point.
Column \(j\) is the kernel evaluated between each observation and \(x_j\), so the prediction for \(x_i\) is a linear combination of the kernels in row \(i\)
\[f(x_i) = c_1K(x_i, x_1) + c_2K(x_i, x_2) + \dotsc c_n K(x_i, x_n)\]
For \(f(x) = \sum_{i=1}^n c_i K(x, x_i)\), the RKHS norm is \(||f||^2_{\mathcal{H}_K} = \mathbf{c}^\prime\mathbf{K}\mathbf{c}\)
So KRLS is a ridge regression of \(\mathbf{y}\) on the columns of \(\mathbf{K}\), with a penalty that also uses \(\mathbf{K}\)
\[\hat{\mathbf{c}} = \argmin_{\mathbf{c}} \ (\mathbf{y} - \mathbf{K}\mathbf{c})^\prime(\mathbf{y} - \mathbf{K}\mathbf{c}) + \lambda \mathbf{c}^\prime\mathbf{K}\mathbf{c}\]
With a closed-form solution
\[\hat{\mathbf{c}} = (\mathbf{K} + \lambda \mathbf{I})^{-1}\mathbf{y}\]
Two tuning parameters: the kernel bandwidth \(\sigma^2\) and the penalty \(\lambda\)
krls() standardizes each input and uses the kernel \(\exp(-||x - x^\prime||^2/\sigma^2)\). Its argument sigma is the \(\sigma^2\) in that formula.approx = "none": since version 1.7, krls() silently switches to a low-rank approximation of \(\mathbf{K}\) when \(N > 500\).Ridge regression is the posterior mode under a normal prior on \(\beta\). KRLS has the same Bayesian reading.
Prior: the function values at the data are multivariate normal, with the kernel as their covariance
\[\mathbf{f} = \{f(x_1), \dotsc, f(x_n)\} \sim \text{Normal}(\boldsymbol{\mu}, \mathbf{K}), \qquad \mathbf{K}_{ij} = K(x_i, x_j) = \sigma_0^2\exp\bigg(-\frac{||x_i - x_j||^2}{2l^2}\bigg)\]
Likelihood: \(y_i = f(x_i) + \epsilon_i\), with \(\epsilon_i \sim \text{Normal}(0, \sigma_y^2)\)
Posterior mean at a new input \(x^*\), with \(\mathbf{k}_* = K(x^*, \mathbf{x})\):
\[E[f(x^*)|\mathbf{y}] = \mu + \mathbf{k}_*(\mathbf{K} + \sigma_y^2 I)^{-1}(\mathbf{y} - \boldsymbol{\mu}) = \mu + \sum_{i=1}^n \hat{c}_i K(x^*, x_i)\]
Uncertainty: the full posterior of \(f(x^*)\) is normal, with variance
\[Var[f(x^*)|\mathbf{y}] = K(x^*, x^*) - \mathbf{k}_*(\mathbf{K} + \sigma_y^2 I)^{-1}\mathbf{k}_*^\prime\]
gp_neg_loglik <- function(log_par, x, y) { # log_par = log(sigma0, l, sigma_y)
par <- exp(log_par)
Sigma <- rbf_kernel(x, x, par[1], par[2]) + diag(par[3]^2, length(y))
-mvtnorm::dmvnorm(y, rep(mean(y), length(y)), Sigma, log = TRUE)
}
krig_opt <- optim(log(c(3, 300, 1)), gp_neg_loglik, x = stations_km, y = weather$deviation)
krig_par <- setNames(exp(krig_opt$par), c("sigma0", "l", "sigma_y"))
krig_par sigma0 l sigma_y
1.04 186.37 1.03
gp_predict <- function(x, y, x_new, sigma0, l, sigma_y) { # posterior mean and SD of f(x_new)
K_inv <- solve(rbf_kernel(x, x, sigma0, l) + diag(sigma_y^2, length(y)))
k_star <- rbf_kernel(x_new, x, sigma0, l)
post_mean <- as.vector(mean(y) + k_star %*% K_inv %*% (y - mean(y)))
post_sd <- sqrt(pmax(sigma0^2 - rowSums((k_star %*% K_inv) * k_star), 0))
data.frame(fit = post_mean, sd = post_sd, lower = post_mean - 1.96 * post_sd, upper = post_mean + 1.96 * post_sd)
}
krig <- gp_predict(stations_km, weather$deviation, grid_km, krig_par["sigma0"], krig_par["l"], krig_par["sigma_y"])
grid_points_within_us$gp_mean <- krig$fit
grid_points_within_us$gp_sd <- krig$sdpolls_all <- read_csv("data/all_polls_2012.csv") %>% filter(state == "--") %>% # national polls
mutate(end.date = mdy(end.date),
obama.2way = obama/(obama + romney),
day = as.numeric(end.date - ymd("2012-11-06"))) # 0 = Election Day, -211 = April 9
actual_2way <- 65915795/(65915795 + 60933504) # Obama's share of the two-party vote (FEC) sigma0 l sigma_y
0.00769 10.56362 0.01799
Poll aggregators usually model the trend as a random walk (Jackman 2005; Linzer 2013)
\[f(t) = f(t-1) + \epsilon_t\]
That’s just a GP with a different kernel:
These kernels are Markov: the future depends on the past only through the present.
After the last poll, a random walk keeps the last level instead of reverting to the grand mean.
PS 818 - University of Wisconsin-Madison