Weighters
Entropy Balancing & MAIC
- class pybalance.weighting.BaseWeighter(matching_data, weight_col='sample_weight', verbose=True)[source]
Common interface for weighting methods. Unlike the Matcher classes (genetic/lp/propensity), a Weighter never drops pool patients; instead it assigns every pool patient a non-negative weight so that the weighted pool resembles the target on the moments of interest. This is the standard approach for indirect/external comparisons when excluding patients is undesirable or infeasible – e.g. small pools, or a target known only through published aggregate statistics.
- Parameters:
matching_data (MatchingData) – MatchingData whose pool is to be weighted. The target can be either patient-level or an
AggregateTarget(e.g. a published Table 1).weight_col (str) – Name of the column used to store weights on the MatchingData returned by match(). Must not collide with an existing matching feature.
verbose (bool) – Whether to log fitting diagnostics.
- effective_sample_size()[source]
Kish’s effective sample size of the fitted pool weights. See
effective_sample_size().- Return type:
float
- get_best_match()[source]
Return a MatchingData instance in which every pool patient is retained and carries a new column (see weight_col) holding their weight. The target population (patient-level or aggregate) is passed through unchanged, with weight 1.0 assigned to any patient-level target rows unless the weighter also fits target weights. Requires match() to have been called.
- Return type:
- get_target_weights()[source]
Return the fitted per-patient target weights, or None if the target is not reweighted (it then counts with weight 1).
- Return type:
ndarray | None
- get_weights()[source]
Return the fitted per-patient pool weights (in pool row order).
- Return type:
ndarray
- class pybalance.weighting.EntropyBalanceWeighter(matching_data, match_variance=False, normalize='target', max_iter=200, tol=1e-08, ridge=1e-08, weight_col='sample_weight', verbose=True, limit_penalty=0.01)[source]
General maximum-entropy (“method of moments”) weighting: solves for pool weights of the form
w_i = exp(z_i . alpha)such that the weighted pool matches the target. For anAggregateTargetevery disclosed statistic is its own constraint and nothing else is constrained: a numeric mean, the rate of each disclosed categoric level, and the rate above each disclosed median / quantile (the feature is dichotomized at the disclosed value). A feature or categoric level the target says nothing about is simply left free. Optionally also balances variance for numeric features whose target discloses (or, for a patient-level target, has) a standard deviation; for anAggregateTargetthat needs the mean too, since the variance is taken around it.A disclosed
min/maxis a soft constraint, as inAggregateConstraintSatisfactionMatcher: exactly zero weight on patients above a max cannot be reached by positive weights, so the fraction of weight there is only penalized (seelimit_penalty).This is the general form of Matching-Adjusted Indirect Comparison (MAIC; Signorovitch et al., 2010); see
MAICWeighterfor the classic mean-only formulation.- Parameters:
matching_data (MatchingData) – MatchingData whose pool is to be weighted.
match_variance (bool) – If True, additionally constrain the weighted variance of numeric features. For an
AggregateTarget, only features that actually disclose a “std” are constrained (mirroringAggregateConstraintSatisfactionMatcher); for a patient-level target, every numeric feature’s variance is constrained. Categoric features are never variance-constrained: their variance is already determined by their (matched) rate.normalize (str) – How to rescale the fitted weights for reporting: “target” (default) rescales so weights sum to the target population size, “pool” rescales so weights sum to the pool size, “none” leaves the raw dual-optimizer weights unscaled. This choice has no effect on balance (the moment constraints are scale-invariant) or on effective_sample_size(); it only affects the units the weights are reported in.
max_iter (int) – Maximum number of Newton iterations.
tol (float) – Convergence tolerance on the (max-norm) constraint violation.
ridge (float) – Ridge regularization added to the Newton step for numerical stability; increase this if fitting fails to converge due to collinear/near-collinear features.
weight_col (str) – Name of the column used to store weights on the MatchingData returned by match().
verbose (bool) – Whether to log fitting diagnostics.
limit_penalty (float) – Strength of the quadratic penalty on the weight placed beyond a disclosed min / max of an
AggregateTarget(a soft constraint). Larger values enforce the limit more tightly.
- class pybalance.weighting.MAICWeighter(matching_data, normalize='target', max_iter=200, tol=1e-08, ridge=1e-08, weight_col='sample_weight', verbose=True, limit_penalty=0.01)[source]
Matching-Adjusted Indirect Comparison (MAIC; Signorovitch et al., 2010, “Comparative effectiveness without head-to-head trials: a method for matching-adjusted indirect comparisons applied to psoriasis clinical trials”). Reweights patient-level (“IPD”) pool data so that its weighted means match a target’s aggregate statistics – typically a comparator trial’s published Table 1 – using the method-of-moments / maximum-entropy weighting scheme of
EntropyBalanceWeighter, restricted to first moments only. This is the standard MAIC formulation and is appropriate whenever the comparator discloses only means (and category rates), not variances.Use
EntropyBalanceWeighter(matching_data, match_variance=True)directly if the comparator additionally discloses standard deviations you also want to match.- Parameters:
matching_data (MatchingData) – MatchingData whose pool (IPD) is to be weighted to match the target’s (typically aggregate, e.g.
AggregateTarget) moments.normalize (str) – See
EntropyBalanceWeighter. Defaults to “target”, i.e. weights sum to the target’s sample size, matching common MAIC reporting conventions.max_iter (int) – Maximum number of Newton iterations.
tol (float) – Convergence tolerance on the (max-norm) constraint violation.
ridge (float) – Ridge regularization added to the Newton step for numerical stability.
weight_col (str) – Name of the column used to store weights on the MatchingData returned by match().
verbose (bool) – Whether to log fitting diagnostics.
limit_penalty (float) – See
EntropyBalanceWeighter.
Propensity Score Weighter
- class pybalance.weighting.PropensityScoreWeighter(matching_data, objective='beta', method='att', trim_quantiles=None, min_ess_fraction=0.1, max_iter=50, time_limit=300, weight_col='sample_weight', verbose=True, seed=None)[source]
Weight patients using a propensity score model for pool vs. target membership. As in
PropensityScoreMatcher, the weighter searches randomly over the hyperparameters of the propensity score model and keeps the model whose weights perform best according to the given optimization objective – here, the balance of the weighted populations. The propensity score is mapped to weights bymethod(seepropensity_score_weights()), which plays the role of the matching method inPropensityScoreMatcher.Optimizing balance alone can favor spiky weights that rest on a handful of patients, so candidate models whose effective sample size falls below
min_ess_fractionof either population are rejected.Requires a patient-level target (there is no pool-vs-target classification problem to fit against an
AggregateTarget).- Parameters:
matching_data (MatchingData) – MatchingData whose pool is to be weighted.
objective (Union[str, BaseBalanceCalculator]) – Balance objective to optimize in the hyperparameter search. Can be a string referring to any balance calculator known to utils.balance_calculators.BalanceCalculator or an instance of BaseBalanceCalculator.
method (str) – How to turn propensity scores into weights: “att”, “atc”, “ate”, “overlap” or “matching”.
trim_quantiles (Optional[Tuple[float, float]]) – Optional
(low, high)quantiles (e.g.(0.01, 0.99)) at which to clip the weights of each population before scoring. Trades a little bias for lower variance when extreme weights occur, e.g. with “att” or “ate”.min_ess_fraction (float) – Reject candidate models whose pool or target effective sample size is below this fraction of the population size.
max_iter (int) – Maximum number of hyperparameters to try before returning the best weights.
time_limit (Optional[float]) – Restrict hyperparameter search based on time. No new model will be trained after time_limit seconds have passed (def: 300 sec).
weight_col (str) – Name of the column used to store weights on the MatchingData returned by match().
verbose (bool) – Whether to log diagnostic information during training.
seed (Optional[int]) – Seed for the hyperparameter search and the classifiers. Set it to make weighting reproducible; if None, results vary between runs.
- get_best_match(method=None)[source]
Return a MatchingData instance in which every pool and target patient is retained and carries a new column (see weight_col) holding their weight under
method(default: the method the model was selected for). Passing another method reuses the fitted model without searching again, but note the model was selected to optimize the balance of the method given at construction. Does not change the fitted state. Requires match() to have been called.- Return type:
- get_target_weights(method=None)[source]
Target weights from the fitted model for
method; see get_weights().- Return type:
ndarray
- get_weights(method=None)[source]
Pool weights from the fitted model for
method(default: the method the model was selected for). Does not change the fitted state.- Return type:
ndarray
- match(method=None)[source]
Search for the best propensity model (once; later calls reuse it) and return the weighted MatchingData; see get_best_match() for
method.- Return type:
- plot_propensity_score_distributions(method=None)[source]
Plot histograms of the estimated propensity score for the pool and target populations, before vs. after weighting – the weighting analogue of
PropensityScoreMatcher.plot_propensity_score_distributions().Unlike a Matcher, a Weighter never drops patients, so there is no matched subset to compare against; instead, the “before” panel shows every patient counted equally and the “after” panel shows the same propensity scores counted by their weight. A successful fit should show the “after” histograms move towards each other.
- Parameters:
method (str | None) – Weighting method to plot (default: the method the model was selected for).
- plot_weight_distributions(method=None)[source]
Plot histograms of the fitted weights of the pool and target populations. The effective sample size of each population is shown in its panel title; a long right tail or a low effective sample size indicates that a few patients dominate.
- Parameters:
method (str | None) – Weighting method to plot (default: the method the model was selected for).
- pybalance.weighting.propensity_score_weights(ps_pool, ps_target, method='att')[source]
Map propensity scores
p = P(target | X)to weights for the pool and target patients. The weighting analogue ofpybalance.propensity.propensity_score_match.“att”: pool weighted by the odds
p / (1 - p), target weight 1. The pool is reweighted onto the target (Rosenbaum & Rubin, 1983; Austin, 2011).“atc”: the reverse: target reweighted onto the pool, pool weight 1.
“ate”: inverse probability weights for both populations, which reweights each onto their union.
“overlap”: pool weighted by
p, target by1 - p(Li, Morgan & Zaslavsky, 2018). Emphasizes patients who could belong to either population; weights are bounded in [0, 1] and, with an unregularized logistic model, covariate means are balanced exactly.“matching”:
min(p, 1 - p)over the inverse probability weight (Li & Greiner, 2013), a smoother analogue of 1:1 matching.
Propensity scores should be clipped away from 0 and 1 by the caller.
- Returns:
Tuple
(pool_weights, target_weights).- Return type:
Tuple[ndarray, ndarray]