Conversation
# Conflicts: # NEWS.md
# Conflicts: # NEWS.md
# Conflicts: # NEWS.md
…reference model fits with get_fit()
…the tests with getters
…) error checks into test blocks
…hes to helpers/switches.R
# Conflicts: # NEWS.md # tests/testthat/helpers/expectors.R # tests/testthat/setup.R # tests/testthat/test_as_matrix.R # tests/testthat/test_parallel.R # tests/testthat/test_proj_pred.R # tests/testthat/test_project.R # tests/testthat/test_refmodel.R # tests/testthat/test_setup.R # tests/testthat/test_varsel.R
# Conflicts: # tests/testthat/test_varsel.R
…use mu_offs only for reference models built without projpred.mlvl_proj_ref_new
…rix(), check the rank of the unpenalized part and keep gamm4 in the gamm4 tests
…d a nearly singular group block
…ance, and accept the fixed-basis GAMM fits in the test helper
…lerance of the optimizer
…a for all draws and weight the draws in the shared criteria
…draw-wise closures and report draw-wise fallbacks in the fits at one theta
…and show the full formula in the fallback warning
…mits platform differences
… a compass search where nlminb() stops early
…e rounding noise, and skip repeated evaluations
aloctavodia
reviewed
Dec 4, 2026
| # Columns without variance in the rows with a positive weight (for example a | ||
| # factor level that only a row with weight 0 has) get a coefficient of 0: | ||
| sd2 <- nrow(x) / (nrow(x) - 1) * diag(g_mat) / sum_w | ||
| keep <- sd2 > 1e-12 * max(sd2, 1e-300) |
Collaborator
There was a problem hiding this comment.
Suggested change
| keep <- sd2 > 1e-12 * max(sd2, 1e-300) | |
| keep <- sd2 > 1e-12 * colSums(x_noi^2 * w) / sum_w |
Compare each column's variance against its own weighted mean square rather than max(sd2) so that predictors on small scales are not zeroed out.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
varsel()andcv_varsel()are slow for Gaussian submodels (identity link, also in the latent projection) with smooth terms or group-level terms. projpred fits each projected draw withmgcv::gam(),lme4::lmer()orgamm4::gamm4(). This PR fits all draws of a submodel together:(1 | <group>): one penalized least-squares fit of all draws on a fixed basis, with shared penalty parameters.(x | <group>): one relative covariance factor (thetaof lme4) for all draws. Each draw gets anlmer()orgamm4()object at thistheta.In the examples below, the calls ran 2.7 to 86 times faster (medians; pepper with
nloo = 50: 59 s instead of 85 min).Changes
All fits:
projpred.smooth_fixed_basis = FALSEandprojpred.mlvl_fixed_basis = FALSEselect the per-draw fits of master.projpred.warn_additive_experimental.Additive submodels without group-level terms (
R/smooth_fit.R, classsubfit_smooth):mgcv::smoothCon(absorb.cons = TRUE, modCon = 3)(as in brms) for all rows of the reference model data. The same basis serves all submodels and all LOO folds.search_forward_gauss()ranks smooth terms from the cross-products, after the linear terms of their variables.nlminb()minimizes the GCV score for the shared smoothing parameters. A compass search follows (steps of 2 to 0.25 in each log smoothing parameter), then a restart ofnlminb().nlminb()alone stopped early in flat parts of the score. The convergence check then failed in 11 of 40 seeds of the reference model oftest_smooth_fit.R, and on Windows also in the CI. In the mesquite and body fat calls below, the compass search added at most 4 % to the run times and gave the same rankings.as.matrix()maps the coefficients to the brms or rstanarm basis. The SD of a block is the root mean square of its coefficients in each draw.gam()formo()terms, offsets,gam()arguments in...,regulbelow1e-6and missing projected responses.Random-intercept submodels (
R/mlvl_fixed.R, existing classprojpred_mlvl) and additive submodels with random intercepts (R/gamm_fixed.R, classprojpred_gamm_fixed):regul * var(column), the fits are the REML fits oflmer()andgamm4().sd_*columns ofas.matrix().divmin()removes the rows with weight 0, so lost levels and new levels in LOO CV work as before.init_refmodel()and the LOO CV reuse the latent linear predictors (tworef_predfun()calls fewer).t2()terms, no intercept, more than 500 group levels, a rank-deficient model matrix) go to the fits at onetheta.Other multilevel submodels (
R/slopes_fixed.R):thetaminimizes the REML criterion of lme4 summed over the draws, with one sparse Cholesky factor per value ofthetafor all draws. A floor on the penalized residual sum of squares keepsthetafinite when the submodel reproduces the draws.lmer()orgamm4()object at thistheta, so the existing methods apply (predictions, new levels,as.matrix(), the parallel per-draw loop).sd_*andcor_*columns ofas.matrix(). lme4's sigma timesthetahas no stable value when the submodel nearly reproduces the draws. In VerbAgg, theidSD of(1 | id) + btype + mode + situwas 0.25 from lme4 and 1.21 with this definition (first draw of 20 clusters).mo()terms,lmer()orgamm4()arguments in..., designs that lme4 rejects,projpred.mlvl_fixed_basis = FALSE,projpred.smooth_fixed_basis = FALSE(with smooth terms),projpred.PQL = TRUEandprojpred.gaussian_not_as_generalized = FALSE. A draw whose fit at the sharedthetafails gets its per-draw fit and a warning.repair_re.merMod()andgamm4_re_b()used the covariance matrix of the first term of a grouping variable for all its terms. Now each term (for example(1 | g) + (0 + x | g)) uses its own covariance matrix.Why shared penalty parameters
The KL projection of a Gaussian draw onto a fixed basis is the unpenalized least-squares fit. In simulations (100 data sets per case), submodels that leave out terms predicted new data worse without a penalty, by up to 0.037 log density per observation at n = 46. Without the group-level penalty, the loss was up to 0.024. The shared penalty parameters and the per-draw fits differed by at most 0.0044 (smooth terms) and 0.0018 (random intercepts) per observation. The LOO estimates differed by at most 0.0029 and 0.0033. With Stan reference models (3 cases, 5 data sets each), the full-data rankings of the random-intercept fits and of
lmer()were the same in 15 of 15 data sets. No K-fold elpd difference was below -4 SE.Speed
varsel()cv_varsel(), LOO, validated searcht2(), n = 3443)cv_varsel(), LOOvarsel()(1 | g) + (1 | h), Gaussian and latent Bernoullivarsel(),cv_varsel()s(water), 2 random intercepts, n = 791)cv_varsel(),nloo = 50cv_varsel(), LOO(x1 + x2 | g)+s(z), Gaussiancv_varsel(), K-fold, validated searchgam()orgamm4()convergence and singular-fit warnings (for example 218 against 3 for mesquite, 81 against 0 for bangladesh).lmer()path stopped with an lme4 error in 10 of 20 data sets (K-fold CV). The new fit had no error. On master,cv_varsel()of VerbAgg (lme4::VerbAgg, 7584 observations, latent cumulative) withbtype * mode * situstops with the lme4 error "not positive definite".init_refmodel()stops for the bangladesh model (mo()with smooth and group-level terms). That row ran on a local build that adds this case.Tests
test_smooth_fit.R,test_mlvl_fixed.R,test_gamm_fixed.R,test_slopes_fixed.R. With one draw, the fits equal the REML fits oflmer()andgamm4(), also with weights. With several draws, the coefficients equal a direct penalized solve with the shared parameters. The weights of the draws enter the criteria. The SDs and covariance matrices equal their definitions above. The files also cover predictions for new data and new levels, rows with weight 0, the latent projection, the fallbacks and the convergence warnings.test_search_gauss.R),as.matrix()in the brms and rstanarm bases (test_smooth_basis.R), lost factor levels (test_loo_fold_projection.R), the reuse of the latent linear predictors (test_latent.R), and the per-draw tests, which now set the options toFALSE.theta).NOT_CRAN=trueat the branch head: 804 blocks, 65,982 expectations, 0 failed, 1 skipped, 14 warnings. In CRAN mode, before the merge of Raise five tolerances near machine precision #691 and of the GCV change of this PR: 8,483 expectations, 0 failed, 2 warnings. These warnings are the same as in the runs of Build the shared test objects with getters when a test needs them #688, Turn off gc() and use a free port for the PSOCK workers of the parallel tests #689 and Keep the brms fits of the tests between the GitHub CI runs #690 before their squash merges.This PR was assisted by Claude