Kharon Applied Intelligence Fellowship in Denver, London, or Madrid

Juan Lopez Martin (coauthor of the very useful MRP Case Studies) writesL

Kharon, where I work, is launching a new program called the Applied Intelligence Fellowship, and I think Master/PhD students at PoliSci/SIPA/Stats/QMSS would be a great fit.

Kharon operates at the intersection of data science and global issues, building data, intelligence, and technology products that help organizations understand geopolitical and economic security risks. Our work maps the connections between companies, people, technologies, supply chains, and networks to reveal relationships with real-world consequences.

The fellowship is a six-month, full-time, paid program for people interested in using AI and computational methods to understand complex global systems, geopolitics, and economic security. I’ll be working closely with the fellows throughout the program, which is also designed to lead to a permanent role on our team.

I just noticed that the deadline for the application is 23 Nov, so if you’re interested, you better get to it right away!

Postdoc opportunity! Here with me at Columbia! Cutting-edge Bayesian analysis and causal inference: Statistical Tools for Generalizing in Education Research.

We’re seeking excellent applicants who are excited to make important contributions in Bayesian modeling, statistical computation, education research, and quantitative social science, in a fun and demanding work environment.

The project aims to develop new statistical tools for nonrepresentative samples and imbalanced experiments, addressing problems of generalization that are central challenges in empirical research. The project will improve statistics and research methodology in education research by enabling researchers and policymakers to make more reliable generalizations and focused estimates, unifying the ideas of multilevel regression, poststratification, and sampling weights. The goal is for education researchers to be able to fit more sophisticated regressions, multilevel models, and small-area estimation to real-world data.

The approach will use the following statistical methods: Bayesian inference, sampling theory, bootstrapping, Monte Carlo methods, multilevel regression, and poststratification. The core of the proposed method is a new theoretical idea for embedding sampling weights into a joint distribution with modeled outcomes, along with analytical work mapping population to sampling distribution, and a computational implementation using probabilistic programming. The postdoc will help apply these methods to existing experiments in education research, including the Head Start Impact Study.

The postdoc will work with Prof. Andrew Gelman in the Department of Statistics and Political Science at Columbia University and be immersed in an active research community, including Ph.D. students and postdoctoral researchers in statistics, economics, political science, and biostatistics; programmers; and a weekly meeting on causal inference. The project will involve active collaboration with Prof. Tyler Watts of Teachers College, Columbia University. In addition to the immediate research group, the Departments of Statistics and Political Science and Teachers College are lively research communities involving a wide range of projects, and there will also be the opportunity to work with others at the university and in the larger New York City research community.

Review of applications begins immediately and will continue until the position is filled.

You should have a PhD at the time of appointment, expertise in Bayesian modeling and computation, and an interest in education research. Knowledge of survey sampling and causal inference is a plus, and the work will involve programming in Stan, R, and Python.

Please send a cover letter (explaining your interest and qualifications for the position), a C.V., and names of at least two recommenders to me at [email protected]

Survey Statistics: Blue Rose Research is hiring !

As readers may know, I’m a survey statistician at Blue Rose Research. We survey the public to forecast elections and test political messages, used to advise Democrats. We are hiring for several roles heading into the 2028 election cycle: https://blueroseresearch.org/jobs/

All positions are remote, with an option to be in person in New York City.

Please circulate and apply !

The polar bear is at Blue Mountain Reservation:

 

Bayesian Workflow (my talk in NYC, Wed 18 Nov 2:30pm)

This talk is sponsored by the New York City Chapter of the American Statistical Association, and it’s at CUNY Graduate Center, 365 Fifth Avenue, room 8301 & 8304 (8th Floor).  If you want to attend (in person or remotely; I recommend in person!), just go to the form before 15 Nov and fill it out.

Also here’s a zoom link so if you’re attending remotely, maybe you don’t need to sign up.

Here’s the summary:

Bayesian statistics and statistical practice have evolved over the years, driven by advancements in theory, methods, and computational tools. This book explores the intricate workflows of applied Bayesian statistics, aiming to uncover the tacit knowledge often overlooked in published papers and textbooks. By systematizing the process of Bayesian model development, the book seeks to improve applied analyses and inspire future innovations in theory, methods, and software. It emphasizes the importance of iterative model building, model checking, computational troubleshooting, and simulated-data experimentation, offering a comprehensive perspective on statistical analysis.

Through detailed examples and practical guidance, the book bridges the gap between theory and application, empowering practitioners and researchers to navigate the complexities of Bayesian inference. It is not a checklist or cookbook but a flexible framework for understanding and resolving challenges in statistical modeling and decision making under uncertainty.

The key innovations of Bayesian Workflow include:

    • Going beyond Bayesian data analysis (model building, inference, model checking, and model expansion) to consider the larger process of statistical modeling, including comparisons of multiple models fit to a single dataset.
    • A fuller use of informative priors.  One reason we’ve moved toward stronger priors is that the replication crisis has taught us that the amount of prior information available in any given problem is often approximately the same as the information coming from an experiment (see here, for example). Informative priors also fit our increased focus on generative modeling, and we’re doing a lot more prior predictive checking to understand the implications of our models.
    • More integration between modeling, data analysis, and computing. One way to see this is that the Bayesian Workflow webpage has the code to run all our examples.
    • Simulation-based experimentation.  At its most basic, simulation-based experimentation provides a best-case baseline for statistical methods: if you can’t recover your quantities of interest with sufficient accuracy under ideal conditions (when your data are simulated from the model you’re fitting), then you know you’re in trouble. And often this is the case! Beyond that, we can simulate from one model and fit another, and see what happens. Simulation experiments aren’t always so easy to construct, as they involve specifying the entire data-generation process.

All the information on the book, including the book itself, is at the Bayesian Workflow webpage.

The non-Bayesians among you might be interested in Appendix A of the book, on Statistical and computational workflow for Bayesians and non-Bayesians, and also our short general article, Statistical Workflow, and its accompanying journal issue.

In the talk I’ll follow my usual practice and tell lots of stories.  Stories are how we learn about the world, and I’ll try to also go meta and discuss the anomalous and immutable aspects of the stories I tell.

If you can make it to the talk, please come prepared with some tough questions!

Constructing a latent-variable model to fit measurement data: A polychoric story

Following up on our recent post, Mathias Berggren writes:

I coded up a polychoric estimate for the problem you present in Constructing a latent-variable model to fit measurement data: A Stan story, part 2. I think it led to pretty decent estimates. I attach the R-code in case you want to have a look.

I hadn’t thought about it, but I guess it makes sense that this sort of model is used enough that people would have already hard-coded it!

Here’s the R code:

# Polychoric solution of latent variable stan example from Andrew

# Load required libraries
library(polycor)

# Data as a matrix
data = matrix(c(208,501,51,640,9879,1439,40,464,1432), nrow = 3, ncol = 3)

# Observed joint probabilities
Pobs = data / sum(colSums(data))

# Polychoric estimate of the latent correlation
r = polychor(data)

# Observed marginal probabilities
pX = colSums(data) / sum(colSums(data))
pY = rowSums(data) / sum(colSums(data))

# Corresponding marginal thresholds
cX = c(qnorm(pX[1]),qnorm(pX[1]+pX[2]))
cY = c(qnorm(pY[1]),qnorm(pY[1]+pY[2]))

# Estimated joint probabilities from this information
P = matrix(nrow = 3, ncol = 3)
P[1,1] = integrate(function(y) dnorm(y) * pnorm((cX[1]-r*y)/sqrt(1-r^2)), -Inf, cY[1])$value
P[1,2] = integrate(function(y) dnorm(y) * (pnorm((cX[2]-r*y)/sqrt(1-r^2)) - pnorm((cX[1]-r*y)/sqrt(1-r^2))), -Inf, cY[1])$value
P[2,1] = integrate(function(y) dnorm(y) * pnorm((cX[1]-r*y)/sqrt(1-r^2)), cY[1], cY[2])$value
P[2,2] = integrate(function(y) dnorm(y) * (pnorm((cX[2]-r*y)/sqrt(1-r^2)) - pnorm((cX[1]-r*y)/sqrt(1-r^2))), cY[1], cY[2])$value
P[1,3] = pY[1] - P[1,1] - P[1,2]
P[2,3] = pY[2] - P[2,1] - P[2,2]
P[3,1] = pX[1] - P[1,1] - P[2,1]
P[3,2] = pX[2] - P[1,2] - P[2,2]
P[3,3] = pX[3] - P[1,3] - P[2,3]

# Compare estimated and observed probabilities
P
Pobs
Pobs - P

# Find least squares estimates to transform thresholds to 1.5 and 3.5
b1X = sd(c(1.5, 3.5)) / sd(cX)
b0X = mean(c(1.5, 3.5)) - b1X * mean(cX)

b1Y = sd(c(1.5, 3.5)) / sd(cY)
b0Y = mean(c(1.5, 3.5)) - b1Y * mean(cY)

# Check  so we get the correct values
b0X + b1X * cX
b0Y + b1Y * cY

# Least squares estimates
# These show how we should transform the standard normal marginal 
# distributions above to a scale with thresholds 1.5 and 3.5.
# Thus, they also indicate the updated mean and standard deviation of 
# each variable (as they transform from one with mean = 0 and sd = 1).
# If one wants one common mean, then one might take some weighted mean 
# of the intercepts
c(b0X,b1X)
c(b0Y,b1Y)

# Discussion
# If there are more thresholds then the least squares solutions may not be 
# exact, and we may find that the thresholds cannot be at 1.5, 2.5, etc.
# Same way, one might find that the intercept cannot be the same.

The challenge of truly probabilistic programming

Many years ago, Jouni and I wrote an unpublished paper called Fully Bayesian Computing:

A fully Bayesian computing environment calls for the possibility of defining vector and array objects that may contain both random and deterministic quantities, and syntax rules that allow treating these objects much like any variables or numeric arrays. Working within the statistical package R, we introduce a new object-oriented framework based on a new random variable data type that is implicitly represented by simulations.

A few years later we published an updated version of the paper under the title, Manipulating and summarizing posterior simulations using random variable objects. Here’s the background:

In the Bayesian paradigm, unknown quantities have probability distributions and are thus random variables. Observed values are just realizations of random variables, and constants may be thought of as random variables with point mass distributions. In mathematical notation, we deal with objects that are random variables, but in practice these objects are approximated by vectors of numbers, that is, simulations. Consequently, when programming for manipulating simulations of unknown quantities, we must write code to manipulate arrays of numeric constants.

And here’s the challenge:

Arrays of simulations are cumbersome objects to work with. Functions that work with vectors will not in general work with matrices, so special versions of the functions need to be written to accommodate matrices of simulations as arguments. For example, a scalar-valued random variable becomes a vector of simulations, and a random vector becomes a matrix of simulations. . . . The usual approach now is to use loops and vector-matrix computations to manipulate the matrix of posterior simulations. This approach is general but awkward and far from transparent . . .

As part of this effort, Jouni wrote a package in R called “rv” that allows direct manipulation of random variable objects, so for example if alpha and beta are random variables, each a vector of length J, and gamma is a scalar, then you can compute something like delta = (alpha + gamma)/beta, which would be a vector of length J. Internally, alpha, beta, and delta would be stored as S x K arrays, and gamma would be stored as an array of length S, where S is the number of simulation draws in your simulation frame, but the user would be able to work with these without having to keep track of that indexing; it would all be implicit.

The rv package was just a demonstration, but then more recently Paul Bürkner, Jonah Gabry, Matthew Kay, and Aki Vehtari implemented the idea in the “posterior” package in R. They call it rvar: The Random Variable Datatype. I still haven’t integrated rvar() into my Bayesian workflow, but I’d like to do it.

The point I want to make here is that this random variable datatype moves us closer to what I’d call “truly probabilistic programming.”

Here’s what I mean by that.

Stan (and Bugs, PyMC, etc.) are called “probabilistic programming languages,” characterized by Wikipedia as “based on the declarative specification of probabilistic models, for which inference is performed automatically.” Fair enough. In Stan, the variables defined in the parameters block, transformed parameters block, model block, and generated parameters block represent random variables with a joint density that is specified by the Stan program.

But, although this is called a probabilistic program as the term is used, it doesn’t fully feel like probabilistic programming in the sense of allowing me to grab random variables and work with them directly. I can do all that within the Stan program in the generated quantities block, but at a certain remove. Stan and other probabilistic programming languages are set up to run in batch mode: you specify a model and then the inference engine runs and spits out posterior simulations (or some other distributional summary).

To me, a truly probabilistic programming environment would allow me to interactively work with random variables, and to work with them as random variables, not as arrays of simulation draws. I want to be able to multiply two matrices without having to loop through the simulations. Part of this is about clean code, but more generally it’s about workflow. Any mathematical or graphical operations we can do on numbers, we should be able to do with random variables, with the simulations all hiding under the hood. Kind of by analogy to how we can do floating-point math on the computer without (usually) having to worry about how all these digits are being stored.

This will require tools such as rvar() and also some experience with the workflow. The payoff is . . . you could call it “better postprocessing of Bayesian simulations,” but I think that would understate the potential benefits of being able to work directl with uncertainty without that extra array dimension getting in your face at every step.

Survey Statistics: Sampling from a Bayesian Menu

A week ago Andrew wrote about Alan Zaslavsky, who recently passed. Alan’s obituary has information about an upcoming celebration of life.

Alan Mark Zaslavsky Profile Photo

Andrew highlighted Alan’s work on the census. In Sampling from a Bayesian Menu, Alan wrote about objections not only to model-based adjustments for undercount, but the Supreme Court’s ruling in 1999 against even purely “design-based” estimates using sampling for nonresponse followup.

Alan was on the panel who wrote “Sampling for Nonresponse Follow-up: Achieving Adequate Precision at Acceptable Cost”. They explained that after initial response to the census, the bureau conducts nonresponse follow-up on remaining housing units. In the 1990 census, this was massively delayed, costing both money and accuracy. They recommended that the 2000 census should conduct nonresponse follow-up on a random sample of nonresponding housing units for unbiased estimation of the total number of people in all nonresponding housing units. This is what Alan described in Sampling from a Bayesian Menu as the “design-based” approach that was rejected by the Supreme Court in 1999.

Despite this bad (old) news, the paper is fun to read, and will make you hungry.

Constructing a latent-variable model to fit measurement data: A Stan story, part 2

Following up on our post from the other day, we were trying to come up with parameters for the following measurement-error model:

– People have latent a distribution of attractiveness:
latent_attractiveness ~ normal(0, sigma_latent)
– Attractiveness for each person is measured twice, with different mean levels and different levels of added variance:
At time t, observed_attractiveness ~ normal(mu_obs_t + latent_attractiveness, sigma_obs_t), for t = 1, 2
– Attractiveness at each time is then recorded as a discrete variable, rounded to the nearest integer and constrained to fall between 1 and 5: That is, if observed attractiveness is less than 1.5, it is recorded as 1, if observed attractiveness is between 1.5 and 2.5, it is recorded as 2, etc.
– The only information easily accessible is recorded attractiveness binned into three categories: 1 or 2, 3 or 4, and 5. This summary is available for each person at both time points.

Here are the data, from the first two waves of the Add Health survey:

So, here’s the deal. We want to choose five parameters (sigma_latent, mu_obs_1, mu_obs_2, sigma_obs_1, sigma_obs_2) to fit 9 data points. Actually 8 data points because what we’re fitting are the proportions that sum to 1.

This shouldn’t be so hard, right?

Actually, it is kind of hard! At least, it’s hard to get a fit that gets real close to the data table.

1. Trial and error to find parameter values that match the data

I started with trial and error, first computing the mean and sd of the attractiveness ratings for each wave of the data (approximating the three binned levels as 1.5, 3.5, and 5 on the 1-to-5 scale), then setting mu_obs_1 and mu_obs_2 to the mean values and partitioning the variance so that sd_latent and sd_obs are roughly equal. In R:

discretize <- function(a) {
  ifelse(a < 2.5, 1, ifelse(a < 4.5, 2, 3))
}
N_table <- rbind(c(208, 640, 40), c(501, 9879, 464), c(51, 1439, 1432))
N_data <- sum(N_table)
long_data <- array(NA, c(N_data, 2))
long_data[,1] <- rep(c(1,2,3, 1,2,3, 1,2,3), as.vector(N_table))
long_data[,2] <- rep(c(1,1,1, 2,2,2, 3,3,3), as.vector(N_table))
long_data_1to5 <- ifelse(long_data==1, 1.5, ifelse(long_data==2, 3.5, ifelse(long_data==3, 5, NA)))
means <- apply(long_data_1to5, 2, mean)
sds <- apply(long_data_1to5, 2, sd)
mu_obs <- means
sigma_latent <- sqrt(0.5*mean(sds^2))
sigma_obs <- sqrt(sds^2 - sigma_latent^2)

The result:

> print(round(mu_obs, 2))
[1] 3.68 3.59
> print(round(sigma_latent, 2))
[1] 0.54
> print(round(sigma_obs, 2))
[1] 0.61 0.45

I then estimate the probabilities in the 9 cells by simulating a million pairs of observations from this model, first simulating latent attractiveness, then the two observed attractiveness measures, then rounding:

N <- 1e6
y_latent <- rnorm(N, 0, sigma_latent)
y_obs <- array(NA, c(N, 2))
for (j in 1:2) {
  y_obs[,j] <- rnorm(N, mu_obs[j] + y_latent, sigma_obs[j])
}
y_discrete <- discretize(y_obs)

And here's the result:

> print(table(y_discrete[,1], y_discrete[,2]))
         1      2      3
  1  18715  54792    393
  2  41167 674479  55053
  3    653 110776  43972

OK, it's hard to compare this to the data table because the numbers are so big, so let's rescale so that it sums to the number of people in the data:

> print(table(y_discrete[,1], y_discrete[,2])*N_data/N)
              1           2           3
  1  274.249610  802.921968    5.759022
  2  603.261218 9883.815266  806.746662
  3    9.569062 1623.311504  644.365688

This is hard to read so I'll round it:

> print(round(table(y_discrete[,1], y_discrete[,2])*N_data/N))
       1    2    3
  1  274  803    6
  2  603 9884  807
  3   10 1623  644

And, for convenience, let's look again at the data:

> print(N_table)
     [,1] [,2] [,3]
[1,]  208  640   40
[2,]  501 9879  464
[3,]   51 1439 1432

Comparing the cells [1,3] and [3,1] in the simulated table to the observed data, we see that our simulations don't have enough variation between the two measurements. So let's rejigger by decreasing sigma_latent and increasing sigma_obs:

sigma_latent <- sqrt(0.25*mean(sds^2))
sigma_obs <- sqrt(sds^2 - sigma_latent^2)

Simulate again with these new parameter values:

y_latent <- rnorm(N, 0, sigma_latent)
y_obs <- array(NA, c(N, 2))
for (j in 1:2) {
  y_obs[,j] <- rnorm(N, mu_obs[j] + y_latent, sigma_obs[j])
}
y_discrete <- discretize(y_obs)

And here's what we get:

> print(round(table(y_discrete[,1], y_discrete[,2])*N_data/N))
   
       1    2    3
  1  145  896   37
  2  687 9592 1011
  3   54 1827  404

Now the [1,3] and [3,1] entries are basically OK, but [1,1] and [3,3] are too small.

I tried some more tinkering with the five parameters but couldn't get the table to line up. And then I thought: Hey, why not cut out the middleman and just solve the optimization problem directly?

2. Stan program: first try

It goes like this:

data: the observed table, N_table
parameters: the five parameters, sigma_latent, mu_obs, sigma_obs
model: compute table(y_discrete) and compare to N_table

In this model, table(y_discrete)*N_data/N represents E(N_table|parameters), and we were computing this using simulation . . . but you can't simulate random data in the Stan model block! Or we could compute the expectations directly, but these are two-dimensional normal integrals, and there's no formula for that.

So I did a hack. You can't do simulations in the Stan model block, but you can simulate random numbers offline and pass them into the Stan model. Here's our Stan program, table_match.stan:

functions {
  int discretize (real y) {
    if (y < 2.5)
      return 1;
    else if (y > 2.5 && y < 4.5)
      return 2;
    else
      return 3;
  }
}
data {
  array[3, 3] int N_table;
  int N;
}
transformed data {
  int N_data = 0;
  for (j1 in 1:3) {
    for (j2 in 1:3) {
      N_data += N_table[j1,j2];
    }
  }
  vector[N] z_latent;
  matrix[N, 2] z_obs;
  for (n in 1:N){
    z_latent[n] = std_normal_rng();
    for (j in 1:2) {
      z_obs[n, j] = std_normal_rng();
    }
  }
  real a = 1.*N_data/N;
}
parameters {
  vector[2] mu_obs;
  real s_latent;
  vector[2] s_obs;
}
transformed parameters {
  matrix[3,3] N_sim = rep_matrix(0, 3, 3);
  for (n in 1:N){
    real y_latent = s_latent * z_latent[n];
    array[2] int y_discrete;
    for (j in 1:2){
      real y_obs = y_latent + mu_obs[j] + s_obs[j] * z_obs[n,j];
      y_discrete[j] = discretize(y_obs);
    }
    N_sim[y_discrete[1], y_discrete[2]] += 1;
  }
  N_sim = a*N_sim;
}
model {
  mu_obs ~ normal(3,3);
  s_latent ~ exponential(1);
  s_obs ~ exponential(1);
  for (j1 in 1:3) {
    for (j2 in 1:3) {
      N_table[j1, j2] ~ poisson(N_sim[j1, j2]);
    }
  }
}

At the very end we're using the Poisson likelihood to compare the observed data to the model. And we include weak priors on the model parameters to keep everything stable.

We run the program from R:

library("cmdstanr")
table_match <- cmdstan_model("table_match.stan")
table_data <- list(N_table=N_table, N=1000)
fit <- table_match$sample(data=table_data, parallel_chains=4, refresh=0)
print(fit, max_rows=30)

Aaaand . . . it doesn't work:

   variable     mean   median       sd      mad       q5      q95  rhat ess_bulk ess_tail
 lp__       77677.57 77880.76 10570.22 13247.66 63077.85 91926.34  3.66        4        5
 mu_obs[1]      0.24     0.10     0.61     0.51    -0.42     1.22  3.94        4       11
 mu_obs[2]      0.47     0.40     1.64     2.24    -1.47     2.54  3.70        4       11
 s_latent       2.78     1.82     2.52     1.37     0.49     7.00  3.42        4       12
 s_obs[1]       1.84     1.60     1.18     1.08     0.46     3.68  3.47        4       13
 s_obs[2]       1.65     1.70     1.36     1.93     0.18     3.03  3.43        4       11
 N_sim[1,1]  8290.04  8865.67  1305.70   640.92  6096.06  9319.94  5.54        4       NA
 N_sim[2,1]   890.16   593.49   669.06   358.48   351.70  2007.60 32.33        4       NA
 N_sim[3,1]   468.94    80.60   711.48    65.18    14.65  1699.86 13.53        4        4
 N_sim[1,2]  1759.81  1472.73  1368.41  1292.70   219.81  3883.31  5.95        4        4
 N_sim[2,2]   852.42   622.80   655.06   369.34   219.81  1948.98  9.66        4       NA
 N_sim[3,2]   322.47   307.73   251.19   336.75    29.31   644.78  8.22        4        4
 N_sim[1,3]   626.65   256.44   779.88   260.71    14.65  1963.64 18.31        4       NA
 N_sim[2,3]   408.84   300.41   339.12   271.58    58.62   952.51 16.39        4       NA
 N_sim[3,3]  1034.67   381.00  1331.88   304.16    29.31  3326.46 16.98        4       NA

What about Stan in optimize setting?

fit_optimize <- table_match$optimize(data=table_data)

Nope:

Initial log joint probability = 69172.8 
    Iter      log prob        ||dx||      ||grad||       alpha      alpha0  # evals  Notes  
       1       69172.8             0       9.10807    0.001749       0.001       45    
Chain 1 Optimization terminated with error: 
Chain 1   Line search failed to achieve a sufficient decrease, no more progress can be made
Warning: Fitting finished unexpectedly! Use the $output() method for more information.

Damn.

3. Stan program: revision

What went wrong? The above code is mathematically correct, but the discreteness of all these simulations leads to difficulty with the Hamiltonian Monte Carlo. The problem is that, due to the use of fixed error terms and a finite N, continuous changes in the parameters result in jumps in the expected data and thus jumps in the likelihood.

But then I realized something: I can't compute two-dimensional normal integrals in closed form, but one-dimensional normal integrals are trivial. So, instead of passing in the vectors of random numbers z_latent, z_obs[,1], and z_obs[,2], I can just pass in z_latent, and then we can use the normal cdf function in Stan to integrate over z_obs[,1] and z_obs[,2]. This offers two advantages: first, by integrating over two of the three dimensions analytically rather than by simulation, we're computing the cell probabilities more accurately and we don't need such a large N; second, the target function will now be a smoothly continuous function of the parameters, so HMC should work better.

Here's our revised Stan program, table_match_2.stan:

data {
  array[3, 3] int N_table;
  int N;
}
transformed data {
  int N_data = 0;
  for (j1 in 1:3) {
    for (j2 in 1:3) {
      N_data += N_table[j1,j2];
    }
  }
  vector[N] z_latent;
  for (n in 1:N){
    z_latent[n] = std_normal_rng();
  }
  real a = 1.*N_data/N;
}
parameters {
  vector[2] mu_obs;
  real s_latent;
  vector[2] s_obs;
  real sigma;
}
transformed parameters {
  matrix[3,3] N_sim = rep_matrix(0, 3, 3);
  for (n in 1:N){
    real y_latent = s_latent * z_latent[n];
    matrix[3,2] p;
    for (j in 1:2) {
      p[1,j] = normal_cdf(2.5 | y_latent + mu_obs[j], s_obs[j]);
      p[2,j] = normal_cdf(4.5 | y_latent + mu_obs[j], s_obs[j]) - p[1,j];
      p[3,j] = 1 - (p[1,j] + p[2,j]);
    }
    N_sim += p[,1] * p[,2]';
  }
  N_sim = a*N_sim;
}
model {
  mu_obs ~ normal(3,3);
  s_latent ~ exponential(1);
  s_obs ~ exponential(1);
  sigma ~ exponential(1);
  for (j1 in 1:3) {
    for (j2 in 1:3) {
      sqrt(N_table[j1, j2]) ~ normal(sqrt(N_sim[j1, j2]), sigma);
    }
  }
}

You can see from the last line of code that I also changed the likelihood. The Poisson likelihood is appropriate if the model is correct, but it won't be correct; by fitting on the square root scale but including a free parameter, sigma, we're allowing for overdispersion.

We call it from R:

fit_2 <- table_match_2$sample(data=table_data, parallel_chains=4, refresh=0)
print(fit_2, max_rows=30)

Aaahhhh, much better:

   variable    mean  median     sd    mad      q5      q95 rhat ess_bulk ess_tail
 lp__        -25.68  -25.29   2.22   2.08  -29.93   -22.80 1.00     1009     1687
 mu_obs[1]     3.79    3.79   0.08   0.07    3.67     3.92 1.00     2090     2047
 mu_obs[2]     3.66    3.66   0.07   0.06    3.56     3.78 1.00     1762     2092
 s_latent      0.68    0.68   0.06   0.05    0.59     0.77 1.00     2562     1803
 s_obs[1]      0.51    0.51   0.08   0.07    0.39     0.64 1.00     2562     1894
 s_obs[2]      0.27    0.28   0.11   0.10    0.08     0.44 1.00     1791     1139
 sigma         4.22    4.07   1.01   0.93    2.84     6.14 1.00     1511     2172
 N_sim[1,1]  338.69  326.65 114.39 103.68  173.55   539.20 1.00     2433     2009
 N_sim[2,1]  434.37  418.15 164.48 152.14  199.93   722.66 1.00     2775     2271
 N_sim[3,1]    1.63    0.52   3.59   0.70    0.01     6.71 1.00     2207     2454
 N_sim[1,2]  588.17  570.14 193.09 180.59  304.30   926.40 1.00     2580     2098
 N_sim[2,2] 9734.95 9745.35 520.62 488.97 8858.11 10563.91 1.00     3395     2533
 N_sim[3,2] 1637.06 1621.71 322.01 300.94 1134.19  2184.29 1.00     3159     2436
 N_sim[1,3]    0.66    0.13   1.92   0.18    0.00     2.98 1.00     2309     2220
 N_sim[2,3]  595.11  575.31 193.51 175.52  319.79   954.80 1.00     2496     2634
 N_sim[3,3] 1323.36 1298.78 300.80 278.37  863.93  1847.16 1.00     1967     1755

Although, if you look at the expected values in the table (N_sim), it's not so great! The [1,3] and [3,1] values are 0.66 and 1.63, much lower than the data values of 40 and 51.

I think the problem is with the Poisson or square-root likelihood, that it allows relatively large error for small-count cells.

4. Stan program: another revision

So I'll try a new model, this time with a lognormal likelihood. This will go into the file table_match_3.stan. I'll just show you the one line in the model block because that's the only part of the program that's changed:

      log(N_table[j1, j2]) ~ normal(log(N_sim[j1, j2]), sigma);

We call it from R:

fit_3 <- table_match_3$sample(data=table_data, parallel_chains=4, refresh=0)
print(fit_3, max_rows=30)

Which yields:

   variable    mean  median      sd     mad      q5     q95 rhat ess_bulk ess_tail
 lp__         -6.98   -6.42    3.35    3.34  -13.32   -2.51 1.01      339      559
 mu_obs[1]     4.12    4.00    0.59    0.37    3.48    5.25 1.00      819      721
 mu_obs[2]     3.86    3.74    0.52    0.22    3.38    4.89 1.01      761      600
 s_latent      0.82    0.69    0.48    0.22    0.40    1.69 1.01      434      306
 s_obs[1]      0.98    0.95    0.37    0.28    0.46    1.58 1.00     1040      744
 s_obs[2]      0.55    0.51    0.34    0.23    0.09    1.16 1.01      777      833
 sigma         0.84    0.74    0.38    0.30    0.42    1.56 1.01      448      810
 N_sim[1,1]  488.28  286.72  716.36  190.52   91.35 1536.07 1.00     1071      888
 N_sim[2,1]  666.97  552.96  480.97  294.04  220.03 1474.32 1.00     1772     1300
 N_sim[3,1]  115.33   64.10  308.25   42.04   19.43  302.69 1.01     1794     1046
 N_sim[1,2] 1043.18  944.89  607.16  461.48  313.54 2133.92 1.00     1109     1153
 N_sim[2,2] 5820.30 6119.15 2055.18 2028.03 1832.99 8729.56 1.01      432      610
 N_sim[3,2] 2887.52 2773.01 1308.13 1259.89  941.96 5226.20 1.00     1142     1137
 N_sim[1,3]   69.16   36.91  145.99   24.02   12.50  203.99 1.00     1730     1098
 N_sim[2,3] 1139.58  969.93  709.41  479.43  390.12 2416.68 1.00     1478     1611
 N_sim[3,3] 2423.68 1726.31 2045.37 1221.81  495.16 7118.74 1.01      526      635

Or, in optimize setting:

fit_optimize <- table_match$optimize(data=table_data)
print(fit_3_optimize, max_rows=30)
   variable estimate
 lp__           1.62
 mu_obs[1]      3.86
 mu_obs[2]      3.68
 s_latent       0.54
 s_obs[1]       0.82
 s_obs[2]       0.52
 sigma          0.38
 N_sim[1,1]   209.05
 N_sim[2,1]   549.51
 N_sim[3,1]    49.04
 N_sim[1,2]   931.32
 N_sim[2,2]  8175.10
 N_sim[3,2]  2736.90
 N_sim[1,3]    30.44
 N_sim[2,3]   984.07
 N_sim[3,3]   988.56

Not bad! Not perfect---you can see that the [3,3] cell is much too big. But it'll do.

5. Conclusion

The model doesn't quite fit! Maybe it could make sense to try longer-tailed distributions such as the t with low degrees of freedom. But for our original purpose, which is to understand the impact of measurement error on a nonlinear relationship, this will be just fine. Also we've learned something about statistical computing.

Constructing a latent-variable model to fit measurement data: A Stan story, part 1

This simulation is a little different than what came before. For my earlier post I simulated hypothetical future data from the beauty-and-sex-ratio study. For my new post I’m simulating data from a hypothetical strong relationship between two variables. Here I’m entirely focused on the question of what happens to a nonlinear (but monotonic) pattern when independent measurement error is added to the predictor. To make the patterns clear, I will assume a large effect; indeed, I’m only concerned here with the effect size, not its variation.

The one thing I’ll preserve from the previous simulation is the distribution of attractiveness measurements in the sample: 2%, 5%, 45%, 37%, and 11% in the five attractiveness categories.

I want to set up a model where there’s an assumed true nonlinear relationship between some outcome of interest and a continuous underlying latent attractiveness variable.

The nonlinear model isn’t hard to come up with. The hard thing is creating a distribution for the latent attractiveness, under the constraint that it be roughly consistent with the data.

I’ll assume a symmetric model, a normal distribution on the measurement scale. This might seem like a strong assumption but it seems reasonable enough given the data, which have an average that’s between 3 and 4. The tails are asymmetric but that’s just because the scale has 5 as an upper bound.

My first step is to compute the mean and sd of the observed data:

n <- round(2792*c(.02,.05,.45,.37,.11))
mean_ratings <- sum(n*(1:5))/sum(n)
sd_ratings <- sqrt(sum(n*((1:5) - mean_ratings)^2)/sum(n))

These come to 3.5 and 0.83. Assuming random zero-mean measurement error, the latent attractiveness distribution should have the same mean but a lower variance. We should subtract 1/12 to account for the rounding (as this is approximately equivalent to adding an independent uniform(-0.5,0.5) random variable, which has a variance of 1/12) and then more to account for measurement error.

But how much to subtract? For this, we need to make some assumption about variation in the attractiveness measurement. Attractiveness seems pretty subjective to me (also it can vary a lot over time, as we know from those high-school yearbook photos of people who later became movie stars). I gotta assume something here, so let's assume that the standard deviation of the measurements is 0.5. I'm picking this because 0.5 is a large value, but it's not as large as the sd of 0.83 in the data. Indeed, 0.5^2 + 1/12 = 0.33 and 0.83^2 = 0.69, so I'm assuming that about half of the variance in the data is coming from measurement error.

But is 0.5 a reasonable value? To answer that question, it helps to have data.

The data at hand come from wave 3 of the Add Health study. I already downloaded those data awhile ago in preparing my earlier analysis, but I've had difficulty working with the numbers. I can't remember why, but there's no single dataset and no single codebook. It's kind of a mess. I spent a few minutes going through to see if there were any repeated measurements of attractiveness there, but I wasn't sure where to look.

So I googled *reliability of add health attractiveness measure*. I was hoping to find the names of the relevant variables in the survey, and that didn't come up in the search. What did appear was a bunch of research papers on the topic. I looked at a few of them and then came across this one: "Ugly criminals," by Naci Mocan and Erdal Tekin. I'm not so interested in the topic of the paper---I'll leave it to others to decide if its conclusions are reasonably supported by its data---; what's relevant here is that they discuss the Add Health attractiveness measure. Which is indeed how it came up in my search.

They looked at data from respondents whose attractiveness had been recorded in two waves. That's exactly what we need for a reliability analysis:

There's only one mild annoyance here: they pooled categories 1 and 2, and they pooled categories 3 and 4. So we don't have the full 5 x 5 table, only a 3 x 3 collapsing of it.

But we can deal with that. We'll just simulate and see what happens.

First we write a couple of simple functions:

round_and_bound <- function (a, lower=1, upper=5){
  pmin(upper, pmax(lower, round(a)))
}

clumped <- function(a) {
  ifelse(a==1 | a==2, 1, ifelse(a==3 | a==4, 2, ifelse(a==5, 3, NA)))
}

We set up the parameters for the latent data:

mu_obs <- c(3.87, 3.69)
s_latent <- 0.53
s_obs <- c(0.82, 0.52) 

Then we simulate two independent measurements on each of 14654 people---that's the number of cases in the above table:

y_latent <- rnorm(N, 0, s_latent)
y_obs <- array(NA, c(N, 2))
for (j in 1:2) {
  y_obs[,j] <- round_and_bound(rnorm(N, mu_obs[j] + y_latent, s_obs[j]))
}

And then we look at the two margins and the table showing the joint distribution of the two measurements:

print(table(clumped(observed_1)))
print(table(clumped(observed_2)))
print(table(clumped(observed_1), clumped(observed_2)))

I also looked at the unclumped data but I won't bother showing you that here.

Here are the results:

> print(table(clumped(observed_1)))
    1     2     3 
  668 11186  2800 

> print(table(clumped(observed_2)))
    1     2     3 
  723 11221  2710 

> print(table(clumped(observed_1), clumped(observed_2)))
       1    2    3
  1  227  437    4
  2  490 9292 1404
  3    6 1492 1302

These don't quite match the table above. The simulations have not enough "unattractive" people and too many "very attractive." Also they two waves in the simulations are essentially the same (by construction, as we simulated them from the same distribution), but the real data show a few more unattractive people and a lot more very attractive people in wave 1.

There would be a way to set up my simulation to alter its parameters and get the closest possible match to the observed two-way table---I guess it wouldn't be hard to program this in Stan, actually! But here I took the lazy way out and just tinkered with the numbers to get things to work. It took about five tries of playing with the inputs, and eventually I converged on this:

sd_measurement <- 0.5
mu_latent <- 3.8
sd_latent <- 0.67
latent_beauty <- rnorm(n_sim, mu_latent, sd_latent)
observed_1 <- round_and_bound(rnorm(n_sim, latent_beauty, sd_measurement))
observed_2 <- round_and_bound(rnorm(n_sim, latent_beauty - 0.1, sd_measurement*0.6))

As you can see, I hacked the simulations to give the wave 2 measurement a lower mean and lower variance.

Here's the result:

> print(table(clumped(observed_1)))
    1     2     3 
  845 10839  2970 

> print(table(clumped(observed_2)))
    1     2     3 
  731 11852  2071

> print(table(clumped(observed_1), clumped(observed_2)))
       1    2    3
  1  330  514    1
  2  400 9727  712
  3    1 1611 1358

OK, now I have the margins pretty good, but the joint table doesn't have enough people whose measurements shifted between the lowest and highest categories.

I played around some more with the parameters of the model but I couldn't get the counts to line up with the data.

So I bit the bullet and did what I should've done from the start, which was to write a Stan program to find a best fit. That was its own struggle---as is often the case, I learn a lot from these little examples---so I'll devote a separate post to it.

Here's what I ended up using:

mu_obs <- c(3.87, 3.69)
s_latent <- 0.53
s_obs <- c(0.82, 0.52) 
y_latent <- rnorm(N, 0, s_latent)
y_obs <- array(NA, c(N, 2))
for (j in 1:2) {
  y_obs[,j] <- round_and_bound(rnorm(N, mu_obs[j] + y_latent, s_obs[j]))
}

And here's the result, which is still not perfect (as will be discussed in my followup post) but is enough for my goals here:

> for (j in 1:2) print(table(clumped(y_obs[,j])))
   1     2    3 
 1225 9684 3745  

   1     2    3 
 815 11857 1982 

> print(table(clumped(y_obs[,1]), clumped(y_obs[,2])))
       1    2    3
  1  208  990   27
  2  563 8141  980
  3   44 2726  975

Which is far from a perfect match to the actual table of responses from the two waves:

> print(N_table)
     [,1] [,2] [,3]
[1,]  208  640   40
[2,]  501 9879  464
[3,]   51 1439 1432

But it's close enough, as we're just trying to make a general point about attenuation of effects under measurement error.

P.S. For the next story, see Constructing a latent-variable model to fit measurement data: A Stan story, part 2.

Survey Statistics: Times/Siena Polls and Times Voter Trends

Yesterday Andrew wrote about Alan Zaslavsky, who recently passed.

This is typical of his work in that it was innovative, with applied importance, and understated.

As Fan Li quoted, Alan was “the best applied statistician on earth”. I’ll write more Alan stories soon. He was my PhD advisor and hero.

Since it is election day, let’s talk about methods to analyze polls, where Alan’s legacy can’t be overstated. Fan Li mentioned work with Alan on balancing covariates, cited by Huling & Mak (2024) in their work on energy balancing weights, which are used by the Times/Siena Poll. This Survey Statistics series has discussed a few Times/Siena Poll decisions over the last year.

This week, in “The Final Polls Show a Blue Surge. Can We Trust Them?” Nate Cohn compares how the 2026 polls would look without these big changes, and sees they would be on average more than 3 points higher for Democrats.

Last week Andrew wrote about MRP at the NYT. So cool ! Their methodology article says:

The estimates do not report a margin of sampling error because they are not based on a sample of the population. The estimates are derived from multiple models, which are each subject to different kinds of error.

Yes, there are many kinds of error to consider, in “Margin of Error” we discussed how to get an MRP margin of error assuming no nonresponse bias after the MRP adjustments, no measurement error, and no model misspecification. In “Total Margin of Error” we saw that in election polls from 1998 to 2014, Shirani-Mehr et al. found that total survey error is about twice the reported margins of error. Even if you have margins of error to report, visualizing them is challenging (see Gelman and Price 1999 “All maps of parameter estimates are misleading”).

I was curious about the relationship between their MRP methods and their weighting methods. (See “MRPW”, “struggles with equivalent weights”, continued struggles, and “equivalent models, equivalent weights (locally)”, and “structured MRP to smooth survey weights”.) The only mention I found of their weights is:

The polls were joined to the given year’s voter file and reweighted to match the voter file by L2’s modeled race, party, age and interactions thereof, with the original survey weight as the base weight. The adjusted survey weight was used in all subsequent race models.

So they calibrate the base weights to match the voter file, see Lumley 2010 Chapter 7.

It’s been a few months since I’ve blogged about the logit shift, so it is time. (See: “2 flavors of calibration”, 2nd helpings (multinomial outcomes), 3rd helpings (multivariate outcomes), 4th helpings (more on multivariate outcomes), “logit shift and raking”.) The NYT uses a version of this shift:

The resulting individual-level probabilities were adjusted in multiple steps to match the actual election result by precinct. First, the probability that a voter would support a minor party candidate was adjusted to match the minor party proportion of the vote. Second, the probability that a voter would support a major party candidate was adjusted to match a candidate’s major party vote share in the precinct. Finally, the probability that a voter would support the Democratic or Republican candidate was calculated by multiplying the adjusted Democratic and Republican share of the major party vote by the adjusted major party vote share of the precinct.

Presumably they’re doing something like:

  1. E(shift_a(P(major party | X))) = P(major party) solve for a.
  2. Then either:
    1. E(shift_b(P(Dem | major party, X))) = P(Dem | major party) solve for b. Or
    2. E(shift_a(P(major party | X)) * shift_b(P(Dem | major party, X))) = P(Dem) solve for b.

2A isn’t quite right: it implies E(shift_a(P(major party | X))) * E(shift_b(P(Dem | major party, X))) = P(Dem). But we want 2B to hold, and the two are equivalent only if the individual-level probabilities for major party and for Dem given major party are uncorrelated.

It’s hard to write prose to describe something technical. The NYT level of methods transparency is great !

This guy has a transformer-based election forecasting model

Harvey Olden writes:

I’ve developed an election prediction model based on a transformer architecture; I thought you might find it interesting. The model will update its information automatically in the run-up to the midterm elections; you can also click on a state/district to see what information the model is leaning on to make its predictions. You can find an explainer for exactly how it works in the website.

I can’t follow the explanation myself, but that’s on me, that I’ve never actually learned exactly what a transformer is. This is not a boast—I’d be a better statistician if I understood such things—just my honest admission of imperfection.

So, given that, I can’t say much about the above forecast, but I thought it might interest some of you, at least from a methodological perspective. There must be some aspects of forecast uncertainty that are well captured by this model and also some weaknesses, corners of probability space where the model architecture induces artifacts (by analogy to the edge-case absurdities we found in a different sort of forecasting models a few years ago and which made their way into Section 8.1 of our Bayesian Workflow book, under the heading, “Exploring inferences to reveal problems with a model”). I haven’t been following the 2026 races closely enough to know what problems to look for, and I don’t see a Github site or anything else with the model’s data, code, or predictive simulations. But if that’s out there somewhere, then youall can take a look.

R-hat, August 1990

I came up with R-hat when working at Bell Labs in the summer of 1990.

Here’s the story, and below is the first version of the paper, exactly as I wrote it.

First, here are some recent things to read regarding monitoring convergence from iterative simulations:

And now, here’s the original R-hat paper from 1990. I (appropriately) included Rubin as a coauthor, as the idea came about after many long phone conversations, and when I brought up this idea, Rubin picked up on it right away, as it was close to methods he had developed for inference from multiple imputations.

To all:

Here’s the abstract of the work I’ve done this summer. It’s stored in the file,
/fs5/gelman/abstract.bell, and copies of the Figures 1-3 are on Trevor’s desk.
Any comments are of course appreciated; I’m at [email protected].

On the Routine Use of Markov Chains for Simulation

Andrew Gelman and Donald Rubin, 6 August 1990

corrected version: 8 August 1990

1. Simulation

In probability and statistics we can often specify multivariate distributions
many of whose properties we do not fully understand–perhaps, as in the
Ising model of statistical physics, we can write the joint density function, up
to a multiplicative constant that cannot be expressed in closed form.
For an example in statistics, consider the Normal random
effects model in the analysis of variance, which can be
easily placed in a Bayesian framework with a conjugate prior distribution.
All the conditional densities of the resulting posterior distribution
are simple, but marginal densities can only be written in integral form and
can only be calculated approximately. (For details, see Kinderman and Snell
(1980) or Pickard (1987) for the Ising model, and Lindley and Smith (1972)
for the Bayesian random effects model.)

In such cases, we may not even be able to compute marginal moments of the
difficult distribution, let alone more complicated and interesting summaries
that would help us understand a probability model or posterior inference.
When direct methods such as analytic or numerical integration of “nuisance”
parameters are not computationally feasible, we might try Monte Carlo simulation;
in the simplest form, we draw a finite set of independent random samples from our
distribution, and then calculate desired distributional summaries as functions of
the sampled points. The Monte Carlo method is quite general and powerful; it is
easy to calculate arbitrary quantities of interest
such as the expected long-distance correlation in the Ising model or a posterior
95% confidence region for the largest block effect in a random effects model.
Any aspect of the distribution can be approximated to any desired accuracy if
the number of independently sampled points is large enough.
Simulation also has the advantage of flexiblility: once a sample is drawn, it
can be used to learn about any number of different distributional summaries.

2. Markov chain methods

Drawing independent random samples is a wonderful tool that is unfortunately not
available for every distribution; in particular, the Ising model and random
effects posterior distributions mentioned above do not permit direct
simulation. Fortunately, a form of indirect simulation method exists for
any multivariate distribution if we can calculate its joint density
(up to a multiplicative constant) or if we can sample from all its univariate
conditional densities. The first of these methods was introduced by
Metropolis et al. (1953) in the Journal of Chemical Physics. Our work focuses
on a similar and slightly simpler method called the Gibbs sampler by Geman and
Geman (1984) in an article for the IEEE.

Let F(x) be our distribution; the Metropolis algorithm takes a starting (vector)
point x0 and constructs a series x1, x2, . . ., that is a sample from an
ergodic Markov chain whose stationary distribution is F(x). Computer
simulation of the series requires calculation of the density f(x) (up to a
constant). These samples xj are not independent; however, the stationary
distribution of the Markov chain is
correct, so if we take a long enough series, the set of values {x1, . . ., xn}
takes the place of the distribution just as an
independent random sample does (although of course an independent sample
carries more information than a Markov chain sample of the
same length).

The Gibbs sampler is a similar algorithm, which produces a Markov chain that
converges to the desired distribution, this time requiring draws from all the
univariate conditional densities at each iteration.

3. Have we converged yet?

Markov chain simulation methods are attractive for many problems because they
enable us to flexibly summarize intractable multivariate distributions by making
full use of the mathematical structure we do know, using a tool we think we
understand–Monte Carlo simulation. Unfortunately, using a sample of a Markov
chain to estimate a distribution raises an immediate question: how long a series
is needed? After one or two steps, we are almost certainly still too close to
the starting point to hope for unbiased summaries. Asymptotically, the chain is
stationary, and all is OK (with some loss of efficiency compared to independent
samples, as mentioned above).

To obtain a feeling for the practical difficulties, we ran the Gibbs sampler for
2000 steps to simulate a case of the Ising model. To give the minimum of details:
x is a vector of binary variables defined on a 100 by 100 lattice; each step of
the Gibbs sampler took on the order of 10,000 computations; and we summarize
each iterate xj by the sample correlation r on the lattice–a function r(x) that
lies between -1 and 1. Theoretical calculations (Pickard, 1987) show that
under our model–the Ising model with beta = 0.5–the marginal distribution
of r is approximately Gaussian with mean around 0.85 or 0.9 and standard
deviation around 0.01. We’d like to know whether the set {r(x1), . . .,
r(x2000)} from the simulated Markov chain can serve as a substitute for the
marginal distribution of r.

Figure 1 shows the values of r(xj), for j=1 to 2000. (r(x0) = 0, and the first
few values are cut off to improve resolution on the graph.) The Markov chain
seems to have “converged to stationarity” after the thousand or so steps required
to shake off its initial state. How do we know it has converged, though? Figure
2 zooms in of the first 500 steps of the series, whose apparent convergence we
know to be illusory. For comparison we ran the Gibbs
sampler again for 2000 steps, but this time starting at a point x0 for which
r(x0) = 1; Figure 3 displays the series r(xj), which again seems to have
converged nicely. To destroy all illusions about convergence, hold
Figures 1 and 3 up to the light. The two Markov chains have “converged” to
different distributions! We are, of course, still observing transient
behavior.

Interestingly, the means of the series in Figures 1 and 3 differ, but
the variances are roughly equal. We’re not sure why, but it seems to be a
general feature in these Markov chain simulations that the variance converges
before the mean.

All simulations and plots were done using the New S Language:
A Programming Environment for Data Analysis and Graphics.

4. The answer: parallel Markov chains

To restate the general problem: we wish to summarize an intractable
distribution F(x) by running the Gibbs sampler (or a similar method such as the
Metropolis algorithm) until the distribution of the set of Markov chain
iterates is close to F. As shown in the previous section, convergence seems
impossible to monitor from a single finite realization of the Markov chain;
consequently, we follow the implicit suggestion of Figures 1 and 3 and track
several parallel sample paths.

Consider m independent runs of the Gibbs sampler, each of length n, starting
from m different initial states x10, . . ., xm0:

series 1: x11, . . ., x1n
. . .
series m: xm1, . . ., xmn.

Again, we focus attention on a univariate summary, say r(x); we want to
use the observed simulations rij to determine whether the series of r’s are
close to convergence after n steps.
To understand our method, consider the set of series as m blocks, each with
n observations, in the one-way analysis of variance layout (that is, ignore the
time ordering in the series). We will work with the total sum of squares
(with (mn-1) degrees of freedom) and the “within” sum of squares (with
(m-1)(n-1) degrees of freedom).

First assume for simplicity that the starting points of the simulated series
are themselves independent random samples from F(x). (Of course, if this
condition could be obtained in practice,
a Markov chain simulation method would not be
needed.) With independent starting points, all values of any series
are independent of all the values of any other series, and the unconditional
variance of any point rij is just the marginal variance var r under the
distribution F. We can then estimate var r, given the “data matrix” (rij),
by [total SS – (within SS)/m] / ((m-1)n). (Algebraic derivations appear
in the longer version of this article.) Given the assumption of initial
independence, this “between” estimate of variance
(not the same as the usual “between” estimate in ANOVA) is unbiased for finite
series of any length.

In contrast, the estimated variance within the series, (within SS) / ((m-1)(n-1)),
has expectation var r only in the limit as n -> infinity.
For finite series, the expected within mean square increases with n, assuming,
as is likely, that the random variables r(x1), r(x2), . . ., from the Markov
chain are positively correlated. The discrepancy between the two estimates
of var r suggests a test: declare the Markov chain to have converged when
the within mean square is close to the variance estimate between series, with
confidence intervals derived from classical ANOVA theory. Because of the
dependence within blocks, the degrees of freedom of the between and within
estimates are less than (m-1)n and m(n-1), respectively. We can
approximately correct for this information loss (once again, details will be
provided in the longer article).

Once we are close enough to convergence to be satisfied, the variance estimates
and degrees of freedom corrections alluded to above allow us to estimate the
marginal summaries E r, var r, and Normal-theory confidence intervals for our
Monte Carlo approximations. We can run the series longer if more precision
is desired, and can repeat the process to study the marginal distributions of
other parameters (without, of course, having to simulate any new series of x’s).

In practice, the starting points of the parallel series can never be sampled
independently with distribution F(x); the simulated series are thus no longer
stationary for any finite n, formally invalidating the above analysis. We
currently have two strategies designed to make the independence assumption
approximately true. First, we try to pick starting values that are far apart and,
if anything, more dispersed than independent random samples. The m parallel series
should then start far apart and grow closer as they approach stationarity, as in
Figures 1 and 3; since the variance between series declines with n, the
comparison-of-variances test should be conservative. Second, we reduce the
effect of the starting values by crudely throwing away the the first half
of each simulated series until approximate convergence has been reached.
Once again, Figures 1 and 3 illustrate how a few early steps
of the Markov chain can greatly distort estimates of means and variances
within series. We hope that the conservative strategies of starting with
dispersed points and throwing away early simulations will yield confidence
regions that are wider than those obtained by the ideal method, but that
still have good coverage properties.

The idea of comparing parallel simulations is not new; for
example, Fosdick (1959) applied the Metropolis algorithm to the Ising model
by simulating four series independently, from each of two different starting
points. Approximate convergence was declared when the two groups of series
became indistinguishable on the scale of a prechosen error bound.

5. Some references

Ehrman, J. R., Fosdick, L. D., and Handscomb, D. C. (1960).
Computation of order parameters in an Ising lattice by the Monte Carlo method.
{\em Journal of Mathematical Physics} {\bf 1} 547–558.

Fosdick, L. D. (1959). Calculation of order parameters in a binary
alloy by the Monte Carlo method. {\em Physical Review} {\bf 116}, 565–573.

Geman, S., and Geman, D. (1984). Stochastic relaxation, Gibbs
distributions, and the Bayesian restoration of images. {\em IEEE Transactions
on Pattern Analysis and Machine Intelligence} {\bf 6}, 721–741.

Hammersley, J. M., and Handscomb, D. C. (1964), chapter 9. {\em Monte Carlo
Methods}. London: Chapman and Hall.

Kinderman, R., and Snell, J. L. (1980). {\em Markov Random Fields and
their Applications}. Providence, R.I.: American Mathematical Society.

Lindley, D. V., and Smith, A. F. M. (1972). Bayes estimates for the linear
model. {\em Journal of the Royal Statistical Society B} {\bf 34}, 1–41.

Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., and
Teller, E. (1953). Equation of state calculations by fast computing machines.
{\em Journal of Chemical Physics} {\bf 21}, 1087–1092.

Pickard, D. K. (1987). Inference for discrete Markov fields: the
simplest nontrivial case. {\em Journal of the American Statistical Association}
{\bf 82} 90–96.

Ripley, B. D. (1981). {\em Spatial Statistics}, p. 16ff. New York: Wiley.

Tanner, M. A., and Wong, W. H. (1987). The calculation of posterior
distributions by data augmentation. {\em Journal of the American Statistical
Association} {\bf 82}, 528–550.

Bou-Rabee’s breakthrough paper, “Persistence Pays: Square-root condition-number dependence for Metropolis-adjusted kinetic Langevin Monte Carlo …”

This post is from Bob

This one’s a big deal.

Bou-Rabee, Nawaf. 2026. Persistence Pays: Square-root condition-number dependence for Metropolis-adjusted kinetic Langevin Monte Carlo with a non-reversibly updated accept/reject uniform. arXiv 2610.35781.

Abstract: We prove accelerated mixing for a Metropolis-adjusted kinetic Langevin sampler: the OBABO splitting with friction 2 * sqrt(m), adjusted with Neal’s non-reversibly updated uniform, which is redrawn after every epoch of E steps. For targets exp(−U) on ℝ^d with m * I ⪯ ∇^2 U ⪯ L * I and an L_H-Lipschitz Hessian, started from a Gaussian at an approximate minimizer, the chain reaches total variation accuracy ε after Õ(sqrt(κ * d) + sqrt(L_H) * (d/m)^0.75) gradient evaluations, where κ=L/m and Õ hides logarithmic factors. The sqrt(κ) term is necessary, already on Gaussian targets. The proof discretizes Lu’s entropic hypocoercivity by means of an entropy inequality for free transport, so that the relative entropy of the unadjusted chain decays at a rate of order sqrt(m) up to a discretization bias. With the non-reversibly updated uniform, the leading energy errors of velocity Verlet telescope along a path. A coupling argument combines the two. On Bayesian logistic regression posteriors for two standard data sets, which satisfy these assumptions, the gradient cost of the chain with the non-reversibly updated uniform grows roughly like the square root of the condition number at the posterior mode, and that of standard adjusted OBABO roughly like its 3/4 power.

Note the square-root in the condition-number dependence. This is the tightest result we know for a discrete-step, adjusted sampler (i.e., one we can implement as a black-box). The full set of concavity and Lipschitz assumptions are in the abstract above (strongly log concave, Lipschitz in the Hessian). For what it’s worth, Claude (5.5 medium effort) concurs that nobody has proved a result this tight in condition number before.

The scales here get confusing, pardon my pun, so let’s establish some intuition from simple cases (skip this paragraph and the next if you know condition numbers). Suppose we have a multivariate normal distribution. The Hessian (matrix of second partial derivatives) of the negative log density is constant around the density and equal to the inverse of the covariance matrix. In general (i.e., not just for normals) for a point that is log concave (i.e., the Hessian is positive definite), the condition number is the ratio of the largest eigenvalue of that Hessian to the smallest eigenvalue. To simplify even further, suppose the covariance is diagonal, so that Sigma[m,m] represents the variance of variable m and all the off diagonal entries are zero (i.e., zero correlation). In that case, the eigenvalues are just the Sigma[m,m] and the condition number is just the ratio of the largest eigenvalue to the smallest eigenvalue. The problem for sampling with algorithms like random-walk Metropolis, Langevin, or Hamiltonian Monte Carlo, is that their run time is multiplied by the condition number. For a standard normal, where Sigma[m,m] is 1 for every m, the condition number is 1, and that’s the fastest we can get, because condition numbers are >= 1 by construction. That’s why we try to precondition our target posteriors with mass matrixes to make them (or their gradients in the case of Nutpie) look more normal (e.g., with non-centered parameterizations).

Why is posterior exploration time proportional to the condition number? It’s because we have to set the step size to accommodate the direction of highest curvature, then we have to take a number of steps traverse the scale of the direction of lowest curvature. For all of these samplers, traversing a distance takes quadratic time. So the algorithm is quadratic in the ratio of scales, which makes it linear in the condition number.

This is why reducing the condition number is so appealing. Sparse NUTS, from Cole Monnahan, works exceptionally well for mixed-effects models by preconditioning with a sparse Hessian located at the max marginal likelihood estimate (e.g., the estimate produced by lme4 or TMB). Note to Stan devs: We should adapt this for brms through TMB—it’s too model specific for Stan and we don’t have the linear algebra tools we need built into C++.

Why is this paper such a breakthrough? The assumptions on which the guarantee is based are standard in theoretical work, namely that the density must be strictly log concave with Lipschitz-bounded Hessians. Bou-Rabee establishes that generalized Hamiltonian Monte Carlo with one step (aka “kinetic Langevin”) has run time that grows only with the square root of the condition number! This kinetic or generalized part of the algorithm refers to the way momentum is refreshed. Rather than fully refreshing momentum, a new momentum is taken and averaged with the existing momentum at a fixed mixing rate (which could presumably be randomized, but not made dependent on state). The bottom line is that run time for a fixed level of accuracy grows with the ratio of scales (i.e., the square root of the condition) rather than the ratio of squared scales (i.e., the condition number). And unlike something like NUTS or WALNUTS, swapping in a new acceptance probability sequence couldn’t be much easier to implement.

Why is this a big deal? The main obstacle to Stan’s sampling, as I’ve just realized while building Walnuts and Walnutpie and evaluating on a ton of real-world models, is that the condition number remains high in most posteriordb models and models Andrew’s suggested, even after diagonal preconditioning with a mass matrix using either the NUTS or Nutpie divergence target. A ratio of scales as low as 10 will cause a 100-fold slowdown in sampling. That is, if I sample normal(0, diag_matrix([1, 10]’)) in Stan, it’s 100 times slower than if I sample normal(0, diag_matrix[1, 1]). The low-rank and diagonal approach from Nutpie helps here where it’s stable, but so far I haven’t found it to be as stable as the diagonal preconditioned in my evaluations.

The algorithm that Bou-Rabee analyzed was introduced by Radford Neal in the following paper, which I thought I had discussed here before, but can’t find any trace.

Neal, Radford. 2020. Non-reversibly updating a uniform [0,1] value for Metropolis accept/reject decisions. arXiv 2001.11950.

This paper is typical of Neal’s paper, introducing a very simple idea with a profound effect that’s explained so that a beginner can understand it and code it. We used it as a reference for my work with Gilad Turok and Chirag Modi (and also Alex Barnett) on delayed rejection generalized HMC, which I’ve blogged as Multiscale generalized HMC with delayed rejection.

I’m still a bit confused about how the regular condition number works compared to the one Langmore et al. generated for normal targets in HMC, which I blogged about as Condition numbers for HMC and the funnel. Nawaf told me before that Langmore’s work was only for normals, but it still seems relevant.

I better get busy adding this algorithm to Walnutpie. I’d planned to do it at some future date, but it looks like this is probably the sampler we should be using everywhere. Stay tuned for more evaluation.

MRP at NYT

Coincidentally, or maybe not, on the same day that our New York Times contact informed me about their new job opening, Yair points us to this new feature at the NYT website, “Times Voter Trends” at the NYT. Yair writes:

It’s a voter-file-based estimate of how every demographic group voted in every state, with survey models poststratified to the full file and calibrated to precinct results. It’s basically the approach we’ve been running at Catalist for years, which of course grew out of the MRP work you and I did together. Here’s a description of the methodology.

They use gradient boosting instead of a multilevel model [what we’ve called Regularized Prediction and Poststratification — AG], but the overall structure is very similar. It’s great to see these methods going increasingly mainstream.

Here are the relevant research papers:

[2013] Deep interactions with MRP: Election turnout and voting patterns among small electoral subgroups. American Journal of Political Science 57, 762-776. (Yair Ghitza and Andrew Gelman)

[2020] Voter registration databases and MRP: Toward the use of [2020] Voter registration databases and MRP: Toward the use of large scale databases in public opinion research. databases in public opinion research. Political Analysis 28, 507-531. (Yair Ghitza and Andrew Gelman)

My Ph.D. adviser once told us that the true sign of success is when people use your methods without even citing you. That’s when you know the ideas are fully in circulation.

One-year election analytics fellowship at the New York Times

Will Davis writes:

We ended up hiring somebody who had seen the job posting through your blog, and he is fantastic.

I also wanted to let you know that we have a fellowship slot open.

This is a one-year, full-time position to get to be a part of the Election Analytics department at The Times and get to work with the team that produces The Needle, The Times/Siena Poll, our early vote trackers, analytical journalism about elections and, starting this election, Times Voter Trends.

The exact form of this role will depend on the individual’s background. Candidates that are more comfortable writing than coding and want to deepen their technical skills to more easily answer questions themselves and candidates that bring a background as a developer or statistician and want to work on their ability to communicate your ideas in words will be considered equally.

The deadline to apply is Nov. 20, no exceptions.

This looks interesting and important.

A big problem with conventional experimentation or A/B testing is that the treatment effect can vary over time and it can depend on the entire history of the treatment. Usual comparisons miss this point.

Andrea Bronzini points to this article and writes:

I’m working on experimentation tooling and wrote a brief note about a failure mode I keep seeing: “winning” A/B tests often lose uplift after rollout.

My claim is that the typical setup mixes novelty response with steady-state effect because assignment happens after first exposure, and the outcome is time-dependent.

My reply: I think he is identifying a real problem. The problem he identifies is a special case of the issue that the treatment effect can vary over time and it can depend on the entire history of the treatment, and I guess that ultimately the best solution is to model these sources of variation.

I also like this bit from his webpage:

He saw how the industry’s obsession with certainty slowed businesses down… so he decided to fix it. . . .

Confidence ≠ Certainty.
Data is never complete.
And that’s why we need to embrace taking decisions with risk.
Progress belongs to those who act while others wait.

Also relevant is my talk (not yet a paper), It’s About Time.

How to get the most out of Bayesian Data Analysis

Appendix B of our new Bayesian Workflow book is called “How to get the most out of Bayesian Data Analysis”:

Our thinking about Bayesian statistics is summarized in the books Bayesian Data Analysis, third edition (BDA3), by Gelman, Carlin, Stern, Dunson, Vehtari, and Rubin (2013), and Statistical Rethinking: A Bayesian Course with Examples in R and Stan, second edition, by McElreath (2020). There is no point in repeating the material in BDA3 here. Instead we go through it, chapter by chapter, pointing out the parts that should be most helpful for learning Bayesian workflow using Stan.

And here’s the appendix right here for you.

CmdStanR 1.0 release candidate is now available!

Jonah writes:

I’m happy to announce that a release candidate for CmdStanR 1.0 is ready and available for testing! This will be by far the biggest release since the initial release of the package. One of the main changes is to how models are compiled, so we’d like to get people to try it out and provide feedback before we release it. If all goes well, we plan to make the official 1.0 release in a few weeks.

For users of brms, instantiate, and rethinking, there are either releases or branches available that are compatible with the release candidate (see below). If you are a developer of another package that uses CmdStanR and have questions about updating your package please reach out.

Install it from the v1.0 branch on GitHub in a fresh R session:

remotes::install_github("stan-dev/[email protected]")

(or pak::pak(“stan-dev/[email protected]”)). Then check packageVersion(“cmdstanr”). The release candidate should show up as version 0.99.0. The final release will have version 1.0.0 when we merge the v1.0 branch. There is also a version of the CmdStanR website for the release candidate that contains the updated documentation, vignettes, and release notes: R Interface to CmdStan • cmdstanr.

The release candidate requires R 4.0 or later and CmdStan 2.37.0 or later. If your CmdStan is older, install_cmdstan() will install the latest version. . . .

Lots of stuff here that will make Stan run faster and more smoothly. Click on the link for details.

Getting better causal inferences by using more information (my talk at Stanford this coming Wed)

It’s the political economy seminar at Stanford business school, Wed 14 Oct at noon in room M109:

Lagged regression, difference in differences, two way fixed effects, regression discontinuity, placebo controls: these are different methods used when estimating causal effects from panel data. We’re working on a general approach using multilevel regression and poststratification (MRP) that aims to get the best from all these approaches. We demonstrate with a range of examples, including observational studies in economics, political forecasting, and controlled experiments in biology. This is joint work with Jori Korpershoek and others.

Come and ask me some tough questions!

The talk will be pretty open-ended. We have lots of ideas and some successes (for example, the chickens paper) but it’s mostly open questions and promising research directions. Should be fun.

I won’t be talking about this paper or this paper at all—that’ll have to wait until I’m invited to speak in the English department.

Our continuing struggles with the Monster model

tl;dr. We’re still stuck.

It was 30 years ago that Frédéric Bois, Jiming Jiang, and I published our paper on hierarchical modeling for toxicology. It was a successful paper–it’s been cited over 400 times! It won a major award! More important for me was that working on this project gave me a much better understanding of several different areas of Bayesian inference and computation. I think the greatest impact of this paper has been on informing my thinking, giving me a perspective which has then spread through my research articles, textbooks, and software. I don’t know that it our approach is used much in toxicology, as it took a lot of work just for that one example.

The example is a study of the population toxicokinetics of tetrachloroethylene. Here’s the applied paper with details of the model, and here’s the statistics paper with an explanation of how we did the Bayesian modeling and inference.

The data come from an experiment with 6 people, and for each person there is a multi-compartment model set up as a differential equation with about 15 parameters, and then we had a hierarchical model to allow these parameters to vary by person. We did the computation using Gibbs and Metropolis with a differential equation solver in there too. You can check out the above-linked paper to see how we set up priors and checked the fit of the model to data.

Back in 1993 or 1994 or whenever, it took a lot of work to fit the model. Frédéric programmed it in an C program he wrote called mcsim. But finally it did work, the model fit the data and made reasonable predictions, and we published the papers. As I said, it was a lot of effort for just one toxin, but the work served as proof of concept for the use of Bayesian methods for a complicated model that could not be fit using standard approaches given the sparse data that were available.

I put the example in Bayesian Data Analysis, and then eventually I wanted to fit the model in Stan. When using an example for teaching, it’s good to be able to run the code directly, rather than just pointing to graphs in a published paper.

But it wasn’t so easy to fit the model in Stan! It seems that there are some difficulties with identification of the parameters; perhaps this is one of those cases where computation works ok with a crude algorithm (random-walk Metropolis), but then when you switch to a better algorithm (Hamiltonian Monte Carlo), complexities arise. It’s like picking up a rock and seeing all the worms underneath.

We had some discussion of the problem on the Stan Forums a few years ago. As part of that conversation, Charles Margossian wrote:

It has a lot of moving parts: a stiff ODE that is highly sensitive to parameter values, sparse data, a low number of patients (which makes it it difficult to estimate inter-individual variability), hierarchies across multiple parameters, etc. The workflow is complicated by the fact each model fit takes several hours, even after firing up the cluster and parallelizing within chains.

I [Charles] fitted simplifications of the model and got reasonable results. Fixing one or two parameters, or the population variance greatly simplifies the problem. The full model returns divergent transitions and I haven’t found the right parameterization. I tried monolithic centering and non-centering, and things in between. I now suspect the problematic geometry may not be only due to the interaction between population and patient parameters. It’s indeed possible to have a funnel between population parameters, in which case no parameterization can help you. Divergences aside, I don’t trust the estimated parameters, because there are somewhat inconsistent with the priors which were very carefully constructed. Truncating priors, as was done in the original paper, limits our ability to reparameterize the model. When using truncation, I find a lot of the probability mass concentrates at the boundary (note that on the unconstrained scale, you actually have infinite volume near the boundary). All that said, you shouldn’t need to truncate the priors, because the truncation occurs at the tail of the prior distributions.

The original paper didn’t use HMC, so they didn’t have access to diagnostics such as divergent transitions. You can also imagine how an accept-reject sampler will interact differently with a truncated distribution.

To sum up, I agree this would make a very good case study and writing it has been my ambition for some time. But it’s a challenging model to fit, with behaviors I don’t fully understand (yet). There exist other examples of hierarchical ODE models, built and used with Stan, which can be considered, if the goal is to write a case study. But yes, I think we have a lot to learn from the Monster model.

Lots more in that thread, including this plea from me:

I’d be soooo happy if someone could get the Monster model running in Stan. It’s a great example but it would be so much better if it were runnable. Also it’s buggin the hell out of me that we could it just fine using Metropolis 25 years ago but now we’re getting stuck when using a much better algorithm on computers that are a zillion times faster. So I’d really really really like to get this one straightened out. Anyone who can do this, I promise you a free homemade loaf of bread, an advance look at some blog posts 6 months in the future, and pretty much whatever else you want from me.

We’re still not there yet, and I don’t know the full story. The above offer still stands. Here are the data and some code from Charles.

I’m sharing this example for two reasons:

1. I’d still like to fit the model in Stan. Not just to show off Stan, but because if the model is in Stan, it’s portable. Other people can use it for other, similar, problems. It would be a good teaching example (even though now it’s too late for it to be included in the Bayesian Workflow book). And, given that we did have problems with the computing, it would be good to know what it takes to get the model to work.

2. It’s good to have examples of our fallibility. Of course I’ll share the successes (see here) but the struggles are important too.

P.S. to Bob: I hope you appreciated the careful use of capitalization to convey meaning in the title of this post.