pyhealth.interpret.methods.tree_shap#

Exact TreeSHAP attributions for gradient-boosted tree models such as XGBoostModel, computed by the tree library itself (no sampling). attribute returns one tensor per input field in the field’s shape. The column-level values, including codes that are absent from a sample, come from model.explain(**batch); model.mean_abs_shap(loader) gives the global ranking.

class pyhealth.interpret.methods.TreeSHAP(model)[source]#

Bases: BaseInterpreter

Exact TreeSHAP for GradientBoostedTreeModel.

Uses the tree library’s own exact Shapley values (pred_contribs in XGBoost) rather than sampling, so it is fast and deterministic. Attributions are on the margin (log-odds for classification) and are returned in the shape of each input field, like the other interpreters:

  • tensor / multi_hot fields: one value per input element.

  • code fields encoded with bag_of_codes and nested_multihot: each code’s contribution is split evenly over the positions holding it, and <pad> / <unk> positions get 0. A code that is absent can still contribute (its absence moved the prediction), but has no input position; GradientBoostedTreeModel.explain() keeps those in column form.

Parameters:

model (GradientBoostedTreeModel) – A fitted gradient-boosted tree model.

Examples

>>> from pyhealth.interpret.methods import TreeSHAP
>>> attributions = TreeSHAP(model).attribute(**batch)  
>>> attributions["labs"].shape == batch["labs"].shape  
True

Initialize the base interpreter.

Parameters:

model (GradientBoostedTreeModel) – 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(target_class_idx=None, **data)[source]#

Computes TreeSHAP attributions in the shape of each input field.

Parameters:
  • target_class_idx (Optional[int]) – Class (multiclass) or label (multilabel) to explain; defaults to the highest-scoring one per sample. Ignored for binary and regression.

  • **data (Any) – A batch from the dataloader.

Return type:

dict[str, Tensor]

Returns:

{field: attribution tensor} with each tensor shaped like the field’s input.