Spaces:
Sleeping
Sleeping
File size: 3,603 Bytes
81e3338 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | """
CloudPulse — SHAP explainability at inference time.
Loads the TreeExplainer trained in notebook 13 and computes per-prediction
SHAP values when the FastAPI service classifies a new incident.
Replaces the previous top-TF-IDF-terms explanation with true Shapley values.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
import joblib
import numpy as np
import shap
from scipy import sparse
class SHAPExplainer:
"""Wraps a SHAP TreeExplainer for the production XGBoost classifier."""
def __init__(self, explainer_path: Path, vocab: np.ndarray, label_encoder: Any):
self.explainer = joblib.load(explainer_path)
self.vocab = np.asarray(vocab)
self.le = label_encoder
self.classes_ = list(label_encoder.classes_)
def explain(self, x_tfidf: sparse.csr_matrix, predicted_class: str, top_k: int = 5) -> dict:
"""Return the top-k token contributions toward the predicted class.
Args:
x_tfidf : 1×n sparse vector (TF-IDF features for one incident)
predicted_class: the class label the classifier returned
top_k : number of top contributions to return
Returns:
{
"predicted_class": "high",
"top_contributions": [
{"token": "authentication", "tfidf_weight": 0.42, "shap_value": 0.18,
"direction": "toward_high"},
...
],
"expected_value_for_class": 0.34,
}
"""
if predicted_class not in self.classes_:
return {"error": f"unknown class: {predicted_class}"}
cls_idx = self.classes_.index(predicted_class)
# SHAP needs dense input. The vector is a single row.
x_dense = x_tfidf.toarray()
shap_vals = self.explainer.shap_values(x_dense)
# Normalise: SHAP returns either a list of (n, n_features) per class
# or a 3D array (n, n_features, n_classes) depending on version.
if isinstance(shap_vals, list):
sv = shap_vals[cls_idx][0]
else:
sv = shap_vals[0, :, cls_idx] if shap_vals.ndim == 3 else shap_vals[0]
# Only consider tokens that are actually present in the input
nonzero = np.nonzero(x_dense[0])[0]
if len(nonzero) == 0:
return {
"predicted_class": predicted_class,
"top_contributions": [],
"expected_value_for_class": float(self._expected_for_class(cls_idx)),
}
contributions = [
(self.vocab[fi], float(x_dense[0, fi]), float(sv[fi]))
for fi in nonzero
]
contributions.sort(key=lambda t: abs(t[2]), reverse=True)
top = []
for token, weight, sv_val in contributions[:top_k]:
top.append({
"token" : token,
"tfidf_weight": round(weight, 4),
"shap_value" : round(sv_val, 4),
"direction" : f"toward_{predicted_class}" if sv_val > 0 else f"away_from_{predicted_class}",
})
return {
"predicted_class" : predicted_class,
"top_contributions" : top,
"expected_value_for_class": float(self._expected_for_class(cls_idx)),
}
def _expected_for_class(self, cls_idx: int) -> float:
ev = self.explainer.expected_value
if isinstance(ev, (list, tuple, np.ndarray)):
return float(ev[cls_idx])
return float(ev)
|