Open data and brms code for soil carbon spectroscopy prediction

We just published a paper in the European Journal of Soil Science using Stan to fit a spectroscopy prediction model. Code and data using brms and targets is here.

In this problem the predictor is a spectroscopy scan, e.g. one of the curves in figure 1d:

Each curve consists of 257 points. Partial least squares (PLSR) is the classic approach for this setting, with a lot of machine/deep learning these days. I was curious if a Bayesian regression would do. Turns out it does! And also addresses two important problems: uncertainty quantification and predicting in new groups (“model transfer”) using a multilevel structure.

It’s a textbook multilevel model. To abuse R formula syntax:

log1p(y) ∼ 1 + Z + X +Z : X + (1 + X | farm + field + layer + field:layer)

where y is soil carbon, Z are 4 group-level predictors, X are 64 spectroscopy predictors [1], and farm, field, and layer are the groupings.

The only twist is those 64 spectroscopy predictors and 256 interactions. Since the predictors form a continuous signal, I tried a bunch of interesting things (random walk and GP priors, wavelet transform). In the end I settled for a simple hierarchical shrinkage (see paper and supplement for full priors)!

Let me know if you have any feedback. Spectroscopy is really popular and practical in everything from soil science to crop breeding. I’m hoping this approach can be deployed. Thanks for reading and thank you to the stan and brms developers!

[1] I had to downsample from 257 to 64 to get it to fit in a reasonable amount of time. But I’m guessing/hopeful this was just a side-effect of using brms to code the model. Brms treats each slope as a separate Stan real instead of using a vector.

Thanks for sharing. Bayesian hierarchical models are really great for this kind of regression if the responses aren’t super non-linear.

Is the log1p an attempt to deal with zeros in a log-linear model? Another approach is to just build a zero-inflated or hurdle model, though I have no idea if you can do that in brms.

What target ESS were you aiming for? Most of our users go with our defaults, which are very conservative in terms of number of draws. Usually an ESS of around 100 should be fine for practical applications, as most of the uncertainty is in the posterior variation, and ESS gives you posterior estimates within 1/10th of the posterior variation (in expectation). MCMC is also massively parallelizable if you can run multiple chains in parallel—the expected ESS is proportional to the number of chains (though outliers can disrupt that nice pattern in practice).

Also, is there a way to warm start or start with reduced initialization variance (I don’t know how brms initializes, but Stan’s approach is usually too diffuse in high dimensions)? Most of the time Stan spends is wasted in the first few hundred iterations going from a cold start to the bulk of the probability mass. Something like Nutpie (from PyMC) is much faster at adaptation, especially in harder models, but to use tha you’d have to export the Stan model from brms and plug it into Nutpie, which isn’t going to be something you can then launch on CRAN easily.

Hey @Bob_Carpenter, I’ve thought a bit about both of your points!

log1p(y)

Here y is between 0 and 100% in general but in our dataset there aren’t zeros and the maximum is 5. Like you, I raised an eyebrow at log1p (the 1 is arbitrary) but past models used it so I compared it to more sensible alternatives like log and logit, but log1p worked best (for prediction performance)!

My intuition for this is that \log(y) is too steep for y \approx 0 and log1p(y) removes this behavior, it’s approximately linear near zero. At some point I’d like to try log(a + y) where a is a parameter. Or maybe there is a better family of transforms for this?

ESS and nutpie

I tried nutpie for the first time on this model! (I used nutpieR and I also opened a feature request for brms to add nutpieR as a backend.) It worked great! It was way faster than Stan… but only when I ran long chains :( Which, to your other point, I was only aiming for ESS \approx 200 and stan achieved that with only 200 iterations per chain (so 400 post-warmup draws). With that number of iters, nutpie was a little faster than stan but also had a slightly lower ESS so I called it a tie. I asked @aseyboldt about it here, he hadn’t really tested nutpie with so few iters. So it seems like a situation of

low target ESS → low iters → nutpie no better than stan

Presumably more complicated models have a lower ESS per draw or require a longer warmup (e.g. to avoid divergences) breaking the first arrow. And it’s not clear to me how specific the second arrow is to my model either.

Thanks, @potash. That’s a good point about the linearity of log between 0 and 1 (where it has to pick out the whole negative number line). I’ve been playing around a bit with with softplus(x) = log(1 + exp(x)) as a transform in place of exp(), which itself can be given a kind of location/scale parameterization to change its shape. What’s nice about this is that’s roughly linear through its domain. It’s nicely behaved in that its derivative is an inverse logit and thus lives in (0, 1). Its inverse is inv_softplus(y) = log(1 + exp(y)). Addig the exp(y) means it will be roughly linear in y`.

My experience with Nutpie was that it handily beats Stan for low ESS situations because it’s so much faster to warmup. How many warmup iterations are you using? In all the examples I’ve tried (and that’s around 50 across some of Andrew Gelman’s recent applied work and posteriordb and some of my own models), you can get away with far fewer warmup iterations with Nutpie.

The amount of time warmup is going to take with Nutpie will depend on the model and its curvature. (This is also true of Stan.) If there’s roughly constant curvature, as in a Gaussian, Nutpie flies at warmup because of the use of scores as well as draws which function like control variates (scores aka gradients of log densities, are the basis of many general control variates because they have zero expectation).

Is there a Stan version of your model with .json data somewhere? If so, I wouldn’t mind adding it as a test case. I’m trying to collect more real world tests for the development of Walnutpie (@aseyboldt is graciously helping).

Thanks @Bob_Carpenter , I hope to try some transformations like that at some point.

I’m attaching the stan model (51.8 KB) and data (4.7 MB). I will warn you that, as I mentioned above, the model that brms spits out is extremely non-vectorized and verbose (a lot of trivial/unnecessary transformed parameters).

It would be embarrassingly easy to write this model directly in stan and avoid that. The reasons I used brms are (1) brms was a convenient way to explore a lot of modeling options that I didn’t end up using and (2) I was hoping it would easier for non-stan users to read.

I don’t know how much that is affecting sampling, but I suspect it is the reason compilation takes almost 5 minutes! (Admittedly on an old laptop. See here and here. I don’t mind much since I fit the model many times after compiling once.)

Edit: Forgot to answer, I defaulted to 200 iterations with a 50/50 warm-up and sampling split. That takes about 15 minutes on my current machine (Intel i7-1355U). Oh and I use the “O1” option, though I didn’t confirm that it helps here.

There’s a ... <truncated> in the stan file, looks like something went wrong when you saved the file maybe?

Whoops! Fixed.

OK I rewrote the model in stan directly[1]. The model, JSON data (strip .txt extension after downloading), and R benchmark script are below. I’m running 100/100 iterations (warmup/draws) with default settings (e.g. adapt_delta=0.8). Stan is slower but performs way better:

Sampler adapt_delta Iter Time (s) Divergences max(Rhat) min(bulk-ESS)
Stan 0.8 100/100 310 0[2] 1.08 135
Nutpie 0.8 100/100 185 14 1.44 9
Nutpie 0.95 300/100 284 0 1.51 8

I tried helping nutpie by increasing adapt_delta (i.e. target_accept=0.95) and increasing warm-up to 300. Still faster than Stan (!) and no divergences, but poor Rhat and ESS.

Seems like nutpie is struggling with this model, a potentially interesting example for you @Bob_Carpenter @aseyboldt?

spectroscopy_data2.json.txt (2.7 MB)
manuscript_model4_pred_nc.stan (3.2 KB)
spectroscopy_benchmark.R (571 Bytes)


  1. As predicted, compared to brms, compilation is now a normal 15 seconds (20x faster!). Sampling improvement is more modest, ~20%. Note the data posted here is smaller than my previous post so the example runs faster but exhibits the desired phenomenon. ↩︎

  2. Edited to add: seems I got a little lucky with my stan runs, and occasionally we do get a couple divergences. However, as with nutpie, these can be eliminated with adapt_delta and/or more warm-up, and the good Rhat and ESS remain. ↩︎

Yes, thanks for sharing. And thanks for converting the data to JSON! I’ll add it to my evaluations of Stan, Nutpie, and Walnutpie.

When Nutpie runs into problems, it’s almost always due to initialization. One thing I’d suggest in Stan is initializing with a lower value than uniform(-2, 2) if you’re taking random initializations. In higher dimensions or for complex geometry, the tails an be very non-representative of the curvature where we actually want to sample (in the bulk of the probability mass).

Currently Nutpie is broken for manual initialization for Stan models or I’d suggest trying something more like a warm start from a draw from a previous run.

Thanks for giving me data to match the model so that it was no problem firing this up.

I’m pretty sure the reason this model is slow is that the likelihood is not identified.

  int pos = 1;
  vector[I] intercepts = rep_vector(0, I);
  matrix[I,K] slopes = rep_matrix(to_row_vector(alpha), I);
  for(n in 1:N) {
    vector[M_n[n]] nu1_n = segment(nu1, pos, M_n[n]);
    intercepts = intercepts + nu1_n[m_ni[n]];
    matrix[M_n[n], K] nu_n = nu[pos:(pos+M_n[n] - 1)];
    slopes = slopes + nu_n[m_ni[n]];
    pos = pos + M_n[n];
  }
  y ~ normal(alpha1 + intercepts + rows_dot_product(X, slopes) + Z*gamma1 + XZ*gamma, sigma);
  ...

I’m not entirely sure because of the loop defining the intercepts, but I’m pretty sure given the evidence of low ESS for alpha1 that the problem is that alpha1 + intercepts is not identified because (alpha1 + c) + (intercepts - c) yields the same data distribution. The symmetric way to identify would be to require the intercepts to sum to zero so that you can’t add to them, but I’m not exactly sure what’s going on here with the intercepts being some kind of sum.

Is there a simple explanation of what’s going on with the model?

On my two generations old Mac Studio, I could run 16 chains for 400 warmup and 400 sampling iterations of Nutpie in 160s and in Walnutpie in 195s. But both had a maximum R-hat of around 1.1 and a minimum ESS of around 50 (out of 6400 draws).

P.S. I find it helps to introduce start and end variables as follows.

  int start = 1;
  for (n in 1:N) {
    vector[M_n[n]] nu1_n = segment(nu1, pos, M_n[n]);
    intercepts = intercepts + nu1_n[m_ni[n]];
    slopes = slopes + nu_n[m_ni[n]];
    int end = start + M_n[n];
    matrix[M_n[n], K] nu_n = nu[start:end];
    start = end + 1;
  }

I also find the subscripted naming hard to scan in expressions like nu1_n[m_ni[n]] and anything that could be done to give those more meaningful and less cluttered names would help with readability, even if it was just to shave the _n suffixes off.

Thanks @Bob_Carpenter , really appreciate you looking into this.

This is actually a standard mixed effects regression just with a flexible number of groupings N and some really bad variable names (sorry! details below). It shouldn’t be any less well identified than other mixed effects regressions (unless I coded it wrong). I’m happy to try adding sum_to_zero to both the random intercept and slope deviations. But I’m left wondering:

  1. Why would this model be more of a problem than other multilevel models
  2. More importantly, why does Stan/NUTS sample it fine? Slow perhaps, but very high ESS per iteration.

Here are the details:

The sum over n in 1:N is to be flexible about the number of groupings in the model (N) and allowing them to be arbitrarily nested. For example in R formula syntax if we had intercepts (1|farm + field + layer + layer:field) then N=4. Then m_ni is the group memberships. For example m_{n4} = [3, 1, 2, 5] says that observation 4 belongs to farm 3, field 1, and layer 2, and layer:field 5.

So we sum intercepts (and slopes) from each level of the multilevel structure to get the intercept and slopes for an observation.[1]

Apologies for the bad variable names. alpha1 is the random intercept mean (should be mu_alpha) and nu1_raw are the standardized deviations from that mean and nu1 are the destandardized deviations. It’s a classic non-centered parameterization? The only unique thing is that we have a flexible number of grouping levels (and bad naming) and a lot of predictors. Unless I coded it wrong!

Anyway I’ll try sum_to_zero soon but I feel like your answer isn’t very satisfying because Stan handles the model OK?


  1. Easy place to optimize is the fact that while we have 500 observations, we only have about 54 unique group membership vectors so intercepts and slopes don’t need to have 500 rows, just 54. That would be faster but it wouldn’t change sampling other than speed ↩︎

Below is a model with sum to zero. No noticeable improvement (in stan or nutpie). I also tried a QR decomposition of the 64 predictors to no effect (not attached).

nutpieR apparently supports specifiying inits for stan models. I tried using warm inits from a previous run. That didn’t help either.

Again, stan gives a min(ess_bulk) of over 100 with 4 chains and 100 warmup + 100 draws. Of course, iterations are not everything, and stan is indeed slow (more gradients per iter?). But the real issue is that running nutpie for longer (e.g., going from 100 + 100 to 400 + 400) doesn’t increase ESS. @Bob_Carpenter I think your min(ess_bulk) of 50 was because you ran 16 chains (I am running 4)? It seems the easiest way to get 100+ ESS in nutpie would be to run 32 chains?(!)

I’m OK to give up on this and file it in the (apparently short) list of exceptions to nutpie’s superior performance. I’m a little disappointed because it’s the first model I’ve ever tried in nutpie!

manuscript_model4_pred_nc_sz3.stan (4.3 KB)

I didn’t make any thorough experiments, but from a few quick tests, I can reproduce your results here.
The difference does seem to be the mass matrix target, the purely variance based mass matrix seems to work better than the variance/gradient based one at least in my basic tests.
You can still use nutpie, and just set adaptation="draw_diag" to get it, but then there won’t be that big of a difference between stan and nutpie anymore. It still typically adapts faster early on, but I didn’t check if that makes a difference for your model.
I’ll try to find time to figure out what’s going on here in more detail, thanks for the clear example model though.

Thanks @aseyboldt for exploring! If you have time to go deeper I’d be curious what you learn.

Interestingly, nutpieR doesn’t support adaptation="draw_diag" so I can’t test it at the moment. But I opened a feature request slash I’ll probably just get set up in python at some point.

Independent from the whole sampler comparison, I would be surprised if there wasn’t a way to speed up your model by an order of magnitude or so with a bit of reparametrization.
With the info I have right now I find it a bit tricky to suggest something, because I don’t really know how the predictors are built, and I find the model code a bit hard to follow.
If you can provide a bit more info, I’d be happy to check if I can find something. Probably along the lines of what Bob already mentioned.

Reparameterization is absolutely the way to go if you can. If you have a lot of data and/or a strong prior, the non-centered parameterization you have will be slower than the centered parameterization. Or it might really want an in-between parameterization we don’t really provide an easy way to code.

The sum-to-zero should help with the non-identified varying effects in intercept. I can’t quite tell what’s going on with those. Maybe you need a sum-to-zero matrix if these are interacted terms like, say space and time.

The Stan code could be sped up a bit, but it’s fairly optimal as written. May I ask why there is a loop adding vectors of length I to the intercept term? That’s going to be super slow if I is big. Are these mostly zeros? If not, then I don’t see how there’s any hope of identification, but as I said, I couldn’t really follow what was going on in the likelihood with the summed intercept. Is the model written out in math somewhere that’s easier to follow conceptually?

I’d be inclined to move the transformed parameters into the model block so they’re not saved. I’d also be inclined to eliminate them and reconstruct as they’re being used, unless some of them get used twice. I’d just turn off the generated quantities until the model’s fitting well as they won’t affect the fit.

There’s no need to broadcast alpha1 to a vector. You can just add a scalar alpha1 to the normal distribution statement’s location.

I would try to rename slopes as there are also slopes gamma1 and gamma. I also found it a bit confusing that N is not the number of observations.

Thanks @aseyboldt and @Bob_Carpenter! I will simplify the model in a few ways to isolate where it is giving nutpie trouble and also make it more readable (thanks for your suggestions Bob). Unfortunately I need to turn my attention to other things for a week but I’ll be back :)

I had another look, and it seems claude was able to figure out most of what I didn’t quite get yet.
Here is a version that samples with normal settings in about 20s and seems to converge fine:

I mostly changed a few parametrizations between centered/noncentered, switched to zerosumnormal a few times and used a svd to find a better basis for the nir effects. I also switched to pymc, just because that feels a lot more comfortable to me, I hope people here don’t mind. :-)
I didn’t test this properly though, so if you want to use it, please check that I didn’t mess something up…

Awesome, thanks for working on this! I will need to double check this works with the full model (at first glance you ran it with site_depth=False which would have been True in my model but that seems minor…)

My hunch is that SVD was the trick-- that was next on my list after QR didn’t work. I don’t have much experience with either of those transformations for regression predictors so I’ll be curious to better understand why one might be better than the other. I suspect it has to do with SVD allowing to preserve the hierarchical shrinkage prior on the original scale whereas QR didn’t.

The other two things you mentioned (centered/non-centered and sum_to_zero) I did try, but it’s possible I my code had a mistake or I didn’t do the magic combo.

Thanks again, I will follow up with a post-mortem probably next week…

No worries. The LLMs are geniuses at translation :-).

Also, I just let Walnutpie and Nutpie rip on this problem and if you give them enough iterations, they get to reasonable agreement. Just to report Nutpie, since it’s more stable,

model                      sampler    time_s  max_rhat  min_ess  med_ess  mean_step
spectroscopy/spectroscopy  Walnutpie   328.0     1.035      125     3754     0.0555
spectroscopy/spectroscopy  Nutpie      535.7     1.011      327    40827     0.0392

Here’ a second run with 2K warmup, 4K sampling over 16 chains:

model                      sampler    time_s  max_rhat  min_ess  med_ess  mean_step
spectroscopy/spectroscopy  Walnutpie  3374.7     1.005     1698    83231     0.0279
spectroscopy/spectroscopy  Nutpie      869.5     1.130       45     2740     0.0398

The first is using Walnutpie with Walnuts turned on and the second is running Walnutpie with the Walnuts part turned off (i.e., just Nuts). I’m not sure what happened to Nutpie in the second run—probably a stuck chain, because both Nutpie and Walnutpie arrived at the same mass matrices and roughly the same step sizes. In both runs, I set Walnutpie’s target accept rate to 0.9, whereas Nutpie’s was at the default 0.8. So I’m guessing Nutpie just got stuck in some region of high curvature. I could run again, but it’s clear here that 50 minutes is enough to fit the model as written.

Of course, fitting in 30s with a better parameterization is the way to go.