bartz.stochtree.BCFModel

class bartz.stochtree.BCFModel[source]

Bayesian Causal Forests with a stochtree-compatible interface, powered by bartz.

This class mimics stochtree.BCFModel with bartz.bcf.bcf. Like for BARTModel, the stochtree defaults of 0 burnin and 100 saved MCMC iterations are best changed:

m = BCFModel()
m.sample(X, Z, y, pihat, num_gfr=0, num_burnin=1000, num_mcmc=1000)
cate = m.predict(X_new, Z_new, pihat_new, terms='cate', type='mean')

See BCFGeneralParams, PrognosticForestParams, and TreatmentEffectForestParams for the supported keys in the general_params, prognostic_forest_params, and treatment_effect_forest_params dicts.

Notes

The differences from stochtree listed in BARTModel apply, and in addition:

  • The treatment must be binary, coded as 0 / 1.

  • The propensity score is not estimated internally, so propensity_train is required unless general_params['propensity_covariate'] is 'none'.

  • The prior of the adaptive coding weights is truncated to |b| >= 0.01.

  • The output of predict contains only the requested terms.

p_x: int

Number of covariates after preprocessing, e.g., after one-hot encoding, excluding the propensity score.

treatment_dim: int

Number of treatment variables (always 1).

multivariate_treatment: bool

Whether there are multiple treatment variables (always False).

binary_treatment: bool

Whether Z_train has both values 0 and 1.

adaptive_coding: bool

Whether adaptive coding was used.

propensity_covariate: Literal['none', 'prognostic', 'treatment_effect', 'both']

The forests that split on the propensity score.

internal_propensity_model: bool

Whether the propensity score was estimated internally (always False).

sample_tau_0: bool

Whether the treatment effect intercept is sampled.

sample_sigma2_leaf_mu: bool

Whether the leaf variance of the prognostic forest is sampled.

sample_sigma2_leaf_tau: bool

Whether the leaf variance of the treatment effect forest is sampled.

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

Posterior samples of the leaf variance of the prognostic forest, in the standardized outcome scale, or None if not sampled.

is_sampled()[source]

Return whether sample has been called.

Return type:

bool

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

Posterior samples of the leaf variance of the treatment effect forest, in the standardized outcome scale, or None if not sampled.

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.

tau_0_samples: Float32[Array, '1 num_samples'] | None

Posterior samples of the treatment effect intercept, or None if not sampled.

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

Posterior samples of the coding weight of untreated units, or None without adaptive coding.

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

Posterior samples of the coding weight of treated units, or None without adaptive coding.

mu_hat_train: Float32[Array, 'n num_samples']

Posterior samples of the prognostic function at the training points.

tau_hat_train: Float32[Array, 'n num_samples']

Posterior samples of the treatment effect at the training points.

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

Posterior samples of the prognostic function at the test points, or None.

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

Posterior samples of the treatment effect at the test points, or None.

sample(X_train, Z_train, y_train, propensity_train=None, *, X_test=None, Z_test=None, propensity_test=None, observation_weights=None, num_gfr, num_burnin=0, num_mcmc=100, general_params=None, prognostic_forest_params=None, treatment_effect_forest_params=None, bcf_kwargs=MappingProxyType({}))[source]

Fit the model.

Parameters:
  • X_train (Real[Array, 'n p'] | Real[ndarray, 'n p'] | DataFrame) – Training covariates with shape (n, p), like in BARTModel.sample.

  • Z_train (Real[Array, 'n'] | Real[ndarray, 'n'] | Series) – Training treatment assignments of length n, 0 or 1.

  • y_train (Real[Array, 'n'] | Real[ndarray, 'n'] | Series) – Training outcomes of length n.

  • propensity_train (Float[Array, 'n'] | Float[ndarray, 'n'] | Series | None, default: None) – Training propensity scores of length n. Required unless general_params['propensity_covariate'] is 'none', else ignored.

  • 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 mu_hat_test, tau_hat_test, and y_hat_test.

  • Z_test (Real[Array, 'm'] | Real[ndarray, 'm'] | Series | None, default: None) – Test treatment assignments, required with X_test.

  • propensity_test (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None) – Test propensity scores, required with X_test if propensity_train is.

  • 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 BCFGeneralParams.

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

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

  • bcf_kwargs (Mapping[str, Any], default: MappingProxyType({})) – Additional arguments forwarded to bartz.bcf.bcf.

Raises:

NotImplementedError – If num_gfr is non-zero, observation_weights is set, Z_train is not binary, or propensity_train is missing.

Return type:

None

Notes

The signature mirrors stochtree.BCFModel.sample, restricted to the arguments bartz supports. This method invokes bartz.bcf.bcf under the hood.

predict(X, Z, propensity=None, *, type='posterior', terms='all', scale='linear')[source]

Predict at new covariates and treatments.

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

  • Z (Real[Array, 'm'] | Real[ndarray, 'm'] | Series) – New treatment assignments of length m.

  • propensity (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None) – New propensity scores of length m, required if the model uses them, else ignored.

  • 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', 'mu', 'tau', 'prognostic_function', 'cate', 'all'] | Sequence[Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate', 'all']], default: 'all') – One of 'y_hat' for the expected outcome mu + Z * tau, 'mu' or 'prognostic_function' for the prognostic function, 'tau' or 'cate' for the treatment effect, 'all', or a list. With adaptive coding, the prognostic function is the expected outcome at Z = 0.

  • scale (Literal['linear', 'probability'], default: 'linear') – 'linear', or, for probit binary regression, 'probability' to apply Phi to each term.

Returns:

Float32[Array, 'm num_samples'] | Float32[Array, 'm'] | dict[str, Float32[Array, 'm num_samples']] | dict[str, Float32[Array, 'm']] – Either a single jax array (for a single requested term) or a dict keyed by 'y_hat', 'mu_hat', 'tau_hat', 'prognostic_function', 'cate'.

Raises:

NotSampledError – If sample has not been called yet.

compute_contrast(X_0, X_1, Z_0, Z_1, propensity_0=None, propensity_1=None, *, type='posterior', scale='linear')[source]

Compute the difference between the predicted outcomes at X_1, Z_1 and at X_0, Z_0.

Parameters:
  • X_0 (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame)

  • X_1 (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame) – Covariates of the subtracted and of the other predictions, with shape (m, p).

  • Z_0 (Real[Array, 'm'] | Real[ndarray, 'm'] | Series)

  • Z_1 (Real[Array, 'm'] | Real[ndarray, 'm'] | Series) – Treatment assignments of the subtracted and of the other predictions, of length m.

  • propensity_0 (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None)

  • propensity_1 (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None) – Propensity scores of the subtracted and of the other predictions, required if the model uses them, else ignored.

  • 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(y_hat).

Returns:

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

Raises:

NotSampledError – If sample has not been called yet.

compute_posterior_interval(X, Z, propensity=None, *, 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)

  • Z (Real[Array, 'm'] | Real[ndarray, 'm'] | Series)

  • propensity (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None)

  • terms (Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate', 'all'] | Sequence[Literal['y_hat', 'mu', 'tau', 'prognostic_function', 'cate', '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') – Like in predict.

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, Z, propensity=None, *, num_draws_per_sample=None)[source]

Sample outcomes from the posterior predictive distribution.

Parameters:
  • X (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame)

  • Z (Real[Array, 'm'] | Real[ndarray, 'm'] | Series)

  • propensity (Float[Array, 'm'] | Float[ndarray, 'm'] | Series | None, default: None) – Like in predict.

  • 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['y_hat', 'mu', 'tau', 'prognostic_function', 'cate', '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_mu', 'leaf_scale_mu', 'mu_leaf_scale', 'sigma2_leaf_tau', 'leaf_scale_tau', 'tau_leaf_scale', 'adaptive_coding', 'y_hat_train', 'y_hat_test', 'tau_hat_train', 'cate_train', 'tau_hat_test', 'cate_test', 'mu_hat_train', 'prognostic_function_train', 'mu_hat_test', 'prognostic_function_test', 'tau_0', 'treatment_intercept', 'tau_intercept']) – The name of the parameter, see stochtree for the aliases. With 'adaptive_coding', the coding weights of untreated and treated units are stacked along the first axis.

Returns:

Float32[Array, 'num_samples'] | Float32[Array, 'k 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