Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -98,18 +98,28 @@ def explain(batch: Optional[BatchInputData] = None, limit: int = 100):
|
|
| 98 |
try:
|
| 99 |
if batch:
|
| 100 |
X = pd.DataFrame([item.dict() for item in batch.data])
|
|
|
|
| 101 |
else:
|
| 102 |
X = fetch_test_data(limit=limit)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
explainer = shap.Explainer(model, X)
|
| 105 |
shap_values = explainer(X)
|
| 106 |
|
| 107 |
-
# Aggregate mean absolute SHAP value per feature
|
| 108 |
shap_summary = pd.DataFrame({
|
| 109 |
"feature": X.columns,
|
| 110 |
"mean_abs_shap": np.abs(shap_values.values).mean(axis=0)
|
| 111 |
}).sort_values("mean_abs_shap", ascending=False)
|
| 112 |
|
|
|
|
|
|
|
| 113 |
return {
|
| 114 |
"n_samples": len(X),
|
| 115 |
"shap_summary": shap_summary.to_dict(orient="records")
|
|
@@ -117,6 +127,8 @@ def explain(batch: Optional[BatchInputData] = None, limit: int = 100):
|
|
| 117 |
|
| 118 |
except Exception as e:
|
| 119 |
import traceback
|
|
|
|
|
|
|
| 120 |
return {"error": str(e), "trace": traceback.format_exc()}
|
| 121 |
|
| 122 |
# =====================================================
|
|
|
|
| 98 |
try:
|
| 99 |
if batch:
|
| 100 |
X = pd.DataFrame([item.dict() for item in batch.data])
|
| 101 |
+
source = "client batch"
|
| 102 |
else:
|
| 103 |
X = fetch_test_data(limit=limit)
|
| 104 |
+
source = f"NoCoDB (limit={limit})"
|
| 105 |
+
|
| 106 |
+
print(f"[DEBUG] SHAP explain called using {source} | shape={X.shape} | cols={list(X.columns)}")
|
| 107 |
+
|
| 108 |
+
# Ensure model is a pipeline
|
| 109 |
+
if hasattr(model, "named_steps"):
|
| 110 |
+
explainer = shap.Explainer(model.named_steps["classifier"], model.named_steps["preprocessor"].transform(X))
|
| 111 |
+
else:
|
| 112 |
+
explainer = shap.Explainer(model, X)
|
| 113 |
|
|
|
|
| 114 |
shap_values = explainer(X)
|
| 115 |
|
|
|
|
| 116 |
shap_summary = pd.DataFrame({
|
| 117 |
"feature": X.columns,
|
| 118 |
"mean_abs_shap": np.abs(shap_values.values).mean(axis=0)
|
| 119 |
}).sort_values("mean_abs_shap", ascending=False)
|
| 120 |
|
| 121 |
+
print(f"[DEBUG] SHAP summary created successfully with {len(shap_summary)} features.")
|
| 122 |
+
|
| 123 |
return {
|
| 124 |
"n_samples": len(X),
|
| 125 |
"shap_summary": shap_summary.to_dict(orient="records")
|
|
|
|
| 127 |
|
| 128 |
except Exception as e:
|
| 129 |
import traceback
|
| 130 |
+
print("[ERROR] SHAP explain failed:", e)
|
| 131 |
+
print(traceback.format_exc())
|
| 132 |
return {"error": str(e), "trace": traceback.format_exc()}
|
| 133 |
|
| 134 |
# =====================================================
|