pyhealth.interpret.methods.ensemble#
Overview#
Ensemble interpreters combine the attributions of several expert interpreters (at least three) into one consensus attribution. Each expert’s attributions are rank-normalized to a common [0, 1] scale, aggregated by a strategy-specific rule, and reshaped back to the original tensor shapes. Choose a strategy:
AvgEnsemble: uniform average (AGGMean / Borda).VarEnsemble: mean divided by standard deviation (AGGVar), which suppresses features the experts disagree on.CrhEnsemble: iteratively reweights experts by their agreement with the consensus (CRH truth discovery).
To add a new strategy, subclass
BaseInterpreterEnsemble and
implement _ensemble.
API Reference#
- class pyhealth.interpret.methods.base_ensemble.BaseInterpreterEnsemble(model, experts)[source]#
Bases:
BaseInterpreterAbstract base class for ensemble interpreters.
Provides the shared workflow for ensemble-based attribution:
Each expert interpreter independently computes attributions.
The per-expert attribution maps are flattened, then normalized to a common [0, 1] scale via competitive ranking.
The normalized attributions are passed to
_ensemble(), which concrete subclasses must override to implement a specific aggregation strategy (e.g., CRH truth discovery, simple averaging, majority voting).The aggregated result is unflattened back to the original tensor shapes.
Subclasses only need to implement
_ensemble().- Parameters:
model (
BaseModel) – The PyHealth model to interpret.experts (
list[BaseInterpreter]) – A list of at least threeBaseInterpreterinstances whoseattributemethods will be called to produce individual attribution maps.
Initialize the base interpreter.
- Parameters:
model (
BaseModel) – A trained PyHealth model to interpret. The model should be in evaluation mode during interpretation.
Note
Subclasses should call super().__init__(model) and then perform any method-specific initialization.
- attribute(**kwargs)[source]#
Compute consensus attributions by ensembling all expert interpreters.
Each expert’s
attributemethod is called with the same inputs. The resulting attribution maps are flattened, competitively ranked to a common [0, 1] scale, and aggregated via the subclass-defined_ensemble()strategy.- Parameters:
**kwargs (
Tensor|tuple[Tensor,...]) – Input data dictionary from a dataloader batch. Should contain feature tensors (or tuples of tensors) keyed by the model’s feature keys, plus optional label or metadata tensors (which are forwarded to experts).- Return type:
- Returns:
Dictionary mapping each feature key to a consensus attribution tensor whose shape matches the corresponding input tensor.
- class pyhealth.interpret.methods.AvgEnsemble(model, experts)[source]#
Bases:
BaseInterpreterEnsembleEnsemble interpreter using uniform averaging (AGGMean / Borda).
Computes the consensus attribution as the simple arithmetic mean of the competitively-ranked attributions from all expert interpreters. This is the simplest ensemble strategy — every expert contributes equally regardless of its agreement with the others.
Because the inputs are already competitively ranked, averaging is equivalent (up to a constant factor) to the Borda count, which sums the ranks instead. The two methods therefore produce identical feature orderings.
Implements the AGGMean method from:
Rieger, L. and Hansen, L. K. “Aggregating Explanation Methods for Stable and Robust Explainability.” arXiv preprint arXiv:1903.00519, 2019.
See also the Borda aggregation in:
Chen, Y., Mancini, M., Zhu, X., and Akata, Z. “Ensemble Interpretation: A Unified Method for Interpretable Machine Learning.” arXiv preprint arXiv:2312.06255, 2023.
- Parameters:
model (
BaseModel) – The PyHealth model to interpret.experts (
list[BaseInterpreter]) – A list of at least threeBaseInterpreterinstances whoseattributemethods will be called to produce individual attribution maps.
Example
>>> from pyhealth.interpret.methods import IntegratedGradients, DeepLift, LimeExplainer >>> experts = [IntegratedGradients(model), DeepLift(model), LimeExplainer(model)] >>> ensemble = AvgEnsemble(model, experts) >>> attrs = ensemble.attribute(**batch)
Initialize the base interpreter.
- Parameters:
model (
BaseModel) – A trained PyHealth model to interpret. The model should be in evaluation mode during interpretation.
Note
Subclasses should call super().__init__(model) and then perform any method-specific initialization.
- attribute(**kwargs)#
Compute consensus attributions by ensembling all expert interpreters.
Each expert’s
attributemethod is called with the same inputs. The resulting attribution maps are flattened, competitively ranked to a common [0, 1] scale, and aggregated via the subclass-defined_ensemble()strategy.- Parameters:
**kwargs (
Tensor|tuple[Tensor,...]) – Input data dictionary from a dataloader batch. Should contain feature tensors (or tuples of tensors) keyed by the model’s feature keys, plus optional label or metadata tensors (which are forwarded to experts).- Return type:
- Returns:
Dictionary mapping each feature key to a consensus attribution tensor whose shape matches the corresponding input tensor.
- class pyhealth.interpret.methods.VarEnsemble(model, experts)[source]#
Bases:
BaseInterpreterEnsembleEnsemble interpreter using variance-weighted averaging (AGGVar).
Computes the consensus attribution by dividing the mean of the competitively-ranked expert attributions by their standard deviation (plus a small constant ε for numerical stability). Features that all experts agree are important receive high scores, while features with high inter-expert disagreement are suppressed.
Implements the AGGVar method from:
Rieger, L. and Hansen, L. K. “Aggregating Explanation Methods for Stable and Robust Explainability.” arXiv preprint arXiv:1903.00519, 2019.
- Parameters:
model (
BaseModel) – The PyHealth model to interpret.experts (
list[BaseInterpreter]) – A list of at least threeBaseInterpreterinstances whoseattributemethods will be called to produce individual attribution maps.
Example
>>> from pyhealth.interpret.methods import IntegratedGradients, DeepLift, LimeExplainer >>> experts = [IntegratedGradients(model), DeepLift(model), LimeExplainer(model)] >>> ensemble = VarEnsemble(model, experts) >>> attrs = ensemble.attribute(**batch)
Initialize the base interpreter.
- Parameters:
model (
BaseModel) – A trained PyHealth model to interpret. The model should be in evaluation mode during interpretation.
Note
Subclasses should call super().__init__(model) and then perform any method-specific initialization.
- attribute(**kwargs)#
Compute consensus attributions by ensembling all expert interpreters.
Each expert’s
attributemethod is called with the same inputs. The resulting attribution maps are flattened, competitively ranked to a common [0, 1] scale, and aggregated via the subclass-defined_ensemble()strategy.- Parameters:
**kwargs (
Tensor|tuple[Tensor,...]) – Input data dictionary from a dataloader batch. Should contain feature tensors (or tuples of tensors) keyed by the model’s feature keys, plus optional label or metadata tensors (which are forwarded to experts).- Return type:
- Returns:
Dictionary mapping each feature key to a consensus attribution tensor whose shape matches the corresponding input tensor.
- class pyhealth.interpret.methods.CrhEnsemble(model, experts, n_iter=20, low_confidence_threshold=None, early_stopping_threshold=None)[source]#
Bases:
BaseInterpreterEnsembleEnsemble interpreter using Conflict Resolution on Heterogeneous data (CRH).
Iteratively estimates a consensus attribution by reweighting experts according to their agreement with the current consensus estimate. Experts whose attributions are closer to the consensus receive higher weights, which in turn pulls the consensus toward more reliable experts.
This implements the truth-discovery algorithm from:
Li, Q., Li, Y., Gao, J., Zhao, B., Fan, W., and Han, J. “Resolving Conflicts in Heterogeneous Data by Truth Discovery and Source Reliability Estimation.” In Proceedings of the 2014 ACM SIGMOD International Conference on Management of Data (SIGMOD’14), pp. 1187–1198, 2014.
- Parameters:
model (
BaseModel) – The PyHealth model to interpret.experts (
list[BaseInterpreter]) – A list of at least threeBaseInterpreterinstances whoseattributemethods will be called to produce individual attribution maps.n_iter (
int) – Maximum number of CRH refinement iterations. Higher values allow more precise convergence at the cost of computation.low_confidence_threshold (
Optional[float]) – If set, batches where the standard deviation of the final expert weights falls below this value are considered low-confidence, and their consensus is replaced by a simple uniform average of all experts.early_stopping_threshold (
Optional[float]) – If set, the CRH loop terminates early when the maximum absolute change in the consensus vector between successive iterations is below this value.
Example
>>> from pyhealth.interpret.methods import DeepLift, IntegratedGradients, LimeExplainer >>> experts = [IntegratedGradients(model), DeepLift(model), LimeExplainer(model)] >>> ensemble = CrhEnsemble(model, experts, n_iter=30) >>> attrs = ensemble.attribute(**batch)
Initialize the base interpreter.
- Parameters:
model (
BaseModel) – A trained PyHealth model to interpret. The model should be in evaluation mode during interpretation.
Note
Subclasses should call super().__init__(model) and then perform any method-specific initialization.
- attribute(**kwargs)#
Compute consensus attributions by ensembling all expert interpreters.
Each expert’s
attributemethod is called with the same inputs. The resulting attribution maps are flattened, competitively ranked to a common [0, 1] scale, and aggregated via the subclass-defined_ensemble()strategy.- Parameters:
**kwargs (
Tensor|tuple[Tensor,...]) – Input data dictionary from a dataloader batch. Should contain feature tensors (or tuples of tensors) keyed by the model’s feature keys, plus optional label or metadata tensors (which are forwarded to experts).- Return type:
- Returns:
Dictionary mapping each feature key to a consensus attribution tensor whose shape matches the corresponding input tensor.