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_trainonx_trainandz_train(treatment) with two latent mean functions represented as sums of decision trees: Y = mu(X, pihat) + tau(X, pihat) * Z + errorFor continuous outcomes, the hyperparameters with units are on the scale of the standardized response, see
standardize, while the outputs are on the scale ofy_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 tox_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 inmu_testandtau_test.z_test (
Float32[Array, 'm']|Float32[ndarray, 'm']|Series|None, default:None) – The test treatment assignment (0 or 1). If provided together withx_test, the outcome prediction is stored inyhat_test.pihat_test (
Float32[Array, 'm']|Float32[ndarray, 'm']|Series|None, default:None) – The test propensity scores. Must be passed together withpihat_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 ofnum_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.Nonefor 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 depthd(0-based) is non-terminal isbase / (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. Withpihat_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 intercepttau_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.01for 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 ofy_trainifstandardizeisFalse, and to 0 ifstandardizeisTrue, which are equivalent, since the standardizedy_trainhas mean 0. For binary outcomes, it is set toPhi^-1(mean(y_train)).standardize (
bool, default:True) – Whether to standardizey_traininternally, ignored for binary outcomes. IfFalse, the hyperparameters with units (sigma_scale,sigma_init,leaf_prior_cov_inv_*,tau_0_prior_var,sigma2_leaf_scale_*,offset) are on the scale ofy_traininstead 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 aBinnerinstance, seebartz.Bart.printevery (
int|None, default:100) – The number of iterations between each progress report,Noneto 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 toinit_bcf, overriding the ones computed from the other parameters.
- Raises:
ValueError – If
z_train,z_test, ory_trainfor binary outcomes, has values other than 0 or 1, or if the format ofx_testdoes not matchx_trainformat, or ifz_testorpihat_testis passed withoutx_test, or if only one ofpihat_trainandpihat_testis passed, or if the length ofy_train,z_trainorpihat_traindoes not matchx_train, or the length ofz_testorpihat_testdoes not matchx_test, or ifpihat_trainis passed but excluded from both forests, or ifx_train,x_test,pihat_trainorpihat_testcontains NaN.
- save_npz(path)[source]¶
Save the fitted model to a compressed npz archive.
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_npzin bartz 0.13 load as models that can only predict.
- predict(x_test, *, pihat_test=None)[source]¶
Compute the control mean and the treatment effect at
x_test.- Parameters:
- Returns:
BCFPrediction– The posterior samples atx_test.
- property offset: Float32[Array, ''][source]¶
The prior mean of the prognostic function.
On the scale of
y_traineven ifstandardizeis set, unlike theoffsetargument, 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_testfor 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_testfor 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_testunderz_testfor 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_testunderz_test.Noneunless the outcome is binary andx_testandz_testwere 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 withpihat_train.rho (
float|Float[Array, '']|Float[ndarray, ''], default:0.0) – The correlation in [-1, 1] between the errors ofy0andy1. The data carry no information on it, see [1]. It affects onlydeltainBCFPotentialOutcomes, widening it asrhodecreases.
- Returns:
BCFPotentialOutcomes– The posterior predictive samples atx_test.
References