bartz.stochtree.BCFModel¶
- class bartz.stochtree.BCFModel[source]¶
Bayesian Causal Forests with a
stochtree-compatible interface, powered by bartz.This class mimics
stochtree.BCFModelwithbartz.bcf.bcf. Like forBARTModel, thestochtreedefaults 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, andTreatmentEffectForestParamsfor the supported keys in thegeneral_params,prognostic_forest_params, andtreatment_effect_forest_paramsdicts.Notes
The differences from
stochtreelisted inBARTModelapply, and in addition:The treatment must be binary, coded as 0 / 1.
The propensity score is not estimated internally, so
propensity_trainis required unlessgeneral_params['propensity_covariate']is'none'.The prior of the adaptive coding weights is truncated to
|b| >= 0.01.The output of
predictcontains only the requested terms.
- p_x: int¶
Number of covariates after preprocessing, e.g., after one-hot encoding, excluding the propensity score.
- 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).
- 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
Noneif not sampled.
- 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
Noneif not sampled.
- 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.
- tau_0_samples: Float32[Array, '1 num_samples'] | None¶
Posterior samples of the treatment effect intercept, or
Noneif not sampled.
- b0_samples: Float32[Array, 'num_samples'] | None¶
Posterior samples of the coding weight of untreated units, or
Nonewithout adaptive coding.
- b1_samples: Float32[Array, 'num_samples'] | None¶
Posterior samples of the coding weight of treated units, or
Nonewithout 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 inBARTModel.sample.Z_train (
Real[Array, 'n']|Real[ndarray, 'n']|Series) – Training treatment assignments of lengthn, 0 or 1.y_train (
Real[Array, 'n']|Real[ndarray, 'n']|Series) – Training outcomes of lengthn.propensity_train (
Float[Array, 'n']|Float[ndarray, 'n']|Series|None, default:None) – Training propensity scores of lengthn. Required unlessgeneral_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 inmu_hat_test,tau_hat_test, andy_hat_test.Z_test (
Real[Array, 'm']|Real[ndarray, 'm']|Series|None, default:None) – Test treatment assignments, required withX_test.propensity_test (
Float[Array, 'm']|Float[ndarray, 'm']|Series|None, default:None) – Test propensity scores, required withX_testifpropensity_trainis.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 ofBCFGeneralParams.prognostic_forest_params (
Mapping[str,Any] |None, default:None) – Optional override for the keys ofPrognosticForestParams.treatment_effect_forest_params (
Mapping[str,Any] |None, default:None) – Optional override for the keys ofTreatmentEffectForestParams.bcf_kwargs (
Mapping[str,Any], default:MappingProxyType({})) – Additional arguments forwarded tobartz.bcf.bcf.
- Raises:
NotImplementedError – If
num_gfris non-zero,observation_weightsis set,Z_trainis not binary, orpropensity_trainis missing.- Return type:
Notes
The signature mirrors
stochtree.BCFModel.sample, restricted to the arguments bartz supports. This method invokesbartz.bcf.bcfunder 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 lengthm.propensity (
Float[Array, 'm']|Float[ndarray, 'm']|Series|None, default:None) – New propensity scores of lengthm, 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 outcomemu + 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 atZ = 0.scale (
Literal['linear','probability'], default:'linear') –'linear', or, for probit binary regression,'probability'to applyPhito 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
samplehas 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_1and atX_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 lengthm.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 contrastPhi(y_hat).
- Returns:
Float32[Array, 'm num_samples']|Float32[Array, 'm']– The contrastpredict(X_1, Z_1) - predict(X_0, Z_0)of'y_hat'.- Raises:
NotSampledError – If
samplehas 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 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') – Like inpredict.
- 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, 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 inpredict.num_draws_per_sample (
int|None, default:None) – Number of draws per posterior sample. IfNone, 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
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_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:
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: