Testland
Browse all skills & agents

alibi-explainability

Generates model explanations with Alibi Explain - Anchors, Integrated Gradients, Kernel/Tree SHAP, ALE, Counterfactual Instances. Wires explainer.fit + explainer.explain into model-evaluation pipelines so that every flagged prediction ships with a "why" record auditors can reason about. Use when a model decision must be explainable to an auditor, regulator, or affected user, or when a support team cannot answer why a specific prediction was made.

Install with skills.sh (any agent)

npx skills add testland/qa --skill alibi-explainability
View source

alibi-explainability

Alibi Explain provides explanation algorithms answering: "How do predictions change with feature inputs? Which features matter for a prediction? What minimal changes would alter a prediction? How does each feature contribute to predictions?" per the Alibi Explain docs (opens in new window).

When to use

  • Compliance / regulator inquiry: "explain this denied loan prediction" - generate counterfactual + per-feature attribution.
  • Model debugging: a single instance got the wrong answer; explain why.
  • High-risk system audit (EU AI Act Annex III): every prediction ships with a stored explanation record.

Step 1 - Install

pip install alibi

Per the Alibi Explain docs (opens in new window).

Step 2 - Pick the right explainer category

Per the Alibi Explain docs (opens in new window):

CategoryExplainersWhen
Global feature attributionAccumulated Local Effects (ALE), Partial Dependence"Across the whole input space, how does feature X drive output?"
Local necessary featuresAnchors, Pertinent Positives"What minimal feature subset locks in this prediction?"
Local feature attributionIntegrated Gradients, Kernel SHAP, Tree SHAP"What did each feature contribute to this prediction?"
CounterfactualCounterfactual Instances, CEM, CFProto, CounterfactualRL"What minimal change flips this prediction?"

Step 3 - The two-method interface

Every Alibi explainer follows the same pattern:

explainer.fit(X_train)        # Some explainers - preparation phase
explanation = explainer.explain(instance)
print(explanation.data)       # Per-explainer schema

Per the Alibi Explain docs (opens in new window) Explainer Interface section.

Step 4 - Anchors example (tabular)

from alibi.explainers import AnchorTabular

predict_fn = lambda x: classifier.predict(x)
explainer = AnchorTabular(
    predict_fn,
    feature_names=FEATURE_NAMES,
    categorical_names=CATEGORICAL_INDEX,
)
explainer.fit(X_train)

explanation = explainer.explain(X_test[0])
print("Anchor: %s" % (" AND ".join(explanation.anchor)))
print("Precision: %.2f" % explanation.precision)
print("Coverage: %.2f" % explanation.coverage)

Anchors return a minimal feature subset such that the prediction holds with precision confidence over coverage of the input space.

Step 5 - Counterfactual example

from alibi.explainers import CounterfactualProto

cf = CounterfactualProto(
    predict_fn,
    shape=X_train[0:1].shape,
    use_kdtree=True,
    theta=10.,
)
cf.fit(X_train)

explanation = cf.explain(X_test[0:1])
print("Counterfactual: %s" % explanation.cf["X"])
print("Original class: %d, CF class: %d" % (
    explanation.orig_class, explanation.cf["class"]
))

Counterfactual = "the closest input that flips the prediction" - auditor-friendly format.

Step 6 - Persist explanations as audit records

import json
from pathlib import Path

def explain_and_log(instance_id, instance, explainer, log_dir="explanations"):
    explanation = explainer.explain(instance)
    record = {
        "instance_id": instance_id,
        "timestamp": "...",
        "explainer": type(explainer).__name__,
        "data": explanation.data,
        "meta": explanation.meta,
    }
    Path(log_dir, f"{instance_id}.json").write_text(json.dumps(record))

For high-risk systems, store every explanation alongside the prediction (immutable audit log). Pair with an audit-trail test skill for storage assertions.

Step 7 - Don't confuse with alibi-detect

Alibi Explain is the explanation library. Drift detection uses the sister package alibi-detect (pip install alibi-detect) - that covers concept drift, adversarial detection, outlier detection. They share governance but are separate packages.

Anti-patterns

Anti-patternWhy it failsFix
Use Kernel SHAP on every prediction in real timeO(n) model calls per explanation; latency-killerTree SHAP for tree models; cache for repeated instances
Show feature attributions to non-technical stakeholders"0.3 contribution from 'income'" is jargonUse Counterfactuals (Step 5) - natural-language friendly
Skip fit() stepSome explainers (Anchors) need training data summaryAlways fit on representative data (Step 3)
Treat explanation as ground-truth causalityAttributions are model-relative, not causalDocument this in audit trail metadata
Mix alibi and alibi-detect packagesDifferent scope; same install string causes confusionInstall both explicitly when needed (Step 7)

Limitations

  • Counterfactual explainers can produce out-of-distribution instances; constrain via prototypes or domain rules.
  • Integrated Gradients requires gradient access (TF/PyTorch native); no support for opaque APIs (SaaS LLMs).

References

Related skills

deepchecks-tests

Run Deepchecks suites (data integrity, train-test validation, model evaluation) on tabular / NLP / vision data + models. Pass `result.passed_conditions()` to CI to gate on regressions; the same checks run during research, CI, and production monitoring per the Deepchecks lifecycle posture. Use before training to catch train-test leakage and data-integrity defects in a tabular, NLP, or vision dataset, and to re-run the same suite on production samples to detect drift.

evidently-monitoring

Use Evidently OSS (100+ evaluation metrics, declarative testing API) to detect data drift, target drift, and model-performance regression, wired into CI as a gate (a Report run with include_tests) and into production monitoring as a continuous check; reports as HTML + JSON for both human review and pipeline assertions. Use when you need a drift or quality gate, or a scheduled monitoring job, for a tabular ML model. Built on the Evidently API specifically: for DeepChecks-based validation suites use deepchecks-tests instead.

fairlearn-fairness

Compute group fairness metrics (selection rate, demographic parity, equalized odds) per sensitive feature with `MetricFrame`, then mitigate disparities using Reductions algorithms (`ExponentiatedGradient` with constraint = `DemographicParity`/`EqualizedOdds`). Wire group-disaggregated assertions into the model-evaluation gate. Use when a model's decisions affect people and a stakeholder, auditor, or regulation (ECOA, GDPR Art. 22, EU AI Act high-risk) requires evidence of per-group outcomes, or when someone reports the model treats a specific group worse.

giskard-tests

Test ML models with Giskard's scan() vulnerability detector + test catalog (performance, robustness, fairness, data leakage, ethical issues) for tabular and NLP models. Wrap a prediction function in giskard.Model + a DataFrame in giskard.Dataset; emit test suites that pass/fail in CI. Use when a trained tabular or NLP model is about to ship with no test suite of its own, or when a feature-engineering or hyperparameter change needs a pre-merge scan for newly introduced vulnerabilities.

model-performance-regression-gate

Computes held-out metrics (accuracy, F1, AUC, RMSE) for a retrained model and compares them against the current production model, failing promotion when any metric regresses beyond a configured tolerance. Adds per-segment checks via Deepchecks WeakSegmentsPerformance so a model that improves globally but regresses on a key slice is still blocked. Use when a retrained model is a candidate for promotion and the CI pipeline must enforce a per-metric pass/fail gate before the artifact is pushed to the model registry.

model-risk-evidence-matrix

Assigns a machine learning model to a low, medium, or high risk tier from what its predictions decide about people, then derives the fairness and explainability evidence that tier must produce: group metrics per declared sensitive feature, intersectional breakdowns with per-cell counts, vulnerability scan categories, a drift monitoring plan, and per-prediction explanation logs. Supplies conventional demographic parity difference bands, a per-vulnerability-category blocking table, and evidence rules that mark a bundle incomplete or self-contradicting. Use when a model release candidate is up for promotion and someone must decide which fairness artifacts are mandatory rather than nice to have, or when a model card declares a risk tier and the attached evidence bundle has to be checked against what that tier demands.