Using approximate estimators

Approximate estimators sample coalitions under a budget and aggregate the payoffs. Each sampler below runs on a toy game with a known answer, then a plot compares them. Theory: Approximate estimation.

All take estimate_attributions(masks, payoffs, aggregator). Monte Carlo uses the estimand’s aggregator; complementary and Neyman aggregate complementary contributions, Shapley only.

A toy game with a known answer

Five players add their weights; p0 and p1 together earn a bonus of 2. Exact Shapley values are the weights, plus half the bonus for p0 and p1:

from mllm_shap import (
    CoalitionMask,
    ComplementaryEstimator,
    ExactEstimator,
    MonteCarloEstimator,
    NeymanEstimator,
    PlayerSet,
    ShapleyAggregator,
)

player_set = PlayerSet(player_ids=("p0", "p1", "p2", "p3", "p4"))
weights = (1.0, 0.5, 2.0, -1.0, 0.25)

def payoff(mask: CoalitionMask) -> float:
    additive = sum(w for w, present in zip(weights, mask.present) if present)
    bonus = 2.0 if mask.present[0] and mask.present[1] else 0.0
    return additive + bonus

exact = ExactEstimator()
all_masks = list(exact.sample_masks(player_set, 1.0, False, seed=0))
reference = exact.estimate_attributions(
    all_masks, [payoff(mask) for mask in all_masks], ShapleyAggregator()
)
print("coalitions:", len(all_masks))
print("exact:", tuple(round(value, 4) for value in reference))

Output

coalitions: 32
exact: (2.0, 1.5, 2.0, -1.0, 0.25)

Monte Carlo

estimator = MonteCarloEstimator()
masks = list(estimator.sample_masks(
    player_set,
    budget_fraction=0.5,
    include_minimal_masks=True,
    seed=42,
))
mc_values = estimator.estimate_attributions(
    masks,
    [payoff(mask) for mask in masks],
    ShapleyAggregator(),
)
print("samples:", len(masks))
print("mc:", tuple(round(value, 4) for value in mc_values))

Output

samples: 16
mc: (1.9062, 1.8125, 2.1094, -1.2656, -0.2812)

The same masks with BanzhafAggregator give the Banzhaf estimate.

Complementary pairs

estimator = ComplementaryEstimator()
masks = list(estimator.sample_masks(
    player_set,
    budget_fraction=0.5,
    include_minimal_masks=True,
    seed=7,
))
# The (N, empty) pair comes first, then the singleton pairs ({i}, N\{i}),
# then pairs S, N\S. Order does not matter for aggregation: masks are
# matched to their complements by value.
cc_values = estimator.estimate_attributions(
    masks,
    [payoff(mask) for mask in masks],
    ShapleyAggregator(),
)
print("samples:", len(masks))
print("complementary:", tuple(round(value, 4) for value in cc_values))

Output

samples: 16
complementary: (2.375, 0.325, 2.375, -0.225, -0.3)

Neyman two-phase sampling

Phase two is drawn from the phase-one payoffs:

estimator = NeymanEstimator(initial_num_samples=2, use_standard_method=False)
phase_one = list(estimator.sample_masks(
    player_set,
    budget_fraction=0.8,
    include_minimal_masks=False,
    seed=11,
))
payoffs_one = [payoff(mask) for mask in phase_one]
estimator.begin_allocation(phase_one, payoffs_one)

phase_two = list(estimator.sample_allocation_masks())
payoffs_two = [payoff(mask) for mask in phase_two]

neyman_values = estimator.estimate_attributions(
    phase_one + phase_two,
    payoffs_one + payoffs_two,
    ShapleyAggregator(),
)
print("phase one:", len(phase_one), "phase two:", len(phase_two))
print("neyman:", tuple(round(value, 4) for value in neyman_values))

Output

phase one: 18 phase two: 6
neyman: (2.075, 1.725, 2.075, -1.225, 0.1)

ExplainRunner runs both phases for neyman_cc; the neyman config section sizes phase one.

Comparing the estimates

Code for this figure
import matplotlib.pyplot as plt
import numpy as np

estimates = {
    "exact": reference,
    "mc": mc_values,
    "complementary": cc_values,
    "neyman": neyman_values,
}
positions = np.arange(len(player_set.player_ids))
figure, axis = plt.subplots(figsize=(6.5, 3), layout="constrained")
for offset, (label, values) in enumerate(estimates.items()):
    axis.bar(positions + 0.2 * (offset - 1.5), values, width=0.2, label=label)
axis.axhline(0, color="black", linewidth=0.8)
axis.set(xticks=positions, xticklabels=player_set.player_ids, ylabel="Shapley value")
figure.legend(ncols=4, loc="outside upper center")

Toy game: exact values and the three estimates above

Grouped bars per player p0 to p4 for exact, mc, complementary and neyman. mc and complementary get the sign of p4 wrong, complementary gives p1 far less than its exact 1.5, and neyman stays closest to exact.

At 16 of 32 coalitions mc and complementary flip the sign of p4; complementary misses most of p1’s bonus. neyman (24 coalitions) is closest.

Configuration

In ExplainConfig:

explanation:
  estimator: neyman_cc
  budget:
    fraction: 0.8
  include_minimal_masks: false
  neyman:
    initial_num_samples: 2
    use_standard_method: false

Phase one size: neyman.initial_num_samples, else neyman.initial_fraction, else a default from the player count. If phase one takes the whole budget, Neyman aggregates it alone. Up to \(2n + 2\) masks it scores what complementary scores; above that its error is often close (examples/estimator_comparison.ipynb shows a game where it is larger). Every key: Configuration.

Plugin resolution

explanation.estimator takes the names in the mllm_shap.estimators entry-point group:

from mllm_shap import PluginGroup, PluginRegistry
from mllm_shap.plugins import register_builtin_plugins

registry = PluginRegistry()
register_builtin_plugins(registry)
print(registry.names(PluginGroup.ESTIMATORS))

Output

('complementary', 'exact', 'kernel_banzhaf', 'leverage', 'lime', 'loo', 'mc', 'neyman_cc', 'permutation', 'proxy')

Regression estimators and long prompts

leverage (Shapley), kernel_banzhaf (Banzhaf) and proxy (both; extra mllm-shap[proxy]) fit a regression, so a few multiples of \(n\) coalitions suffice (Regression estimators and hierarchical players); set budget.per_player. For long prompts, players: sentences with explain_hierarchical scores paragraphs, then the sentences of the top ones:

from mllm_shap import (
    ConversationSnapshot, ExplainConfig, ExplainRunner, Message, Role, Turn,
)

text = "\n\n".join(
    " ".join(f"Point {p}.{k} is made here." for k in range(8)) for p in range(10)
)
snapshot = ConversationSnapshot.from_turns(
    (Turn(messages=(Message(role=Role.USER, text=text),)),)
)
config = ExplainConfig.model_validate({
    "backend": {"kind": "mock", "model_id": "mock"},
    "generation": {"max_new_tokens": 8},
    "explanation": {
        "estimator": "leverage",
        "players": "sentences",
        "budget": {"per_player": 4},
        "hierarchical": {"keep_fraction": 0.2},
    },
})
output = ExplainRunner(config).explain_hierarchical_sync(snapshot)
print("groups kept:", output.kept_groups)
print("coarse calls:", output.coarse.metrics.requested)
print("fine calls:", output.fine.metrics.requested, "(flat game: 320)")

Output

groups kept: (4, 8)
coarse calls: 40
fine calls: 64 (flat game: 320)

Choosing an estimator

Estimator

Best when

Estimand support

Accuracy at low budget

Partial-sample caveat

Monte Carlo (mc)

You need Banzhaf, or Shapley at low and medium budgets

Shapley, Banzhaf

Next to the regression estimators in Estimator benchmark

Not efficient below the full table; strata without both means are skipped

Complementary (complementary)

Every coalition should be scored together with its complement

Shapley only

Converges more slowly than Monte Carlo from a budget of \(8n\)

Not efficient below the full table

Neyman (neyman_cc)

Generous budgets where payoff variance differs by coalition size

Shapley only (two-phase)

Close to complementary while phase one uses the whole budget

Phase-two allocation needs enough phase-one samples per size

leverage, kernel_banzhaf, proxy

Budgets of \(8n\) and more

Shapley; Banzhaf; both

Lowest error in Estimator benchmark

leverage is efficient at every budget; proxy needs scikit-learn

Flowchart and decision table: Choosing an estimator; measured errors: Estimator benchmark.