bartz.bcf.bcf

class bartz.bcf.bcf(x_train, y_train, z_train, *, pihat_train=None, x_test=None, z_test=None, pihat_test=None, include_pihat_in_mu=True, include_pihat_in_tau=False, num_trees_mu=250, num_trees_tau=100, ndpost=1000, nskip=100, keepevery=1, num_chains=None, k_mu=2.0, k_tau=10.0, sigma_df=3.0, sigma_scale='auto', sigma_init='auto', leaf_prior_cov_inv_mu=None, leaf_prior_cov_inv_tau=None, min_points_per_leaf_mu=5, min_points_per_leaf_tau=5, maxdepth_mu=5, maxdepth_tau=5, base_mu=0.95, power_mu=2.0, base_tau=0.25, power_tau=3.0, varprob_mu=None, varprob_tau=None, tau_0_prior_var=None, sample_intercept=True, adaptive_coding=False, sample_sigma2_leaf_mu=True, sample_sigma2_leaf_tau=False, sigma2_leaf_shape_mu=3.0, sigma2_leaf_shape_tau=3.0, sigma2_leaf_scale_mu=None, sigma2_leaf_scale_tau=None, offset=None, standardize=True, outcome_type='continuous', delta_max=0.9, binner=UniqueQuantileBinner, printevery=100, seed=0, init_kw=MappingProxyType({}))[source]

Bayesian Causal Forests (BCF).

Regress y_train on x_train and z_train (treatment) with two latent mean functions represented as sums of decision trees: Y = mu(X, pihat) + tau(X, pihat) * Z + error

For continuous outcomes, the hyperparameters with units are on the scale of the standardized response, see standardize, while the outputs are on the scale of y_train.

Parameters:
  • x_train (Real[Array, 'n p'] | Real[ndarray, 'n p'] | DataFrame) – The training predictors (confounders/modifiers).

  • y_train (Float32[Array, 'n'] | Float32[ndarray, 'n'] | Series) – The training responses.

  • z_train (Float32[Array, 'n'] | Float32[ndarray, 'n'] | Series) – The binary treatment assignment (0 or 1).

  • pihat_train (Float32[Array, 'n'] | Float32[ndarray, 'n'] | Series | None, default: None) – The estimated propensity scores. If provided, appended to x_train.

  • x_test (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame | None, default: None) – The test predictors. If provided, predictions at these points are computed and stored in mu_test and tau_test.

  • z_test (Float32[Array, 'm'] | Float32[ndarray, 'm'] | Series | None, default: None) – The test treatment assignment (0 or 1). If provided together with x_test, the outcome prediction is stored in yhat_test.

  • pihat_test (Float32[Array, 'm'] | Float32[ndarray, 'm'] | Series | None, default: None) – The test propensity scores. Must be passed together with pihat_train.

  • include_pihat_in_mu (bool, default: True)

  • include_pihat_in_tau (bool, default: False) – Whether to include the propensity scores in the prognostic/treatment effect forest.

  • num_trees_mu (int, default: 250)

  • num_trees_tau (int, default: 100) – The number of trees in the prognostic/treatment effect forest.

  • ndpost (int, default: 1000) – The number of MCMC samples to save, after burn-in, per chain. The posterior samples of all chains are concatenated, for a total of num_chains * ndpost.

  • nskip (int, default: 100) – The number of initial MCMC samples to discard as burn-in, per chain.

  • keepevery (int, default: 1) – The thinning factor for the MCMC samples, after burn-in.

  • num_chains (int | None, default: None) – The number of independent MCMC chains. None for a single chain without an explicit chain axis, which is equivalent to 1.

  • k_mu (float | Float[Array, ''] | Float[ndarray, ''], default: 2.0)

  • k_tau (float | Float[Array, ''] | Float[ndarray, ''], default: 10.0) – Prior parameter k of the prognostic/treatment effect forest.

  • sigma_df (float | Float[Array, ''] | Float[ndarray, ''], default: 3.0) – Prior degrees of freedom for error variance.

  • sigma_scale (float | Float[Array, ''] | Float[ndarray, ''] | Literal['auto'], default: 'auto') – Prior scale of the error standard deviation.

  • sigma_init (float | Float[Array, ''] | Float[ndarray, ''] | Literal['auto'], default: 'auto') – Initial value of the error standard deviation.

  • leaf_prior_cov_inv_mu (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None)

  • leaf_prior_cov_inv_tau (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None) – Custom leaf prior precision of the prognostic/treatment effect forest.

  • min_points_per_leaf_mu (int, default: 5)

  • min_points_per_leaf_tau (int, default: 5) – The minimum number of data points per leaf in the prognostic/treatment effect forest. Both forests count all units, untreated ones included.

  • maxdepth_mu (int, default: 5)

  • maxdepth_tau (int, default: 5) – The maximum depth of the trees in the prognostic/treatment effect forest, with the root at depth 0.

  • base_mu (float | Float[Array, ''] | Float[ndarray, ''], default: 0.95)

  • power_mu (float | Float[Array, ''] | Float[ndarray, ''], default: 2.0)

  • base_tau (float | Float[Array, ''] | Float[ndarray, ''], default: 0.25)

  • power_tau (float | Float[Array, ''] | Float[ndarray, ''], default: 3.0) – Parameters of the prior on tree node generation in the prognostic/treatment effect forest. The probability that a node at depth d (0-based) is non-terminal is base / (1 + d) ** power.

  • varprob_mu (Float[Array, 'p_or_p_plus_1'] | Float[ndarray, 'p_or_p_plus_1'] | None, default: None)

  • varprob_tau (Float[Array, 'p_or_p_plus_1'] | Float[ndarray, 'p_or_p_plus_1'] | None, default: None) – The probability distribution over the predictors for choosing one to split on in the prognostic/treatment effect forest. It does not need to be normalized; zero excludes a predictor from the forest. With pihat_train, the last entry is the one of the propensity score. If not specified, use a uniform distribution.

  • tau_0_prior_var (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None) – Prior variance for global intercept tau_0.

  • sample_intercept (bool, default: True) – Whether to sample a global treatment intercept tau_0.

  • adaptive_coding (bool, default: False) – Whether to use adaptive coding for the treatment effect, i.e., to sample the coding weights of untreated and treated units. Their priors are independent N(0, 1/2), truncated to |b| >= 0.01 for numerical accuracy.

  • sample_sigma2_leaf_mu (bool, default: True)

  • sample_sigma2_leaf_tau (bool, default: False) – Whether to sample the leaf variance of the prognostic/treatment effect forest.

  • sigma2_leaf_shape_mu (float | Float[Array, ''] | Float[ndarray, ''], default: 3.0)

  • sigma2_leaf_shape_tau (float | Float[Array, ''] | Float[ndarray, ''], default: 3.0)

  • sigma2_leaf_scale_mu (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None)

  • sigma2_leaf_scale_tau (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None) – The shape and scale of the inverse gamma prior on the leaf variance of the prognostic/treatment effect forest.

  • offset (float | Float[Array, ''] | Float[ndarray, ''] | None, default: None) – The prior mean of the prognostic function, on the latent probit scale for binary outcomes. If not specified, for continuous outcomes it is set to the mean of y_train if standardize is False, and to 0 if standardize is True, which are equivalent, since the standardized y_train has mean 0. For binary outcomes, it is set to Phi^-1(mean(y_train)).

  • standardize (bool, default: True) – Whether to standardize y_train internally, ignored for binary outcomes. If False, the hyperparameters with units (sigma_scale, sigma_init, leaf_prior_cov_inv_*, tau_0_prior_var, sigma2_leaf_scale_*, offset) are on the scale of y_train instead of the standardized one.

  • outcome_type (Literal['continuous', 'binary'], default: 'continuous') – Either ‘continuous’ or ‘binary’ (probit link).

  • delta_max (float | Float[Array, ''] | Float[ndarray, ''], default: 0.9) – Maximum plausible treatment effect on the probability scale for binary probit models.

  • binner (BinnerFactory, default: UniqueQuantileBinner) – A callable that, given the training predictors and a random key, returns a Binner instance, see bartz.Bart.

  • printevery (int | None, default: 100) – The number of iterations between each progress report, None to disable reporting.

  • seed (int | Key[Array, ''], default: 0) – The seed for the random number generator.

  • init_kw (Mapping[str, Any], default: MappingProxyType({})) – Additional arguments passed to init_bcf, overriding the ones computed from the other parameters.

Raises:

ValueError – If z_train, z_test, or y_train for binary outcomes, has values other than 0 or 1, or if the format of x_test does not match x_train format, or if z_test or pihat_test is passed without x_test, or if only one of pihat_train and pihat_test is passed, or if the length of y_train, z_train or pihat_train does not match x_train, or the length of z_test or pihat_test does not match x_test, or if pihat_train is passed but excluded from both forests, or if x_train, x_test, pihat_train or pihat_test contains NaN.

save_npz(path)[source]

Save the fitted model to a compressed npz archive.

Parameters:

path (str | PathLike) – The file to write to.

Return type:

None

Notes

Files written by a bartz release can be loaded by later releases, but not by earlier ones; files written by development versions may not be.

classmethod load_npz(path)[source]

Load a model saved with save_npz.

Archives written by save_npz in bartz 0.13 load as models that can only predict.

Parameters:

path (str | PathLike) – The file to read from.

Returns:

bcf – The loaded model, on the default device.

predict(x_test, *, pihat_test=None)[source]

Compute the control mean and the treatment effect at x_test.

Parameters:
  • x_test (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame) – The test predictors.

  • pihat_test (Float32[Array, 'm'] | Float32[ndarray, 'm'] | Series | None, default: None) – The test propensity scores, required iff the model was fit with pihat_train.

Returns:

BCFPrediction – The posterior samples at x_test.

property offset: Float32[Array, ''][source]

The prior mean of the prognostic function.

On the scale of y_train even if standardize is set, unlike the offset argument, and on the latent probit scale for binary outcomes.

property sigma_trace: Float32[Array, 'num_samples'][source]

The posterior trace of residual standard deviation on the outcome scale, chains concatenated.

property mu_test: Float32[Array, 'num_samples m'] | None[source]

The control mean at x_test for each MCMC iteration.

On the latent probit scale for binary outcomes.

property tau_test: Float32[Array, 'num_samples m'] | None[source]

The treatment effect at x_test for each MCMC iteration.

On the latent probit scale for binary outcomes.

property yhat_test: Float32[Array, 'num_samples m'] | None[source]

The expected outcome at x_test under z_test for each MCMC iteration.

On the latent probit scale for binary outcomes; see prob_test.

property prob_test: Float32[Array, 'num_samples m'] | None[source]

The probability of y being True at x_test under z_test.

None unless the outcome is binary and x_test and z_test were passed to the constructor.

predict_potential_outcomes(x_test, *, key, pihat_test=None, rho=0.0)[source]

Sample joint posterior predictive potential outcomes Y(0), Y(1), and “lift” Y(1) - Y(0).

Parameters:
  • x_test (Real[Array, 'm p'] | Real[ndarray, 'm p'] | DataFrame) – The test predictors.

  • key (int | Key[Array, '']) – A jax random key or an integer seed for sampling the errors.

  • pihat_test (Float32[Array, 'm'] | Float32[ndarray, 'm'] | Series | None, default: None) – The test propensity scores, required iff the model was fit with pihat_train.

  • rho (float | Float[Array, ''] | Float[ndarray, ''], default: 0.0) – The correlation in [-1, 1] between the errors of y0 and y1. The data carry no information on it, see [1]. It affects only delta in BCFPotentialOutcomes, widening it as rho decreases.

Returns:

BCFPotentialOutcomes – The posterior predictive samples at x_test.

References