Estimation¶
Estimation algorithms for cooperative-game attribution.
@domain estimation @see [[knowledge/architecture/estimation]]
Exact coalition enumeration estimator.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_exact.py]]
- class mllm_shap.estimation.exact.ExactEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorEnumerate all coalitions and delegate attribution to an estimand plugin.
- static num_coalitions(num_players: int) int[source]¶
Return the number of coalitions evaluated by exact enumeration (2^n).
- static iter_mask_ints(num_players: int) Iterator[int][source]¶
Lazily yield every coalition bitmask from empty to grand.
- static mask_int_to_present(mask_int: int, num_players: int) tuple[bool, ...]¶
Decode a coalition bitmask into presence flags.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield every coalition mask including the empty and grand coalitions.
- static iter_masks(player_set: PlayerSet) Iterator[CoalitionMask][source]¶
Yield every coalition mask including the empty and grand coalitions.
- standard_errors(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Return zeros: the full table leaves no sampling error.
- bind_snapshot(snapshot: ConversationSnapshot) None¶
Attach the conversation snapshot under explanation.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float]¶
Aggregate coalition payoffs with the selected estimand plugin.
- options_model¶
alias of
PluginOptions
Monte Carlo coalition sampling estimator.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_monte_carlo.py]]
- class mllm_shap.estimation.monte_carlo.MonteCarloEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample random coalitions and delegate attribution to an estimand plugin.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield the small strata exactly, then coalitions with uniformly drawn sizes.
Order (Stratified SVARM): the grand and empty coalitions, the singletons, the coalitions missing one player, then a size drawn uniformly from the sizes with unseen coalitions and a uniform coalition of that size, without repeats. All count toward the budget.
- standard_errors(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Return the stratified standard error of each player’s value.
Coalitions of one size are a simple random sample, so each size stratum is a finite-population mean difference (
marginal_standard_errors).
- bind_snapshot(snapshot: ConversationSnapshot) None¶
Attach the conversation snapshot under explanation.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float]¶
Aggregate coalition payoffs with the selected estimand plugin.
- options_model¶
alias of
PluginOptions
Complementary pair sampling estimator.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_complementary.py]]
- class mllm_shap.estimation.complementary.ComplementaryEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample complementary coalition pairs and aggregate CC attributions.
- reset_sampling_state(num_players: int) None[source]¶
Reset complementary M-matrix counts before a new sampling run.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield complementary coalition pairs up to the configured budget.
Order: the
(N, empty)pair, the singleton pairs({i}, N - {i})(the2n + 2budget floor fits all of them), block pairs that give every player each size once, then random pairs. All count toward the budget.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Aggregate complementary pairs into Shapley attributions.
Masks are paired by complement, so their order does not matter. Complementary contributions estimate the Shapley value only.
- Raises:
ValueError – If the estimand is not Shapley,
masksis empty, or a mask has no complement inmasks.
Permutation sampling with antithetic orderings.
Random orderings of the players are drawn and every prefix of each ordering is
evaluated, so one ordering costs n - 1 new coalitions. An antithetic ordering is
the reverse of its partner: its prefix of size k is the complement of the
partner’s prefix of size n - k, which cancels part of the sampling noise.
Prefixes feed the estimand aggregator, so any estimand works.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_permutation.py]]
- class mllm_shap.estimation.permutation.PermutationOptions(*, antithetic: bool = True)[source]¶
Bases:
PluginOptionsPermutation sampling options.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class mllm_shap.estimation.permutation.PermutationEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample orderings, evaluate their prefixes and delegate to the estimand.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
PermutationOptions
LIME baseline: a locally weighted ridge regression on coalition masks.
The surrogate of Ribeiro et al. (2016) for text: coalitions are random subsets, each
weighted by an exponential kernel of its cosine distance from the full input, and the
payoffs are regressed on presence with an unpenalised intercept. Values are
regression coefficients, not Shapley or Banzhaf values, so the estimand is ignored
and they need not add up to v(N) - v(empty).
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_lime.py]]
- class mllm_shap.estimation.lime.LimeOptions(*, kernel_width: float = 25.0, alpha: float = 1.0)[source]¶
Bases:
PluginOptionsSurrogate settings, with the defaults of the reference
limepackage.- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- mllm_shap.estimation.lime.lime_values(present: ndarray, payoffs: Sequence[float], kernel_width: float = 25.0, alpha: float = 1.0) list[float][source]¶
Return the ridge coefficients of payoffs on presence rows.
Row weights are
sqrt(exp(-d^2 / width^2))withdthe cosine distance to the all-present row times 100; an all-absent row has distance 1.
- class mllm_shap.estimation.lime.LimeEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample random subsets and fit the LIME surrogate on their payoffs.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
LimeOptions
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield the grand and empty coalitions, then distinct random subsets.
The number of removed players is uniform over
1..n-1. Subsets are distinct, soreanalyzeof the archive sees the same rows as the run.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator | None) list[float][source]¶
Return the surrogate coefficients; the estimand is ignored.
Pairwise interaction indices of a full coalition table, through shapiq.
The table is wrapped as a shapiq game and ExactComputer returns the order-2
index: k-SII (the Shapley interaction index at its top order, the default),
SII, FSII (Faith-SHAP) or any other index it accepts. Sampled tables are not
supported, because the approximators of shapiq choose their own coalitions.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_interactions.py]]
- mllm_shap.estimation.interactions.pairwise_interactions(masks: Sequence[Sequence[bool]], payoffs: Sequence[float], index: str = 'k-SII') ndarray[source]¶
Return the symmetric matrix of order-2
indexvalues, zero on the diagonal.- Raises:
ImportError – If
shapiqis not installed (extrainteractions).ValueError – If
masksis not the complete table of2^ncoalitions.
Budget planning from a target error (Maleki et al. 2013, Hoeffding bound).
A player’s value is a mean of marginal contributions that lie in a range of width
r; sampling m random orderings keeps every player within epsilon of the
Shapley value with probability 1 - beta once m >= r^2 ln(2 n / beta) / (2
epsilon^2), a union bound over the n players. The bound is worst-case and loose:
a pilot run gives a tighter range than the spread of the value function.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_planning.py]]
- class mllm_shap.estimation.planning.BudgetPlan(num_players: int, orderings: int, evaluations: int, exact_is_cheaper: bool)[source]¶
Bases:
objectBudget that meets a target error, in orderings and in evaluations.
- evaluations: int¶
Coalitions the orderings can touch,
orderings * (n - 1) + 2, capped at the2^nof the full table.
- property per_player: float¶
Return
evaluationsper player, the unit ofbudget.per_player.
- mllm_shap.estimation.planning.plan_budget(num_players: int, value_range: float, target_error: float, confidence: float = 0.95) BudgetPlan[source]¶
Return the orderings and evaluations for
target_erroratconfidence.value_rangeis the width of the marginal contributions, for examplev(N) - v(empty)for a monotone game or the spread seen in a pilot run.- Raises:
ValueError – If a count is below 1 or an error, range or confidence is not positive or not below one for the confidence.
Stopping rule: end sampling once the estimate is narrow or its top set is stable.
The budget stays the upper bound. After every check_every new coalitions, past a
floor, sampling ends when every player’s 95% interval is at most max_ci_width wide
(needs standard errors) or the top_k_stable players of largest magnitude are the
same set as at the previous check.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_stopping.py]]
- mllm_shap.estimation.stopping.Z_95 = 1.959964¶
Normal quantile of a two-sided 95% interval.
- class mllm_shap.estimation.stopping.StopDecision(stop: bool, reason: str | None, top: tuple[int, ...] | None)[source]¶
Bases:
objectOutcome of one stopping check.
- mllm_shap.estimation.stopping.top_players(values: Sequence[float], k: int) tuple[int, ...][source]¶
Return the
kplayers of largest magnitude, sorted by index.
- mllm_shap.estimation.stopping.check_stop(values: Sequence[float], errors: Sequence[float] | None, max_ci_width: float | None, top_k_stable: int | None, previous_top: tuple[int, ...] | None) StopDecision[source]¶
Decide whether to stop given the current values and standard errors.
Neyman complementary allocation estimator.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_neyman.py]]
- class mllm_shap.estimation.neyman.NeymanEstimator(context: PluginContext | None = None, initial_fraction: float | None = None, initial_num_samples: int | None = None, use_standard_method: bool = False)[source]¶
Bases:
ComplementaryEstimatorTwo-phase complementary estimator with Neyman coalition-size allocation.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield phase-one Neyman masks until the initial M-matrix grid is filled.
Order: the
(N, empty)pair, the singleton pairs({i}, N - {i}), then the grid walk over (size, player) cells. All count toward the budget.
- begin_allocation(masks: Sequence[CoalitionMask], payoffs: Sequence[float]) None[source]¶
Estimate Neyman allocation after phase-one payoffs are available.
- sample_allocation_masks() Iterator[CoalitionMask][source]¶
Yield phase-two masks according to the estimated Neyman allocation.
Leverage SHAP: paired, leverage-score sampling with a constrained regression.
Every coalition size carries the same total leverage in the Kernel SHAP
regression (Musco and Witter 2025), so sizes are sampled uniformly and each
size stratum is weighted by its population over its sample count. Pairs
(S, N - S) are drawn without replacement; a stratum whose share of the
budget covers all its pairs is enumerated.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_leverage.py]]
- mllm_shap.estimation.leverage.pair_classes(num_players: int) list[tuple[int, int]][source]¶
Return
(size, pairs)per pair class of sizessandn - s.
- mllm_shap.estimation.leverage.allocate_pairs(num_players: int, pairs: int) dict[int, int][source]¶
Split
pairsover the pair classes in proportion to their leverage mass.A class holding two sizes carries twice the mass of the middle class. Classes whose share reaches their population are enumerated and drop out; the rest get whole counts by largest remainder.
- mllm_shap.estimation.leverage.distinct_subsets(rng: Generator, num_players: int, size: int, count: int, contains_first: bool) Iterator[tuple[bool, ...]][source]¶
Yield
countdistinct uniform subsets ofsizeplayers.contains_firstrestricts to subsets holding player 0, one per pair when both sides have the same size.
- class mllm_shap.estimation.leverage.LeverageEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample complementary pairs by leverage and solve the Kernel SHAP regression.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield
(N, empty)then complementary pairs per size stratum.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Solve the efficiency-constrained, stratum-weighted least squares.
- Raises:
ValueError – If the estimand is not Shapley or a boundary mask is missing.
- mllm_shap.estimation.leverage.leverage_values(present: ndarray, payoffs: Sequence[float]) list[float][source]¶
Return Shapley estimates from coalition rows by constrained weighted regression.
Stratum
sweighs(n - 1) / (s (n - s) count_s): the Shapley kernel times the stratum population over its sample count, which is exact when the stratum is enumerated. The sum constraint is solved by elimination of the last player.
Kernel Banzhaf: paired uniform sampling with a centred linear regression.
The Banzhaf value of a player is the slope of the best linear fit of v on the
presence indicators under the uniform distribution over coalitions (Wang and Jia
2023). The design uses indicators shifted by one half and an intercept, so the
columns are orthogonal on the full table and the fit is exact there.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_kernel_banzhaf.py]]
- class mllm_shap.estimation.kernel_banzhaf.KernelBanzhafEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorSample uniform complementary pairs and fit the Banzhaf regression.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield
(N, empty)then distinct uniform pairs(S, N - S).
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Return the slopes of the least-squares fit of the payoffs on the rows.
- Raises:
ValueError – If the estimand is not Banzhaf.
ProxySHAP (order 1): a boosted-tree proxy with exact values and a residual fix.
A leaf of the fitted trees is the game c [P in S, A disjoint from S] for the
players present (P) and absent (A) on its path, with closed-form Shapley
and Banzhaf values, so the proxy’s values are exact sums over leaves. The values
of the residual v - proxy on the sampled coalitions are added back when that
is cheap, which makes the estimate exact on the full table.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_proxy.py]]
- mllm_shap.estimation.proxy.CORRECTION_MAX_PLAYERS = 30¶
Fewer players than this always get the residual correction.
- mllm_shap.estimation.proxy.CORRECTION_MIN_PER_PLAYER = 16¶
Larger budgets, in coalitions per player, get the correction at any size.
- mllm_shap.estimation.proxy.leaf_game_values(present: Sequence[int], absent: Sequence[int], estimand: Estimand) tuple[float, float][source]¶
Return the per-player value of a unit leaf for
presentandabsent.Returns the value of each present and of each absent player. Shapley gives
(p-1)! a! / (p+a)!and minusp! (a-1)! / (p+a)!; Banzhaf gives plus and minus1 / 2^(p+a-1).
- mllm_shap.estimation.proxy.tree_values(model: GradientBoostingRegressor, num_players: int, estimand: Estimand) ndarray[source]¶
Return exact per-player values of the fitted ensemble’s game.
- class mllm_shap.estimation.proxy.ProxyEstimator(context: PluginContext | None = None)[source]¶
Bases:
LeverageEstimatorLeverage-sampled coalitions, a tree proxy, and a residual correction.
- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield leverage-sampled complementary pairs.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator) list[float][source]¶
Fit the proxy on the archived coalitions and return its corrected values.
Leave-one-out attribution: each player’s drop from the full coalition.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_loo.py]]
- class mllm_shap.estimation.loo.LeaveOneOutEstimator(context: PluginContext | None = None)[source]¶
Bases:
_SnapshotEstimatorAttribute
v(N) - v(N - {i})to playerifromn + 1coalitions.The baseline every attribution method should beat. It ignores the budget and the estimand: values are not Shapley or Banzhaf values and need not add up to
v(N) - v(empty).- sample_masks(player_set: PlayerSet, budget_fraction: float, include_minimal_masks: bool, seed: int) Iterator[CoalitionMask][source]¶
Yield the grand coalition, then the grand coalition without each player.
- estimate_attributions(masks: Sequence[CoalitionMask], payoffs: Sequence[float], aggregator: EstimandAggregator | None) list[float][source]¶
Return
v(N) - v(N - {i})for every playeri.
Estimand aggregators¶
Estimand aggregation plugins.
@domain estimation @see [[knowledge/architecture/estimation]]
Shapley estimand aggregation.
@domain estimation @see [[knowledge/architecture/estimation]]
- class mllm_shap.estimation.estimands.shapley.ShapleyAggregator(context: PluginContext | None = None)[source]¶
Bases:
objectAggregate coalition samples with Shapley coalition weights.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
Banzhaf estimand aggregation.
@domain estimation @see [[knowledge/architecture/estimation]]
- class mllm_shap.estimation.estimands.banzhaf.BanzhafAggregator(context: PluginContext | None = None)[source]¶
Bases:
objectAggregate coalition samples with uniform Banzhaf coalition weights.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
Semivalue estimands: Beta Shapley and weighted Banzhaf.
Both give each coalition size a probability and read it off the same sampled
stratum means as Shapley and Banzhaf, so any estimator that samples across sizes
(mc, exact) serves them.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/estimands/test_semivalue.py]]
- mllm_shap.estimation.estimands.semivalue.beta_shapley_weight(coalition_size: int, num_players: int, alpha: float, beta: float) float[source]¶
Return the Beta(
alpha,beta) Shapley weight of one coalition.Following Kwon and Zou (2022), the inclusion probability is Beta(
beta,alpha) distributed, soalpha > betafavours small coalitions andalpha = beta = 1is Shapley.
- mllm_shap.estimation.estimands.semivalue.weighted_banzhaf_weight(coalition_size: int, num_players: int, p: float) float[source]¶
Return
p^s (1 - p)^(n - 1 - s);p = 1/2is Banzhaf.
- class mllm_shap.estimation.estimands.semivalue.BetaShapleyOptions(*, alpha: Annotated[float, Gt(gt=0)] = 4.0, beta: Annotated[float, Gt(gt=0)] = 1.0)[source]¶
Bases:
PluginOptionsBeta Shapley shape parameters.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class mllm_shap.estimation.estimands.semivalue.WeightedBanzhafOptions(*, p: Annotated[float, Gt(gt=0)] = 0.3)[source]¶
Bases:
PluginOptionsWeighted Banzhaf inclusion probability.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class mllm_shap.estimation.estimands.semivalue.BetaShapleyAggregator(context: PluginContext | None = None)[source]¶
Bases:
objectAggregate coalition samples with Beta Shapley weights.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
BetaShapleyOptions
- class mllm_shap.estimation.estimands.semivalue.WeightedBanzhafAggregator(context: PluginContext | None = None)[source]¶
Bases:
objectAggregate coalition samples with weighted Banzhaf weights.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
WeightedBanzhafOptions
Normalizers¶
Post-aggregation attribution normalizers.
@domain estimation @see [[knowledge/architecture/estimation]] @tested-by [[tests/estimation/test_normalizers.py]]
- mllm_shap.estimation.normalizers.additive_efficiency(values: Sequence[float], grand_value: float, base_value: float) list[float][source]¶
Shift every value equally so they sum to
v(N) - v(empty).
- mllm_shap.estimation.normalizers.apply_efficiency(mode: str, values: Sequence[float], grand_value: float, base_value: float) list[float][source]¶
Return
valuesafter theexplanation.efficiencycorrectionmode.
- class mllm_shap.estimation.normalizers.IdentityNormalizer(context: PluginContext | None = None)[source]¶
Bases:
objectReturn attributions unchanged.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- class mllm_shap.estimation.normalizers.AbsSumNormalizer(context: PluginContext | None = None)[source]¶
Bases:
objectScale attributions by the sum of absolute values.
- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions
- class mllm_shap.estimation.normalizers.PowerShiftOptions(*, power: Annotated[float, Gt(gt=0)] = 1.0)[source]¶
Bases:
PluginOptionsOptions of the
power_shiftnormalizer.- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class mllm_shap.estimation.normalizers.PowerShiftNormalizer(context: PluginContext | None = None, power: float = 1.0)[source]¶
Bases:
objectShift to non-negative values, apply a power, then scale to sum one.
- options_model¶
Options accepted from
explanation.plugin_options.alias of
PowerShiftOptions
- class mllm_shap.estimation.normalizers.MinMaxNormalizer(context: PluginContext | None = None)[source]¶
Bases:
objectMin-max scale to
[0, 1]then normalize to sum one.- options_model¶
Accepts no
explanation.plugin_options.alias of
PluginOptions