bartz.stochtree.BARTModel¶
- class bartz.stochtree.BARTModel[source]¶
BART model with a
stochtree-compatible interface, powered by bartz.This class mimics
stochtree.BARTModel. The main difference is thatbartzdoes not implement “grow-from-root” (XBART), so thestochtreedefaults of 0 burnin and 100 saved MCMC iterations are best changed:m = BARTModel() m.sample(X_train=X, y_train=y, X_test=X_test, num_gfr=0, num_burnin=1000, num_mcmc=1000) yhat = m.predict(X_new, terms='y_hat', type='mean')
See
GeneralParamsandMeanForestParamsfor the supported keys in thegeneral_paramsandmean_forest_paramsdicts.Notes
Differences from
stochtree:num_gfrhas no default and must be set explicitly to0.The arguments of
sampleaftery_train, and of the other methods after the covariates, are keyword-only, because some of stochtree’s positional arguments are not supported.mean_forest_params['max_depth']must be a non-negative integer at most16; stochtree’s-1(unbounded depth) sentinel is not accepted.The deprecated
general_params['probit_outcome_model']flag is not accepted; passoutcome_model=OutcomeModel('binary', 'probit')instead.general_params['cutpoint_grid_size']is not accepted; bartz uses a fixed grid of 256 evenly-spaced bins per predictor. stochtree only uses this parameter for the GFR sampler, which bartz does not support.Leaf-basis regression, random effects, heteroskedastic variance forests, and warm-starting from a previous model are not supported.
observation_weightsare not supported, because as of stochtree 0.4.5 they do not work as documented, so there is no stochtree behavior to mimic.bartz uses single-precision floats, so outputs differ from stochtree at the float32 precision level.
general_params['random_seed']defaults to deterministic behavior (seed0) when unset, whereas stochtree draws a random seed. This is intentional, to make repeated fits reproducible by default.
References
Herren, A., Hahn, P. R., Murray, J., Carvalho, C. (2026). “StochTree: BART-based modeling in R and Python”. arXiv:2512.12051.
- sample_sigma2_global: bool¶
Whether the global error variance is sampled (always
Falsefor probit binary regression).
- outcome_model: OutcomeModel¶
Outcome family and link specification used during fitting.
- sigma2_init: float | Float[Array, ''] | Float[ndarray, '']¶
Starting value of the global error variance actually used to seed the chain.
- y_bar: Float32[Array, '']¶
Mean used to standardize the outcome (
0if not standardized).
- y_std: Float32[Array, '']¶
Standard deviation used to standardize the outcome (
1if not standardized).
- y_hat_train: Float32[Array, 'n num_samples']¶
Posterior predictions at the training points, in the original outcome scale.
- global_var_samples: Float32[Array, 'num_samples'] | None¶
Posterior samples of the global error variance, or
Noneif not sampled.
- y_hat_test: Float32[Array, 'm num_samples'] | None¶
Posterior predictions at the test points if
X_testwas supplied tosample, elseNone.
- leaf_scale_samples: Float32[Array, 'num_samples'] | None¶
Posterior samples of the leaf variance, in the standardized outcome scale, or
Noneif not sampled.
- sample(X_train, y_train, *, X_test=None, observation_weights=None, num_gfr, num_burnin=0, num_mcmc=100, general_params=None, mean_forest_params=None, bart_kwargs=MappingProxyType({}))[source]¶
Fit the model.
- Parameters:
X_train (
Real[Array, 'n p']|Real[ndarray, 'n p']|DataFrame) – Training covariates with shape(n, p). Any eager dataframe supported by narwhals (e.g., pandas, polars, pyarrow) is accepted, with categorical columns encoded like in stochtree.y_train (
Real[Array, 'n']|Real[ndarray, 'n']|Series) – Training outcomes of lengthn.X_test (
Real[Array, 'm p']|Real[ndarray, 'm p']|DataFrame|None, default:None) – Optional test covariates; if given, predictions are cached on them iny_hat_test.observation_weights (
Float[Array, 'n']|Float[ndarray, 'n']|Series|None, default:None) – Not supported, must beNone.num_gfr (
int) – Number of grow-from-root iterations. Must be set explicitly to0.num_burnin (
int, default:0) – Number of MCMC burn-in iterations. Recommended to set it to 1000.num_mcmc (
int, default:100) – Number of retained MCMC iterations per chain. Recommended to set it to 1000.general_params (
Mapping[str,Any] |None, default:None) – Optional override for the keys ofGeneralParams.mean_forest_params (
Mapping[str,Any] |None, default:None) – Optional override for the keys ofMeanForestParams.bart_kwargs (
Mapping[str,Any], default:MappingProxyType({})) – Additional arguments forwarded tobartz.Bart. Use this to setdevicesandrm_const=Falsewhen wrappingsampleinjax.jit.
- Raises:
NotImplementedError – If
num_gfris non-zero orobservation_weightsis set.- Return type:
Notes
The signature mirrors
stochtree.BARTModel.sample, restricted to the arguments bartz supports. This method invokesbartz.Bartunder the hood.
- predict(X, *, type='posterior', terms='all', scale='linear')[source]¶
Predict at new covariates.
- Parameters:
X (
Real[Array, 'm p']|Real[ndarray, 'm p']|DataFrame) – New covariates with shape(m, p).type (
Literal['posterior','mean'], default:'posterior') –'posterior'returns one prediction per posterior sample, with shape(m, num_samples).'mean'averages the posterior samples, returning a vector of shape(m,).terms (
Literal['y_hat','mean_forest','all'] |Sequence[Literal['y_hat','mean_forest','all']], default:'all') – One of'y_hat','mean_forest','all', or a list. Since random effects and a variance forest are not supported,'y_hat'and'mean_forest'produce the same result.scale (
Literal['linear','probability','class'], default:'linear') – For probit binary regression:'linear'returns the eta values,'probability'returnsPhi(eta),'class'returns 0 / 1. Only'linear'is valid for continuous outcomes.
- Returns:
Shaped[Array, 'm num_samples']|Shaped[Array, 'm']|dict[str,Shaped[Array, 'm num_samples']] |dict[str,Shaped[Array, 'm']] – Either a single jax array (for a single requested term) or a dict keyed by term name.- Raises:
NotSampledError – If
samplehas not been called yet.
- compute_contrast(X_0, X_1, *, type='posterior', scale='linear')[source]¶
Compute the difference between the predictions at
X_1and atX_0.- Parameters:
X_0 (
Real[Array, 'm p']|Real[ndarray, 'm p']|DataFrame) – Covariates of the subtracted predictions, with shape(m, p).X_1 (
Real[Array, 'm p']|Real[ndarray, 'm p']|DataFrame) – Covariates of the other predictions, with shape(m, p).type (
Literal['posterior','mean'], default:'posterior') –'posterior'returns one contrast per posterior sample, with shape(m, num_samples).'mean'averages them, returning a vector of shape(m,).scale (
Literal['linear','probability'], default:'linear') –'linear', or, for probit binary regression,'probability'to contrastPhi(eta).
- Returns:
Float32[Array, 'm num_samples']|Float32[Array, 'm']– The contrastpredict(X_1) - predict(X_0).- Raises:
NotSampledError – If
samplehas not been called yet.
- compute_posterior_interval(X, *, terms='all', level=0.95, scale='linear')[source]¶
Compute equal-tailed posterior credible intervals of the predictions.
- Parameters:
X (
Real[Array, 'm p']|Real[ndarray, 'm p']|DataFrame) – Covariates with shape(m, p).terms (
Literal['y_hat','mean_forest','all'] |Sequence[Literal['y_hat','mean_forest','all']], default:'all') – Like inpredict.level (
float|Float[Array, '']|Float[ndarray, ''], default:0.95) – Posterior probability of the interval, between 0 and 1.scale (
Literal['linear','probability'], default:'linear') –'linear', or, for probit binary regression,'probability'for intervals onPhi(eta).
- Returns:
dict[str,Float32[Array, 'm']] |dict[str,dict[str,Float32[Array, 'm']]] – A dict with keys'lower'and'upper', or, for multiple terms, a dict of such dicts keyed like the output ofpredict.- Raises:
NotSampledError – If
samplehas not been called yet.
- sample_posterior_predictive(X, *, num_draws_per_sample=None)[source]¶
Sample outcomes from the posterior predictive distribution.
- Parameters:
- Returns:
Real[Array, 'm num_samples']|Real[Array, 'm num_samples num_draws_per_sample']– The draws, with shape(m, num_samples)if there is one draw per sample, else(m, num_samples, num_draws_per_sample).- Raises:
NotSampledError – If
samplehas not been called yet.
Notes
The draws are random, and change at each call. Their sequence is determined by
general_params['random_seed'].
- extract_parameter(term)[source]¶
Return the posterior samples of a parameter by name.
- Parameters:
term (
Literal['sigma2','global_error_scale','sigma2_global','sigma2_leaf','leaf_scale','y_hat_train','y_hat_test']) –'sigma2'(alias'global_error_scale'or'sigma2_global') forglobal_var_samples,'sigma2_leaf'(alias'leaf_scale') forleaf_scale_samples,'y_hat_train', or'y_hat_test'.- Returns:
Float32[Array, 'num_samples']|Float32[Array, 'n num_samples']– The samples, indexed by the last axis.- Raises:
NotSampledError – If
samplehas not been called yet.ValueError – If
termis not valid or the model does not have it.
- summary()[source]¶
Print a description of the model and summaries of its posterior samples.
- Raises:
NotSampledError – If
samplehas not been called yet.- Return type: