Spaces:
Sleeping
Sleeping
Download api/explainer.py from CloudPulse/ML_classifier: direct link, hf CLI and curl.
- Browser
- Download file 3.6 kB
-
https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/explainer.py
- Command line
-
hf download hf://spaces/CloudPulse/ML_classifier/api/explainer.py
-
curl -L -o explainer.py https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/explainer.py
3.6 kB
| """ | |
| 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) | |