from _api_doc_utils import *BalancingWeights
Calibration weights for covariate balance
1 Where it fits
Group: Causal inference
BalancingWeights chooses weights for a source sample so weighted source covariate means match a target sample:
\[ \sum_i w_i x_i / \sum_i w_i \approx \sum_j q_j x_j / \sum_j q_j. \]
The objective can be quadratic or entropy-like, with optional lower/upper bounds and ridge stabilization.
2 Python API
Constructor: cm.BalancingWeights
Use fit(covariates, target_covariates, baseline_weights=None, target_weights=None). get_weights() returns the fitted source weights. summary() reports balance diagnostics, the dual coefficients, effective sample size, and solver status.
print(inspect.signature(cm.BalancingWeights))(objective='quadratic', solver='auto', autoscale=False, min_weight=0.0, max_weight=1.0, l2_norm=0.0, max_iterations=200, tolerance=1e-08)
cls = cm.BalancingWeights
display(HTML(html_table(["Public method"], public_methods(cls))))| Public method |
|---|
fit(self, /, covariates, target_covariates, baseline_weights=None, target_weights=None) |
get_weights(self, /) |
summary(self, /) |
3 Minimal example
rng=np.random.default_rng(10)
x0=rng.normal(size=(180,3)); x1=rng.normal(loc=np.array([.4,-.2,.1]), size=(80,3))
model=cm.BalancingWeights(objective="quadratic", max_iterations=500)
model.fit(x0, x1)
print(model.summary()["mean_diff"])
print(model.summary()["effective_sample_size"])
print(model.get_weights()[:5])[1.11022302e-16 5.55111512e-17 1.17961196e-16]
155.1166258737379
[0.00415802 0.00646452 0.00614945 0.00537598 0.00450626]
4 summary() contract
The table below is generated by fitting the live class in this repository and then inspecting summary(). Shapes are shown because most values are plain NumPy arrays or scalars.
rng=np.random.default_rng(110); x0=rng.normal(size=(80,3)); x1=rng.normal(loc=np.array([.4,-.2,.1]), size=(40,3))
model=cm.BalancingWeights(); model.fit(x0,x1)
summary = model.summary()
display(HTML(html_table(["summary() key", "shape"], summary_shape_rows(summary))))| summary() key | shape |
|---|---|
weights |
(80,) |
beta |
(4,) |
objective |
() |
solver |
() |
success |
() |
nit |
() |
criterion |
() |
residual_norm |
() |
weight_sum |
() |
weighted_mean |
(3,) |
target_mean |
(3,) |
mean_diff |
(3,) |
l2_diff |
() |
max_abs_diff |
() |
effective_sample_size |
() |
min_weight |
() |
max_weight |
() |
l2_norm |
() |