library(stochtree)
set.seed(42)Observation Weights and Prior Interactions
Both bart() / BARTModel and bcf() / BCFModel accept an optional vector of non-negative observation_weights \(w = (w_1, \dots, w_n)\) on the training data. Because Bayesian tree ensembles regularize splits, leaf parameters, and error variances jointly through priors, observation weights interact with the model in subtler ways than in ordinary weighted least squares.
This vignette explains:
- What
observation_weightsmean statistically (and how they differ from duplicating rows). - How weights interact with priors on \(\sigma^2\), leaf scale \(\sigma_\mu^2\), and probit links — and when to normalize weights to mean \(1\).
- Zero weights (\(w_i = 0\)) for holdout masking and prior predictive sampling.
- Low-level API note: precision weights \(w_i\) vs. C++ variance multipliers \(v_i = 1 / w_i\).
Statistical Meaning of observation_weights
Continuous Outcomes (Gaussian Likelihood)
For continuous outcomes (OutcomeModel(outcome = "continuous", link = "identity")), observation_weights \(w_i \ge 0\) act as precision (inverse-variance) multipliers in the Gaussian likelihood:
\[ y_i \mid \eta_i, \sigma^2 \;\sim\; \mathcal{N}\!\left(\eta_i,\; \frac{\sigma^2}{w_i}\right), \qquad i = 1, \dots, n, \]
where \(\eta_i\) is the combined conditional mean (mean/prognostic/treatment forests, additive random effects, and parametric BCF terms). Up to additive constants independent of \((\eta, \sigma^2)\), observation \(i\) contributes to the log-likelihood as:
\[ \ell_i(\eta_i, \sigma^2) \;=\; -\frac{\mathbb{I}(w_i > 0)}{2}\log(\sigma^2) \;-\; \frac{w_i\,(y_i - \eta_i)^2}{2\sigma^2}. \]
- Larger \(w_i\) \(\implies\) smaller noise variance \(\sigma^2 / w_i\) (higher precision, stronger pull on tree splits, leaf means, random effects, and BCF treatment parameters).
- \(w_i = 1\) for all \(i\) reproduces unweighted BART/BCF identically.
- \(w_i = 0\) assigns infinite noise variance (zero precision), so observation \(i\) contributes nothing to the likelihood.
Common use cases include:
- Cell-averaged / grouped outcomes: If \(y_i\) is the average of \(n_i\) independent micro-observations with common variance \(\sigma^2\), then \(\operatorname{Var}(y_i \mid \eta_i) = \sigma^2 / n_i\), so \(w_i = n_i\) is exact.
- Known relative heteroskedasticity: If observation \(i\) has known relative error variance \(s_i^2\), set \(w_i = 1 / s_i^2\).
- Survey / inverse-probability weights: Pseudo-likelihood case weights (see normalization rules below).
While both multiply \((y_i - \eta_i)^2\) by \(k\) in the Gaussian exponent, they differ in three ways:
- Error variance degrees of freedom: Duplicating a row \(k\) times increases the sample count by \(k\) (adding \(k / 2\) to the inverse-gamma shape of \(\sigma^2\)). Setting \(w_i = k\) represents one higher-precision observation (adding \(1 / 2\) to the shape of \(\sigma^2\)).
- Tree structural rules:
min_samples_leafcounts the number of rows in a leaf, not \(\sum_{i \in \ell} w_i\), and candidate split cutpoints depend on the rows ofX_train. - Outcome standardization:
y_barandy_std(whenstandardize = TRUE) are computed across the unweighted rows ofy_train.
Binary Outcomes (Probit Link)
For binary probit models (OutcomeModel(outcome = "binary", link = "probit")), global \(\sigma^2 \equiv 1\) is fixed for identifiability, and observation_weights scale the variance of the Albert and Chib (1993) latent normal utility \(z_i\):
\[ z_i = \eta_i + \epsilon_i, \qquad \epsilon_i \;\sim\; \mathcal{N}\!\left(0,\; \frac{1}{w_i}\right), \qquad y_i = \mathbb{I}(z_i > 0). \]
Marginalizing out \(z_i\), a weighted training observation has response probability \(\Pr(y_i = 1 \mid \eta_i, w_i) = \Phi(\sqrt{w_i}\,\eta_i)\) (a heteroskedastic probit model, rather than a frequency-weighted log-likelihood \(w_i \log \Phi(\eta_i)\)). At prediction time on new data, predicting on the probability scale evaluates the baseline link \(\Phi(\eta(x))\).
How Weights Interact With Priors (and When to Normalize)
In stochtree, constant-leaf trees place an independent normal prior on each leaf parameter:
\[ \mu_\ell \;\sim\; \mathcal{N}(0, \sigma_\mu^2), \qquad \sigma^2 \;\sim\; \text{IG}(a, b). \]
Notice that \(\sigma_\mu^2\) is not multiplied by \(\sigma^2\) in the prior. In leaf \(\ell\) with partial residuals \(r_i\), let \(S_{w,\ell} = \sum_{i \in \ell} w_i\) and \(S_{rw,\ell} = \sum_{i \in \ell} w_i r_i\). Both the leaf posterior shrinkage and the split marginal likelihood penalty depend on the effective leaf precision ratio:
\[ \Lambda_\ell \;=\; \frac{\sigma_\mu^2}{\sigma^2}\,S_{w,\ell} \;=\; \sigma_\mu^2 \sum_{i \in \ell} \frac{w_i}{\sigma^2}, \]
via:
\[ \mu_\ell \mid - \;\sim\; \mathcal{N}\!\left(\frac{\Lambda_\ell}{1 + \Lambda_\ell}\,\frac{S_{rw,\ell}}{S_{w,\ell}},\; \frac{\sigma_\mu^2}{1 + \Lambda_\ell}\right), \]
\[ \log p(r_\ell \mid T, \sigma^2, \sigma_\mu^2) \;=\; \text{const} - \frac{1}{2}\log(1 + \Lambda_\ell) + \frac{\sigma_\mu^2\, S_{rw,\ell}^2}{2\sigma^2\left(\sigma^2 + \sigma_\mu^2 S_{w,\ell}\right)}. \]
Meanwhile, letting \(I_+ = \{i : w_i > 0\}\) and \(n_+ = |I_+|\), the full conditional for \(\sigma^2\) is:
\[ \sigma^2 \mid - \;\sim\; \text{IG}\!\left(a + \frac{n_+}{2},\; b + \frac{1}{2}\sum_{i \in I_+} w_i\,(y_i - \eta_i)^2\right). \]
This creates a sharp distinction when weights are multiplied by an overall constant \(c > 0\) (for example, raw survey weights summing to a population total \(N = 10^6\) instead of sample size \(n\)):
| Model Configuration | Effect of Rescaling \(w_i \mapsto c \, w_i\) | Recommendation |
|---|---|---|
Continuous, default Jeffreys’ prior (a = 0, b = 0, sample_sigma2_global = TRUE) |
Scale-invariant after burn-in: \(\sum (c w_i) e_i^2\) rescales \(\sigma^2\) draws by \(c\), so \(w_i / \sigma^2\) and \(\Lambda_\ell\) stay invariant. (Only iteration-0 sigma2_global_init / sigma2_init is unscaled unless specified.) |
Raw scale works (e.g., cell counts \(w_i = n_i\)), though normalizing \(\bar{w}_+ = 1\) keeps \(\sigma^2\) interpretable on the outcome variance scale. |
Continuous, calibrated / proper \(\sigma^2\) prior (a > 0, b > 0) |
Scale-sensitive: prior scale \(b\) anchors \(\sigma^2\) to unit-weight residuals; large \(c\) inflates \(w_i / \sigma^2\) unless \(b\) is also multiplied by \(c\). | Normalize weights to mean \(1\) (\(w_i \leftarrow w_i / \bar{w}_+\)), or multiply sigma2_global_scale and sigma2_global_init (or sigma2_init in Python BARTModel) by \(\bar{w}_+\). |
Continuous, fixed \(\sigma^2\) (sample_sigma2_global = FALSE) |
Scale-sensitive: \(\sigma^2\) cannot adapt, so \(c > 1\) directly inflates \(\Lambda_\ell\) by \(c\) (under-regularizing / overfitting trees). | Use exact inverse-variance weights \(w_i = \sigma^2 / \operatorname{Var}(y_i)\), or normalize relative weights to mean \(1\). |
Binary Probit (link = "probit") |
Scale-sensitive: \(\sigma^2 \equiv 1\) is fixed and \(\Pr(y_i = 1 \mid \eta_i, w_i) = \Phi(\sqrt{w_i}\,\eta_i)\), so \(c\) rescales the link slope by \(\sqrt{c}\) relative to \(\sigma_\mu^2\). | Normalize relative weights to mean \(1\) unless \(1/w_i\) represents a literal latent noise variance. |
If your weights express relative observation importance rather than known physical precision counts, normalize positive weights to mean \(1\) before fitting (w[w > 0] <- w[w > 0] / mean(w[w > 0]) in R, or w[w > 0] /= w[w > 0].mean() in Python). This ensures default sigma2_global_init / sigma2_init, calibrated sigma2_global_scale, fixed-\(\sigma^2\) models, and probit priors all operate on their intended unit scale.
Standardization and Default Hyperparameters
When standardize = TRUE (the default for continuous outcomes), y_bar, y_std, initial root values, sigma2_global_init (or sigma2_init in Python BARTModel), and default sigma2_leaf_scale are computed on y_train without observation_weights. If your data contain extreme corrupted values on rows that you mask out with \(w_i = 0\), pass explicit sigma2_global_init / sigma2_init, sigma2_leaf_init, and sigma2_leaf_scale (or set standardize = FALSE with explicit scales) so those masked rows do not inflate empirical prior calibration.
Zero Weights (w_i = 0) and Prior Predictive Sampling
Partial Zero Weights (Holdout Masking)
Setting \(w_i = 0\) for a subset of training observations completely removes those observations from forest split marginal likelihoods, leaf posteriors, global variance \(\sigma^2\) (both \(n_+ / 2\) and the weighted sum of squared residuals), probit latent draws, additive random effects, and BCF \(\tau_0\) / adaptive-coding updates, while still producing posterior predictions for those rows in y_hat_train.
All-Zero Weights (Prior Sampling Mode)
Setting \(w_i = 0\) for all \(i = 1, \dots, n\) zeroes out the entire log-likelihood, allowing MCMC to sample from the prior predictive distribution over X_train (and X_test). Three requirements apply:
- Set
num_gfr = 0: Grow-From-Root (He and Hahn (2023)) warm-start is greedy and data-dependent, sostochtreeraises an error if all weights are zero withnum_gfr > 0. - Avoid the improper \(\sigma^2 \sim \text{IG}(0, 0)\) default: When \(n_+ = 0\), \(\text{IG}(0, 0)\) cannot be sampled. Either fix \(\sigma^2\) via
sample_sigma2_global = FALSE(settingsigma2_global_init = 1.0in R and PythonBCFModel, or"sigma2_init": 1.0in PythonBARTModel), or supply a proper prior (sigma2_global_shape > 0,sigma2_global_scale > 0). (Probit models automatically fix \(\sigma^2 = 1\).) - Set
standardize = FALSEfor unscaled prior draws: Otherwisey_hatdraws are shifted and scaled bymean(y_train)andsd(y_train).
Even when \(w_i = 0\) everywhere, X_train and min_samples_leaf still define the admissible split space: MCMC grow proposals only split on observed covariate ranges in X_train that leave at least min_samples_leaf rows in each child node. Similarly, if sample_sigma2_leaf = TRUE, the leaf scale \(\sigma_\mu^2\) still updates conditionally on the number of prior leaves \(L\) and their squared values \(\sum_{\ell=1}^L \mu_\ell^2\) via \(\text{IG}(a_\tau + L/2,\, b_\tau + \frac{1}{2}\sum_\ell \mu_\ell^2)\) — exact joint prior Gibbs sampling over \((T, \mu, \sigma_\mu^2)\).
Compatibility Summary & Low-Level API Note
| Component / Feature | observation_weights Behavior |
|---|---|
| Mean, prognostic (\(\mu\)), & treatment (\(\tau\)) forests | Weighted (constant, univariate basis, & multivariate basis leaves) |
| Global error variance (\(\sigma^2\)) | Weighted (\(a + n_+/2\), \(b + \frac{1}{2}\sum_{i \in I_+} w_i e_i^2\)) |
| Binary probit link | Weighted latent utility \(z_i \sim \mathcal{N}(\eta_i, 1/w_i)\) |
Additive random effects (rfx_*) |
Weighted group (\(\xi_g\)) and working (\(\alpha\)) conditionals |
BCF linear term (tau_0) & adaptive_coding (\(b_0, b_1\)) |
Weighted conjugate Gaussian updates |
Heteroskedastic variance forest (variance_forest_params: num_trees > 0) |
Warns: variance forests overwrite var_weights_ dynamically |
Ordinal / binary cloglog link |
Not supported (raises an error) |
Dataset / ForestDataset)
High-level bart() / BARTModel and bcf() / BCFModel accept precision weights \(w_i\) (\(\operatorname{Var}(y_i \mid -) = \sigma^2 / w_i\)). In contrast, the low-level C++, R (createForestDataset, createRandomEffectsDataset), and Python (Dataset.add_variance_weights, RandomEffectsDataset.add_variance_weights) primitives store variance multipliers \(v_i = 1 / w_i\) (\(\operatorname{Var}(y_i \mid -) = \sigma^2 v_i\), matching variance-forest \(\exp(s(X_i))\) predictions), with \(v_i = +\infty\) representing \(w_i = 0\). Invert precision weights before passing them to low-level Dataset objects.
Worked Examples
Load the necessary packages:
import numpy as np
import matplotlib.pyplot as plt
from stochtree import BARTModel, calibrate_global_error_variance
rng = np.random.default_rng(42)Example 1: Cell-Averaged Heteroskedastic Data & Calibrated Priors
Simulate grouped outcomes where cell sizes vary \(50\times\) across observations, normalize weights to mean \(1\), and pair them with a calibrated \(\sigma^2\) prior (Chipman et al. (2010)):
n <- 300
p <- 4
X <- matrix(runif(n * p), ncol = p)
f_true <- sin(2 * pi * X[, 1]) + 2 * (X[, 2] > 0.5)
sigma_true <- 1.5
cell_counts <- sample(c(1, 2, 10, 50), size = n, replace = TRUE)
y <- f_true + rnorm(n, mean = 0, sd = sigma_true / sqrt(cell_counts))
w_norm <- cell_counts / mean(cell_counts)
nu <- 3
lambda <- calibrateInverseGammaErrorVariance(y, X, nu = nu)
fit_unweighted <- bart(
X_train = X, y_train = y,
num_gfr = 5, num_burnin = 200, num_mcmc = 500,
general_params = list(
sigma2_global_shape = nu / 2,
sigma2_global_scale = (nu * lambda) / 2,
random_seed = 101
)
)
fit_weighted <- bart(
X_train = X, y_train = y,
observation_weights = w_norm,
num_gfr = 5, num_burnin = 200, num_mcmc = 500,
general_params = list(
sigma2_global_shape = nu / 2,
sigma2_global_scale = (nu * lambda) / 2,
random_seed = 101
)
)
pred_unweighted <- rowMeans(extractParameter(fit_unweighted, "y_hat_train"))
pred_weighted <- rowMeans(extractParameter(fit_weighted, "y_hat_train"))
rmse_unweighted <- sqrt(mean((pred_unweighted - f_true)^2))
rmse_weighted <- sqrt(mean((pred_weighted - f_true)^2))
round(c(unweighted = rmse_unweighted, weighted = rmse_weighted), 4)unweighted weighted
0.2748 0.1621
n, p = 300, 4
X = rng.uniform(size=(n, p))
f_true = np.sin(2 * np.pi * X[:, 0]) + 2.0 * (X[:, 1] > 0.5)
sigma_true = 1.5
cell_counts = rng.choice([1.0, 2.0, 10.0, 50.0], size=n)
y = f_true + rng.normal(0.0, sigma_true / np.sqrt(cell_counts), size=n)
w_norm = cell_counts / np.mean(cell_counts)
nu = 3
lambda_ = calibrate_global_error_variance(X, y, nu=nu)
fit_unweighted = BARTModel()
fit_unweighted.sample(
X_train=X, y_train=y,
num_gfr=5, num_burnin=200, num_mcmc=500,
general_params={
"sigma2_global_shape": nu / 2,
"sigma2_global_scale": (nu * lambda_) / 2,
"random_seed": 101,
},
)
fit_weighted = BARTModel()
fit_weighted.sample(
X_train=X, y_train=y,
observation_weights=w_norm,
num_gfr=5, num_burnin=200, num_mcmc=500,
general_params={
"sigma2_global_shape": nu / 2,
"sigma2_global_scale": (nu * lambda_) / 2,
"random_seed": 101,
},
)
pred_unweighted = fit_unweighted.extract_parameter("y_hat_train").mean(axis=1)
pred_weighted = fit_weighted.extract_parameter("y_hat_train").mean(axis=1)
rmse_unweighted = np.sqrt(np.mean((pred_unweighted - f_true) ** 2))
rmse_weighted = np.sqrt(np.mean((pred_weighted - f_true) ** 2))
print({"unweighted": round(float(rmse_unweighted), 4), "weighted": round(float(rmse_weighted), 4)}){'unweighted': 0.2568, 'weighted': 0.1841}
Example 2: Sampling From the BART Prior (observation_weights = 0)
Pass all-zero observation_weights with num_gfr = 0, standardize = FALSE, and fixed \(\sigma^2\) to visualize prior function draws over a 1D grid:
X_grid <- matrix(seq(0, 1, length.out = 200), ncol = 1)
y_placeholder <- rep(0.0, nrow(X_grid))
prior_fit <- bart(
X_train = X_grid,
y_train = y_placeholder,
observation_weights = rep(0.0, nrow(X_grid)),
num_gfr = 0,
num_burnin = 200,
num_mcmc = 100,
general_params = list(
standardize = FALSE,
sample_sigma2_global = FALSE,
sigma2_global_init = 1.0,
random_seed = 7
),
mean_forest_params = list(
num_trees = 50,
sample_sigma2_leaf = FALSE,
sigma2_leaf_init = 1.0 / 50
)
)
prior_draws <- extractParameter(prior_fit, "y_hat_train")
matplot(
X_grid[, 1], prior_draws[, 1:5],
type = "l", lty = 1, xlab = "x", ylab = "f(x) prior draws"
)
X_grid = np.linspace(0.0, 1.0, 200).reshape(-1, 1)
y_placeholder = np.zeros(X_grid.shape[0])
prior_fit = BARTModel()
prior_fit.sample(
X_train=X_grid,
y_train=y_placeholder,
observation_weights=np.zeros(X_grid.shape[0]),
num_gfr=0,
num_burnin=200,
num_mcmc=100,
general_params={
"standardize": False,
"sample_sigma2_global": False,
"sigma2_init": 1.0,
"random_seed": 7,
},
mean_forest_params={
"num_trees": 50,
"sample_sigma2_leaf": False,
"sigma2_leaf_init": 1.0 / 50,
},
)
prior_draws = prior_fit.extract_parameter("y_hat_train")
for k in range(5):
plt.plot(X_grid[:, 0], prior_draws[:, k], alpha=0.8)
plt.xlabel("x")
plt.ylabel("f(x) prior draws")
plt.show()