API reference#
The public interface consists of two explainers, an explanation container, and two function adapters. Constructors below are generated from the installed source, so argument defaults track the implementation.
Prediction explainer#
Call Explainer(model, baseline, **options)(data) to obtain an Explanation.
The baseline and output contracts are detailed in baselines
and semantics.
Control |
Purpose |
|---|---|
|
Relative weights aligned with baseline rows |
|
Named preprocessing boundary, using original inputs |
|
Fixed quadrature node count, or automatic refinement when omitted |
|
Reconstruction checks and automatic refinement trigger |
|
|
|
Explicit |
|
Central-difference perturbation and batch bound |
|
Smooth-backend path-row batch bound |
|
Numerical tree scan and refinement resolution |
|
Explicit finite-score definition for zero tree probabilities |
|
Framework classification versus multi-output regression semantics |
- class unifiedig.Explainer(model, baseline, *, baseline_weights=None, attribute_after=None, n_steps=None, check_completeness=True, on_incomplete='warn', completeness_atol=1e-06, completeness_rtol=0.0001, fallback=None, finite_difference_step=1e-05, finite_difference_batch_size=8192, gradient_batch_size=8192, tree_grid_size=1024, tree_max_refine=4, probability_floor=None, output_kind='auto')#
Explain a model with Integrated Gradients through one stable interface.
baselineis either one reference sample, a shared baseline matrix, or a background object exposing alignedrowsandweightsproperties. Every input is attributed against every baseline; matching input and baseline row counts do not imply pairing.n_stepscontrols numerical backends and is ignored by exact backends. When omitted, gradient backends start at 16 nodes and retry at 32 or 64 only if completeness fails. An explicit integer disables this automatic refinement. Withcheck_completeness=True,on_incomplete="warn"emits a RuntimeWarning if tolerances still fail after refinement;"raise"raises RuntimeError instead of returning an explanation. Disabling the check disables both actions, but residuals are still returned.Classifiers are explained on their decision-score scale. Binary outputs use one margin; multiclass outputs use the complete centered score vector. Probability attributions are intentionally not offered. Set
fallback="finite_difference"to explain an otherwise unsupported smooth sklearn estimator numerically, orfallback="tree_numeric"to use approximate path-event detection for a recognized piecewise-constant tree model. Probability-only tree classifiers are transformed to log scores;probability_floormust be set explicitly if any path probability is zero. Specialized backends always take precedence. Differentiable JAX functions are selected explicitly by wrapping them inunifiedig.JaxModel; arbitrary TensorFlow functions useunifiedig.TensorFlowModel. TensorFlow-backed Keras models work directly.For a fitted sklearn pipeline,
attribute_after="scale"attributes to features after the named preprocessing step. Nested paths such as"preprocess__scale"are accepted. Always supply original observations and baselines: both are transformed together before constructing paths in the selected space. The defaultNoneexplains original model inputs.Vector-valued automatic-gradient outputs are treated as class scores by default. Set
output_kind="regression"for multi-output regression. Known sklearn and tree estimators declare their own output semantics and do not need this option. Keras 3 models use their configured TensorFlow, JAX, or PyTorch backend automatically.- __call__(data)#
Call self as a function.
Loss explainer#
- class unifiedig.LossExplainer(model, baseline, *, baseline_weights=None, attribute_after=None, loss='squared_error', direction='loss_change', n_steps=None, check_completeness=True, on_incomplete='warn', completeness_atol=1e-06, completeness_rtol=0.0001, fallback=None, finite_difference_step=1e-05, finite_difference_batch_size=8192, gradient_batch_size=8192, probability_floor=None, output_kind='auto')#
Attribute squared-error or log-loss changes with Integrated Gradients.
Model selection, baselines, numerical controls, and output semantics match
unifiedig.Explainer. Classification consumes raw decision scores, margins, or logits; probability outputs are not attributed.Values normally sum to endpoint loss minus baseline loss, so negative values reduce loss.
direction="loss_reduction"negates only the final attribution values. Base values and diagnostics retain the default loss-change direction.- Parameters:
model (object) – Fitted model accepted by
unifiedig.Explainerand a loss-aware backend.baseline (array-like or background object) – One baseline sample or a shared weighted baseline distribution.
baseline_weights (array-like, optional) – Nonnegative weights aligned with baseline rows.
loss ({"squared_error", "log_loss"}, default="squared_error") – Squared error for scalar regression outputs, or binary/multiclass log loss for raw classification scores.
direction ({"loss_change", "loss_reduction"}, default="loss_change") – Orientation of returned attribution values. The alternative reverses values only.
attribute_after (str, optional) – Attribute after a named pipeline preprocessing step. Supply original data and baselines; both are transformed together. None keeps inputs.
n_steps (int, optional) – Gauss–Legendre nodes for numerical gradient backends. When omitted, loss attribution starts at 16 and may refine to 32 or 64.
Notes
The remaining numerical and output arguments have the same meanings as on
unifiedig.Explainer. Callingexplainer(data, y)returns anunifiedig.Explanationwith one scalar loss attribution per input feature and observation.- __call__(data, y)#
Return observation-level feature attributions for realized loss.
- property n_steps#
Current numerical integration resolution.
Explanation#
- class unifiedig.Explanation(values, base_values, data, feature_names=None, output_names=None, completeness_error=None, attribute_after=None)#
Parallel arrays describing feature attributions.
The field names intentionally mirror the useful subset of
shap.Explanation. Arrays use a leading sample dimension.attribute_afterrecords the chosen pipeline boundary (None for original inputs);dataandfeature_namesdescribe that selected space.- contrast(first, second)#
Return the scalar decision-score contrast
first - second.Multiclass explanations store centered class scores. Subtracting two coordinates recovers the invariant pairwise raw-score margin without evaluating the model or recomputing Integrated Gradients.
- property max_abs_completeness_error#
Largest absolute completeness residual, or
Noneif unavailable.
- to_shap()#
Return an equivalent
shap.Explanationwhen SHAP is installed.
Function adapters#
- class unifiedig.JaxModel(predict_fn, params=None, vectorize=False, call_kwargs=None, output_names=None, dtype=None)#
Describe a JAX prediction function for
unifiedig.Explainer.This is a lightweight calling-convention adapter. It stores references to the supplied function and parameters; it does not convert, copy, train, or otherwise modify a model.
predict_fnis called aspredict_fn(X, **call_kwargs)whenparamsis omitted and aspredict_fn(params, X, **call_kwargs)otherwise. It must return one scalar or one output vector per sample. Setvectorize=Trueonly when the function accepts a single sample.
- class unifiedig.TensorFlowModel(predict_fn, call_kwargs=None, output_names=None, dtype=None)#
Describe a TensorFlow prediction function for
unifiedig.Explainer.predict_fnmust accept a batch as its first argument and return one scalar or one output vector per sample.call_kwargsare forwarded on every inference call. Direct TensorFlow-backed Keras models do not need this adapter.