API reference#
The primary interfaces are TreeIG for exact structural attribution,
TreeIGNumeric for numerical fallback, and Explanation for results.
See the user guide for weighted-baseline shapes and runnable examples.
- class treeig.TreeIG(model: Any, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, time_tol: float = 1e-10, tie_policy: str = 'first', target: int | None = None)#
Exact integrated-gradient attribution for supported tree-based models.
TreeIG computes feature attributions for fitted tree ensembles by exactly summing the prediction jumps encountered along the straight-line path from a baseline input to each evaluation input. For supported tree models, this avoids numerical quadrature and produces an additive decomposition of the model-output difference.
For an input row
xand baselinex0, the returned attributions satisfy, up to floating-point error,attributions.sum() = f(x) - f(x0)
where
fis the selected scalar model output.Regression models use their scalar prediction output. Supported classification models are attributed on raw class scores, margins, or logits, not probabilities. Binary classifiers use the positive-class margin by default;
target=0attributes the negative of that margin. Multiclass classifiers require a selected class target.- Parameters:
model (object) – Fitted supported tree-based model. Supported regression backends include scikit-learn decision trees, random forests, extra-trees regressors, gradient boosting regressors, XGBoost regressors and boosters, and LightGBM regressors and boosters. Supported classification backends are additive-score classifiers with raw margin/logit outputs.
baseline (array-like of shape (n_features,), optional) – Default baseline input
x0. If omitted, a baseline must be supplied to methods that compute attributions.time_tol (float, default=1e-10) – Tolerance used when ordering path-crossing times along the straight line from the baseline to each input row.
tie_policy ({"first"}, default="first") – Rule for coincident active split crossings. Only
"first"is currently implemented. The argument is reserved for future allocation rules.target (int or None, default=None) – Scalar model-output target. For regression, use
Noneor0. For binary additive-score classification,Noneor1selects the positive-class margin and0selects the negative margin. For multiclass classification, this selects the class-margin output.
- model#
The fitted model passed at construction.
- Type:
object
- n_features_in_#
Number of input features expected by the extracted tree representation.
- Type:
int
- backend#
Backend identifier inferred from the fitted model.
- Type:
str
Notes
TreeIG currently requires finite numeric inputs and finite numeric baselines. Missing-value routing, categorical splits, probability-output attribution, CatBoost models, and classifiers that average probabilities or vote shares directly are not currently supported.
- attribute(X: ndarray, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, target: int | None = None, batch_size: int | None = None, baseline_batch_size: int | None = None, return_by_baseline: bool = False) ndarray#
Compute exact feature attributions for one or more input rows.
This is the fastest public attribution method. It computes feature attributions only and does not call
model.predictto construct endpoint diagnostics.- Parameters:
X (array-like of shape (n_samples, n_features)) – Evaluation inputs. All entries must be finite numeric values.
baseline (array-like of shape (n_features,), optional) – Baseline input used for the path integration. If omitted, the default baseline supplied at construction is used.
target (int or None, default=None) – Scalar model-output target to attribute. If omitted, the target supplied at construction is used. See
TreeIGfor the regression and classification target conventions.batch_size (int or None, default=None) – Number of rows to process per batch. If
None, all rows are processed in one call. Use a positive integer to reduce peak memory use for largeX.
- Returns:
attributions – Exact integrated-gradient feature attributions. For each row,
attributions[i].sum()equals the selected model output atX[i]minus the selected model output at the baseline, up to floating-point error.- Return type:
ndarray of shape (n_samples, n_features)
- Raises:
ValueError – If no baseline is available, if
Xhas an incompatible shape, or ifXor the baseline contains non-finite values.
Examples
>>> import numpy as np >>> from treeig import TreeIG >>> >>> x0 = np.mean(X_train, axis=0) >>> explainer = TreeIG(model, baseline=x0) >>> attributions = explainer.attribute(X_test) >>> attributions.shape (X_test.shape[0], X_test.shape[1])
- diagnostics(X: ndarray, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, target: int | None = None, batch_size: int | None = None, baseline_batch_size: int | None = None)#
Return per-row split-event details and their aggregate summary.
- explain(X: ndarray, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, target: int | None = None, batch_size: int | None = None, baseline_batch_size: int | None = None) Explanation#
Return a plotting-compatible feature-attribution explanation.
The returned
Explanationfollows the same contract asunifiedig.Explanation. It contains attribution values, repeated baseline outputs, evaluation data, names when available, and signed completeness errors. CallExplanation.to_shap()to use SHAP’s plotting functions without changing the attribution semantics.Use
attribute()for the fastest array-only path anddiagnostics()for split-event and aggregate diagnostic details.
- loss_attribution(X: ndarray, y: ndarray, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, loss: str = 'squared_error', target: int | None = None, batch_size: int | None = None) Dict[str, Any]#
Attribute average loss reduction to input features.
This method decomposes the improvement in loss from the baseline prediction to the model prediction. The resulting feature values sum to average baseline loss minus average model loss, up to floating-point error.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Evaluation inputs.
y (array-like of shape (n_samples,)) – Observed outcomes or labels. For
loss="squared_error", values are interpreted as numeric outcomes. Forloss="log_loss", values must be binary labels in{0, 1}.baseline (array-like of shape (n_features,) or (n_baselines, n_features), optional) – Baseline input or distribution. If omitted, the default baseline supplied at construction is used.
baseline_weights (array-like of shape (n_baselines,), optional) – Nonnegative weights, normalized internally. If omitted, multiple baseline rows receive equal weight.
loss ({"squared_error", "log_loss"}, default="squared_error") – Loss function used to measure improvement.
"log_loss"is currently for binary classification.target (int or None, default=None) – Scalar model-output target. For binary log-loss, this should select the binary margin convention used by the fitted model.
batch_size (int or None, default=None) – Currently unused. Present for API consistency with attribution methods.
- Returns:
result – Dictionary with the following entries:
"observation_values"ndarray of shape (n_samples, n_features)Per-observation feature contributions to loss reduction.
"values"ndarray of shape (n_features,)Average feature contributions to loss reduction.
"standard_errors"ndarray of shape (n_features,)Standard errors of the average feature contributions, computed across observations.
"baseline_loss"floatAverage loss at the baseline prediction.
"model_loss"floatAverage loss at the endpoint model predictions.
"total"floatbaseline_loss - model_loss."baseline_prediction"floatSelected model output at the baseline.
"endpoint_prediction"ndarray of shape (n_samples,)Selected model output at each input row.
"loss"strName of the loss function.
- Return type:
dict
Notes
Positive values indicate features that reduce loss on average relative to the baseline prediction. Negative values indicate features that increase loss on average.
Examples
>>> result = explainer.loss_attribution(X_test, y_test) >>> result["values"] >>> result["total"]
- model_output(X: ndarray, target: int | None = None) ndarray#
Return the scalar model output that TreeIG attributes.
- multiclass_loss_attribution(X: ndarray, y: ndarray, baseline: ndarray | None = None, baseline_weights: ndarray | None = None, n_classes: int | None = None) Dict[str, Any]#
Attribute multiclass log-loss reduction to input features.
This method decomposes the improvement in multiclass log loss from baseline class scores to endpoint class scores. It computes traces for each class-margin output and combines them into a loss-reduction attribution.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Evaluation inputs.
y (array-like of shape (n_samples,)) – Integer class labels. Labels must be nonnegative. The labels are interpreted as class indices.
baseline (array-like of shape (n_features,) or (n_baselines, n_features), optional) – Baseline input or distribution. If omitted, the default baseline supplied at construction is used.
baseline_weights (array-like of shape (n_baselines,), optional) – Nonnegative weights, normalized internally.
n_classes (int or None, default=None) – Number of classes. If omitted,
len(model.classes_)is used. Provide this explicitly for models that do not exposeclasses_.
- Returns:
result – Dictionary with the following entries:
"observation_values"ndarray of shape (n_samples, n_features)Per-observation feature contributions to multiclass log-loss reduction.
"values"ndarray of shape (n_features,)Average feature contributions.
"standard_errors"ndarray of shape (n_features,)Standard errors of the average feature contributions.
"baseline_loss"floatAverage multiclass log loss at the baseline class scores.
"model_loss"floatAverage multiclass log loss at the endpoint class scores.
"total"floatbaseline_loss - model_loss."loss"strEqual to
"multiclass_log_loss".
- Return type:
dict
Notes
This method uses raw class-score traces, not probability-output attributions. Positive values indicate features that reduce multiclass log loss on average relative to the baseline class scores.
- trace(X: ndarray, baseline: ndarray | None = None, target: int | None = None) Dict[str, Any]#
Return ordered split-crossing events along each attribution path.
This advanced method exposes the event representation used internally by TreeIG. It is intended for downstream scalar-functional attribution, including loss-based decompositions. It returns path events rather than feature attribution sums.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Evaluation inputs.
baseline (array-like of shape (n_features,) or (n_baselines, n_features), optional) – Baseline input or baseline distribution. If omitted, the default baseline supplied at construction is used.
baseline_weights (array-like of shape (n_baselines,), optional) – Nonnegative baseline weights. They are normalized internally. Omit for a single baseline or equal weighting.
target (int or None, default=None) – Scalar model-output target.
- Returns:
trace – Dictionary with the following entries:
"counts"ndarray of shape (n_samples,)Number of valid events for each observation.
"times"ndarray of shape (n_samples, max_events)Path-crossing times. For row
i, only the firstcounts[i]entries are valid."features"ndarray of shape (n_samples, max_events)Feature index associated with each valid split-crossing event.
"jumps"ndarray of shape (n_samples, max_events)Prediction jump associated with each valid event.
"baseline_prediction"floatSelected model output at the baseline.
"endpoint_prediction"ndarray of shape (n_samples,)Selected model output at each input row.
"baseline"ndarray of shape (n_features,)Prepared baseline used in the computation.
"target"int or NoneResolved target used in the computation.
- Return type:
dict
Notes
Returned event arrays are padded to a common width. Padding entries beyond
counts[i]are not part of the path for observationi.
- warmup(X: ndarray, baseline: ndarray | None = None, target: int | None = None)#
Trigger JIT compilation and cache baseline tree outputs.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Sample inputs used to trigger compilation. Only up to the first two rows are used.
baseline (array-like of shape (n_features,), optional) – Baseline input. If omitted, the default baseline supplied at construction is used.
target (int or None, default=None) – Scalar model-output target.
- Returns:
self – The fitted TreeIG attribution object.
- Return type:
- class treeig.TreeIGNumeric(model, baseline, target=None, *, probability_to_score: bool = True, probability_floor=None, **engine_kwargs)#
Model-agnostic numeric TreeIG-style explainer.
TreeIGNumericapplies numeric path-event detection to a fitted model. It is designed for piecewise-constant models whose tree structure is not parsed by the exactTreeIGbackend. The class mirrors the high-level TreeIG API but intentionally provides different guarantees.- Parameters:
model (object) – Fitted model exposing a supported prediction interface. Raw margins are used when available; otherwise scores are derived from probabilities by default. Class probabilities require explicit opt-in.
baseline (array-like of shape (p,)) – Baseline input
x0for the interpolation path.target (int or None, default=None) – Target output for classification models. Binary classifiers default to the positive-class margin or derived log odds. Multiclass outputs require an explicit target.
probability_to_score (bool, default=True) – For classifiers without native margins, transform probabilities to binary log odds or centered multiclass log scores. Set explicitly to
Falseto explain a class probability instead.probability_floor (float or None, default=None) – Explicit lower bound used before the logarithm. Without a floor, zero probabilities raise rather than being clipped silently.
**engine_kwargs – Optional controls passed to
NumericEngine, such asgrid_size,max_refine,t_min,tol,residual_atol,residual_rtol, andwarn_residual. SeeNumericEnginefor details.
Notes
This class does not parse split thresholds and should not be described as exact structural TreeIG. It is a structure-free numerical event detector whose accuracy depends on recovering the relevant prediction jumps along the path.
- diagnostics(X)#
Return per-row numerical event details and their summary.
- explain(X) Explanation#
Return a plotting-compatible feature-attribution explanation.
- model_output(X) ndarray#
Return the scalar model output attributed by this explainer.
The output scale follows the model adapter: raw margins are preferred for classifiers, derived log scores are used when no margin interface exists, and regressors use their predictions. Class probabilities are attributed only with explicit
probability_to_score=Falseand no native margin interface.targetselection is the same as forattribute().
- class treeig.Explanation(values: NDArray[floating], base_values: NDArray[floating], data: NDArray[Any], feature_names: Sequence[str] | None = None, output_names: Sequence[str] | None = None, completeness_error: NDArray[floating] | None = None)#
Parallel arrays describing feature attributions.
The contract matches
unifiedig.Explanationand mirrors the useful subset ofshap.Explanation. Arrays use a leading sample dimension.- property max_abs_completeness_error: float | None#
Largest absolute completeness residual, or
Noneif unavailable.
- to_shap() Any#
Return an equivalent
shap.Explanationwhen SHAP is installed.
- treeig.compute(model: Any, baseline: ndarray, X: ndarray, time_tol: float = 1e-10, tie_policy: str = 'first', target: int | None = None, batch_size: int | None = None)#
Convenience function returning a TreeIG explanation object.
This is a functional wrapper around
TreeIG(...).explain(...). It constructs a temporaryTreeIGobject and returns the output ofexplain.- Parameters:
model (object) – Fitted supported tree-based model.
baseline (array-like of shape (n_features,)) – Baseline input.
X (array-like of shape (n_samples, n_features)) – Evaluation inputs.
time_tol (float, default=1e-10) – Tolerance used when ordering path-crossing times.
tie_policy ({"first"}, default="first") – Rule for coincident active split crossings. Only
"first"is currently implemented.target (int or None, default=None) – Scalar model-output target.
batch_size (int or None, default=None) – Number of rows to process per batch.
- Returns:
explanation – Plotting-independent explanation containing attribution values, baseline outputs, evaluation data, names, and completeness errors.
- Return type:
See also
TreeIGObject-oriented interface.
TreeIG.attributeFast attribution method without diagnostics.
TreeIG.explainPlotting-compatible explanation method.
TreeIG.diagnosticsSplit-event and aggregate diagnostic details.
- treeig.compute_numeric(model, baseline, X, target=None, **engine_kwargs)#
Functional mirror of
TreeIGNumeric.
- treeig.supports(model: Any) bool#
Return whether
modelhas an exact TreeIG backend.
The optional GPU interface is described separately in GPU support.