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 that bartz does not implement “grow-from-root” (XBART), so the stochtree defaults 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 GeneralParams and MeanForestParams for the supported keys in the general_params and mean_forest_params dicts.

Notes

Differences from stochtree:

  • num_gfr has no default and must be set explicitly to 0.

  • The arguments of sample after y_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 most 16; stochtree’s -1 (unbounded depth) sentinel is not accepted.

  • The deprecated general_params['probit_outcome_model'] flag is not accepted; pass outcome_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_weights are 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 (seed 0) 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.

is_sampled()[source]

Return whether sample has been called.

Return type:

bool

sampled: bool

Whether sample has been called.

standardize: bool

Whether the outcome was standardized before fitting.

sample_sigma2_global: bool

Whether the global error variance is sampled (always False for probit binary regression).

probit_outcome_model: bool

Whether the model uses a binary outcome with probit link.

outcome_model: OutcomeModel

Outcome family and link specification used during fitting.

num_gfr: int

Number of grow-from-root iterations (always 0).

num_burnin: int

Number of MCMC burn-in iterations.

num_mcmc: int

Number of retained MCMC iterations per chain.

num_chains: int

Number of independent MCMC chains.

keep_every: int

Thinning factor of the retained MCMC samples.

num_samples: int

Total number of retained posterior samples (num_mcmc * num_chains).

n_train: int

Number of training observations.

n_test: int

Number of test observations (0 if X_test was not supplied).

has_test: bool

Whether X_test was supplied to sample.

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 (0 if not standardized).

y_std: Float32[Array, '']

Standard deviation used to standardize the outcome (1 if not standardized).

has_rfx: bool

Whether the model includes random effects (always False).

include_variance_forest: bool

Whether the model includes a variance forest (always False).

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 None if not sampled.

y_hat_test: Float32[Array, 'm num_samples'] | None

Posterior predictions at the test points if X_test was supplied to sample, else None.

num_covariates: int

Number of covariates after preprocessing, e.g., after one-hot encoding.

include_mean_forest: bool

Whether the model includes a conditional mean forest (always True).

sample_sigma2_leaf: bool

Whether the leaf variance is sampled.

leaf_scale_samples: Float32[Array, 'num_samples'] | None

Posterior samples of the leaf variance, in the standardized outcome scale, or None if 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 length n.

  • X_test (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame | None, default: None) – Optional test covariates; if given, predictions are cached on them in y_hat_test.

  • observation_weights (Float[Array, 'n'] | Float[ndarray, 'n'] | Series | None, default: None) – Not supported, must be None.

  • num_gfr (int) – Number of grow-from-root iterations. Must be set explicitly to 0.

  • 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 of GeneralParams.

  • mean_forest_params (Mapping[str, Any] | None, default: None) – Optional override for the keys of MeanForestParams.

  • bart_kwargs (Mapping[str, Any], default: MappingProxyType({})) – Additional arguments forwarded to bartz.Bart. Use this to set devices and rm_const=False when wrapping sample in jax.jit.

Raises:

NotImplementedError – If num_gfr is non-zero or observation_weights is set.

Return type:

None

Notes

The signature mirrors stochtree.BARTModel.sample, restricted to the arguments bartz supports. This method invokes bartz.Bart under 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' returns Phi(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 sample has not been called yet.

compute_contrast(X_0, X_1, *, type='posterior', scale='linear')[source]

Compute the difference between the predictions at X_1 and at X_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 contrast Phi(eta).

Returns:

Float32[Array, 'm num_samples'] | Float32[Array, 'm'] – The contrast predict(X_1) - predict(X_0).

Raises:

NotSampledError – If sample has 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 in predict.

  • 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 on Phi(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 of predict.

Raises:

NotSampledError – If sample has not been called yet.

sample_posterior_predictive(X, *, num_draws_per_sample=None)[source]

Sample outcomes from the posterior predictive distribution.

Parameters:
  • X (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame) – Covariates with shape (m, p).

  • num_draws_per_sample (int | None, default: None) – Number of draws per posterior sample. If None, it is 1 if there are at least 1000 posterior samples, else enough to get at least 1000 draws per observation.

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 sample has not been called yet.

Notes

The draws are random, and change at each call. Their sequence is determined by general_params['random_seed'].

has_term(term)[source]

Return whether the model includes a term.

Parameters:

term (Literal['mean_forest', 'y_hat', 'all']) – The term to check.

Returns:

bool – True for the terms in the signature, else False.

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') for global_var_samples, 'sigma2_leaf' (alias 'leaf_scale') for leaf_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:
summary()[source]

Print a description of the model and summaries of its posterior samples.

Raises:

NotSampledError – If sample has not been called yet.

Return type:

None