Overview
Concrete tool for generating anchor-based explanations for text classification models using the Alibi library and spaCy NLP provided by the KServe sample code.
Description
AnchorText extends ExplainerWrapper and wraps the Alibi AnchorText explainer. During construction, it receives a prediction function and an optional pre-built Alibi AnchorText explainer instance. If no explainer is provided, it lazily loads a spaCy language model (defaulting to en_core_web_md) and creates the AnchorText explainer on the first explain() call using an "unknown" sampling strategy. The explain() method extracts the first text input from the batch, checks whether the predictor returns class labels or probabilities (applying ArgmaxTransformer if needed), and runs the anchor text explanation algorithm. The result identifies which words in the text are sufficient for the classification decision.
Usage
Use this class as part of the Alibi explainer server pipeline when you need to generate word-level explanations for text classification models, identifying which words drive the model's prediction.
Code Reference
Source Location
Signature
class AnchorText(ExplainerWrapper):
def __init__(
self,
predict_fn: Callable,
explainer: Optional[alibi.explainers.AnchorText],
spacy_language_model: str = "en_core_web_md",
**kwargs,
):
...
def explain(self, inputs: List, headers: Dict[str, str] = None) -> Explanation:
...
Import
from alibiexplainer.anchor_text import AnchorText
I/O Contract
Inputs
Constructor
| Name |
Type |
Required |
Description
|
| predict_fn |
Callable |
Yes |
Prediction function that accepts text input and returns predictions
|
| explainer |
Optional[alibi.explainers.AnchorText] |
No |
A pre-built Alibi AnchorText explainer instance; if None, one is created lazily
|
| spacy_language_model |
str |
No |
Name of the spaCy language model to load (default: "en_core_web_md")
|
| **kwargs |
dict |
No |
Additional keyword arguments passed to the Alibi explain call
|
explain()
| Name |
Type |
Required |
Description
|
| inputs |
List |
Yes |
List of text strings to explain (first text is used)
|
| headers |
Dict[str, str] |
No |
Optional HTTP headers
|
Outputs
explain()
| Name |
Type |
Description
|
| anchor_exp |
Explanation |
Alibi Explanation object containing anchor words and metadata
|
Usage Examples
Basic Usage
from alibiexplainer.anchor_text import AnchorText
import numpy as np
# Define a text prediction function
def my_predict_fn(texts):
# Returns class probabilities for each text
return np.array([[0.1, 0.9]])
wrapper = AnchorText(
predict_fn=my_predict_fn,
explainer=None,
spacy_language_model="en_core_web_md"
)
# Generate an explanation for a text input
texts = ["This movie was absolutely fantastic and wonderful"]
explanation = wrapper.explain(texts)
print(explanation.anchor) # e.g., ["fantastic", "wonderful"]
Related Pages
Page Connections
Double-click a node to navigate. Hold to expand connections.