-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
585 lines (485 loc) · 18.1 KB
/
main.py
File metadata and controls
585 lines (485 loc) · 18.1 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
from typing import Any, Dict, List
import numpy as np
import pandas as pd
import joblib
import shap
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from pydantic import BaseModel
from io import StringIO
import io
import matplotlib
matplotlib.use("Agg") # important for server environments (no GUI)
import matplotlib.pyplot as plt
from fastapi.responses import StreamingResponse
MODEL_PATH = "risk_model.pkl"
FEATURES_PATH = "feature_names.pkl"
model = None
feature_names: List[str] = []
explainer = None
def ffloat(x: Any, ndigits: int = 6) -> float:
"""Convert to float safely and round."""
return float(np.round(float(np.ravel(x)[0]), ndigits))
def clean_feature_name(feat: str) -> str:
"""Optional: make one-hot names easier to read."""
return feat.replace("_", " ")
def format_contribs(
cols: List[str],
vals: np.ndarray,
shap_vec: np.ndarray,
top_k: int = 5,
ndigits: int = 6
) -> Dict[str, Any]:
"""
Returns a clean explanation payload:
- top_contributions (abs sorted)
- top_positive (increases risk)
- top_negative (decreases risk)
"""
records = []
for feat, val, sv in zip(cols, vals, shap_vec):
impact = ffloat(sv, ndigits)
value = ffloat(val, ndigits)
records.append({
"feature": feat, # or clean_feature_name(feat)
"value": value,
"impact": impact, # SHAP value
"direction": "increases_risk" if impact > 0 else "decreases_risk"
})
# Sort by absolute impact
records_sorted = sorted(records, key=lambda r: abs(r["impact"]), reverse=True)
top = records_sorted[:top_k]
top_pos = [r for r in records_sorted if r["impact"] > 0][:top_k]
top_neg = [r for r in records_sorted if r["impact"] < 0][:top_k]
return {
"top_contributions": top,
"top_positive": top_pos,
"top_negative": top_neg
}
class RiskInput(BaseModel):
# numeric
person_age: float
person_income: float
person_emp_length: float
loan_amnt: float
loan_int_rate: float
loan_percent_income: float
cb_person_cred_hist_length: float
# categorical
person_home_ownership: str
loan_intent: str
loan_grade: str
cb_person_default_on_file: str
def preprocess(payload: RiskInput) -> pd.DataFrame:
raw = pd.DataFrame([payload.model_dump()])
categorical_cols = [
"person_home_ownership",
"loan_intent",
"loan_grade",
"cb_person_default_on_file",
]
encoded = pd.get_dummies(raw, columns=categorical_cols, drop_first=True)
encoded = encoded.reindex(columns=feature_names, fill_value=0)
return encoded
@asynccontextmanager
async def lifespan(app: FastAPI):
global model, feature_names, explainer
model = joblib.load(MODEL_PATH)
feature_names = joblib.load(FEATURES_PATH)
explainer = shap.TreeExplainer(model)
yield
app = FastAPI(
title="Explainable Risk Classification API",
description="Machine Learning API for loan risk prediction with SHAP explainability",
version="1.0",
lifespan=lifespan
)
# CORS configuration (allow frontend apps to call this API)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # allow all origins (good for development)
allow_credentials=True,
allow_methods=["*"], # allow all HTTP methods
allow_headers=["*"], # allow all headers
)
@app.get("/")
def home() -> Dict[str, str]:
return {"message": "Explainable ML API is running"}
@app.get("/health")
def health() -> Dict[str, Any]:
return {
"status": "ok",
"model_loaded": model is not None,
"n_features": len(feature_names),
}
@app.get("/features")
def features() -> Dict[str, Any]:
return {"feature_names": feature_names}
@app.post("/predict")
def predict(payload: RiskInput) -> Dict[str, Any]:
X = preprocess(payload)
pred = int(model.predict(X)[0])
proba = float(model.predict_proba(X)[0][1]) if hasattr(model, "predict_proba") else None
return {
"prediction": pred,
"probability_class_1": proba
}
@app.post("/explain")
def explain(payload: RiskInput) -> Dict[str, Any]:
try:
X = preprocess(payload)
exp = explainer(X)
values = exp.values
base_values = exp.base_values
# --- pick class 1 if (n, f, c) ---
if values.ndim == 3:
class_idx = 1
shap_vec = values[0, :, class_idx]
base_val = base_values[0, class_idx]
else:
shap_vec = values[0]
base_val = base_values[0]
shap_vec = np.asarray(shap_vec).reshape(-1)
vals = X.iloc[0].to_numpy().reshape(-1)
cols = list(X.columns)
if len(shap_vec) != len(vals) or len(vals) != len(cols):
raise ValueError(
f"Length mismatch: shap={len(shap_vec)}, vals={len(vals)}, cols={len(cols)}"
)
# --- formatting helpers ---
def r(x: Any, nd: int = 6) -> float:
return float(np.round(float(np.ravel(x)[0]), nd))
# --- build records ---
records: List[Dict[str, Any]] = []
for feat, val, sv in zip(cols, vals, shap_vec):
sv_f = r(sv, 6)
val_f = r(val, 6)
records.append({
"feature": feat,
"value": val_f,
"impact": sv_f, # renamed from shap_value -> impact (cleaner)
"abs_impact": abs(sv_f),
"direction": "increases_risk" if sv_f > 0 else "decreases_risk",
})
# --- sort and slice ---
records_sorted = sorted(records, key=lambda r: r["abs_impact"], reverse=True)
top_contributions = [
{
"feature": rec["feature"],
"value": rec["value"],
"impact": rec["impact"],
"direction": rec["direction"],
}
for rec in records_sorted[:10]
]
top_positive = [
{
"feature": rec["feature"],
"value": rec["value"],
"impact": rec["impact"],
}
for rec in records_sorted
if rec["impact"] > 0
][:5]
top_negative = [
{
"feature": rec["feature"],
"value": rec["value"],
"impact": rec["impact"],
}
for rec in records_sorted
if rec["impact"] < 0
][:5]
# --- model outputs ---
pred = int(model.predict(X)[0])
proba = float(model.predict_proba(X)[0][1]) if hasattr(model, "predict_proba") else None
# Sort by abs impact (already have records_sorted)
records_sorted = sorted(records, key=lambda rec: rec["abs_impact"], reverse=True)
# Keep top 10 for display
top_n = 10
top_records = records_sorted[:top_n]
# Aggregate the rest into "other" (optional but nice for waterfall)
other_impact = sum(rec["impact"] for rec in records_sorted[top_n:])
if abs(other_impact) > 0:
top_records = top_records + [{
"feature": "other",
"value": 0.0,
"impact": float(np.round(other_impact, 6)),
"abs_impact": abs(float(np.round(other_impact, 6))),
"direction": "increases_risk" if other_impact > 0 else "decreases_risk",
}]
# Build waterfall steps
start = float(np.round(float(np.ravel(base_val)[0]), 6))
running = start
steps = []
for rec in top_records:
before = running
after = float(np.round(before + rec["impact"], 6))
steps.append({
"feature": rec["feature"],
"impact": rec["impact"],
"direction": rec["direction"],
"value_before": before,
"value_after": after,
})
running = after
final_value = running
return {
"prediction": pred,
"risk_score": r(proba, 6) if proba is not None else None,
"base_value": start,
# existing pretty list (optional keep)
"top_contributions": [
{
"feature": rec["feature"],
"value": rec["value"],
"impact": rec["impact"],
"direction": rec["direction"],
}
for rec in records_sorted[:10]
],
# ✅ waterfall-ready payload
"waterfall": {
"start": start,
"final": final_value,
"steps": steps
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/batch_predict")
async def batch_predict(file: UploadFile = File(...)) -> Dict[str, Any]:
"""
Upload a CSV with the SAME raw columns as RiskInput:
numeric columns + categorical columns (strings).
Returns predictions + probabilities for all rows.
"""
try:
if not file.filename.lower().endswith(".csv"):
raise HTTPException(status_code=400, detail="Please upload a .csv file")
content = await file.read()
df_raw = pd.read_csv(StringIO(content.decode("utf-8")))
# Required raw columns (same as RiskInput)
required_cols = [
"person_age",
"person_income",
"person_emp_length",
"loan_amnt",
"loan_int_rate",
"loan_percent_income",
"cb_person_cred_hist_length",
"person_home_ownership",
"loan_intent",
"loan_grade",
"cb_person_default_on_file",
]
missing = [c for c in required_cols if c not in df_raw.columns]
if missing:
raise HTTPException(
status_code=422,
detail=f"CSV missing required columns: {missing}"
)
# One-hot encode like training (drop_first=True)
categorical_cols = [
"person_home_ownership",
"loan_intent",
"loan_grade",
"cb_person_default_on_file",
]
X_encoded = pd.get_dummies(df_raw[required_cols], columns=categorical_cols, drop_first=True)
# Align to training features
X_encoded = X_encoded.reindex(columns=feature_names, fill_value=0)
# Predict
preds = model.predict(X_encoded).astype(int).tolist()
probas = None
if hasattr(model, "predict_proba"):
probas = model.predict_proba(X_encoded)[:, 1].astype(float).tolist()
return {
"n_rows": int(len(df_raw)),
"predictions": preds,
"probability_class_1": probas,
}
except UnicodeDecodeError:
raise HTTPException(status_code=400, detail="Could not decode file. Please upload a UTF-8 CSV.")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/batch_explain")
async def batch_explain(
file: UploadFile = File(...),
top_k: int = 5
) -> Dict[str, Any]:
"""
Upload a CSV with the SAME raw columns as RiskInput.
Returns predictions + risk_score + top_k SHAP contributions per row.
"""
try:
if top_k < 1 or top_k > 20:
raise HTTPException(status_code=400, detail="top_k must be between 1 and 20")
if not file.filename.lower().endswith(".csv"):
raise HTTPException(status_code=400, detail="Please upload a .csv file")
content = await file.read()
df_raw = pd.read_csv(StringIO(content.decode("utf-8")))
required_cols = [
"person_age",
"person_income",
"person_emp_length",
"loan_amnt",
"loan_int_rate",
"loan_percent_income",
"cb_person_cred_hist_length",
"person_home_ownership",
"loan_intent",
"loan_grade",
"cb_person_default_on_file",
]
missing = [c for c in required_cols if c not in df_raw.columns]
if missing:
raise HTTPException(status_code=422, detail=f"CSV missing required columns: {missing}")
categorical_cols = [
"person_home_ownership",
"loan_intent",
"loan_grade",
"cb_person_default_on_file",
]
X_encoded = pd.get_dummies(df_raw[required_cols], columns=categorical_cols, drop_first=True)
X_encoded = X_encoded.reindex(columns=feature_names, fill_value=0)
# Predictions
preds = model.predict(X_encoded).astype(int)
probas = model.predict_proba(X_encoded)[:, 1].astype(float) if hasattr(model, "predict_proba") else None
# SHAP explanations for ALL rows at once
exp = explainer(X_encoded)
values = exp.values
base_values = exp.base_values
# Handle shapes: (n,f) or (n,f,c)
if values.ndim == 3:
class_idx = 1
shap_vals = values[:, :, class_idx]
base_vals = base_values[:, class_idx]
else:
shap_vals = values
base_vals = base_values
cols = list(X_encoded.columns)
# rounding helper
def r(x: Any, nd: int = 6) -> float:
return float(np.round(float(np.ravel(x)[0]), nd))
results: List[Dict[str, Any]] = []
for i in range(len(X_encoded)):
row_vals = X_encoded.iloc[i].to_numpy().reshape(-1)
row_shap = np.asarray(shap_vals[i]).reshape(-1)
# Build records
records: List[Dict[str, Any]] = []
for feat, val, sv in zip(cols, row_vals, row_shap):
impact = r(sv, 6)
value = r(val, 6)
records.append({
"feature": feat,
"value": value,
"impact": impact,
"abs_impact": abs(impact),
"direction": "increases_risk" if impact > 0 else "decreases_risk"
})
# Sort by absolute impact
records_sorted = sorted(records, key=lambda rec: rec["abs_impact"], reverse=True)
# --- waterfall (top_k + other) ---
top_records = records_sorted[:top_k]
other_impact = sum(rec["impact"] for rec in records_sorted[top_k:])
if abs(other_impact) > 0:
top_records = top_records + [{
"feature": "other",
"value": 0.0,
"impact": float(np.round(other_impact, 6)),
"abs_impact": abs(float(np.round(other_impact, 6))),
"direction": "increases_risk" if other_impact > 0 else "decreases_risk",
}]
start = r(base_vals[i], 6)
running = start
steps = []
for rec in top_records:
before = running
after = float(np.round(before + rec["impact"], 6))
steps.append({
"feature": rec["feature"],
"impact": rec["impact"],
"direction": rec["direction"],
"value_before": before,
"value_after": after,
})
running = after
top_contributions = [
{
"feature": rec["feature"],
"value": rec["value"],
"impact": rec["impact"],
"direction": rec["direction"],
}
for rec in records_sorted[:top_k]
]
top_positive = [
{"feature": rec["feature"], "value": rec["value"], "impact": rec["impact"]}
for rec in records_sorted if rec["impact"] > 0
][:top_k]
top_negative = [
{"feature": rec["feature"], "value": rec["value"], "impact": rec["impact"]}
for rec in records_sorted if rec["impact"] < 0
][:top_k]
results.append({
"row_id": int(i),
"prediction": int(preds[i]),
"risk_score": r(probas[i], 6) if probas is not None else None,
"base_value": start,
"top_contributions": top_contributions,
"top_positive": top_positive,
"top_negative": top_negative,
# ✅ waterfall-ready
"waterfall": {
"start": start,
"final": running,
"steps": steps
}
})
return {
"n_rows": int(len(df_raw)),
"top_k": int(top_k),
"results": results
}
except UnicodeDecodeError:
raise HTTPException(status_code=400, detail="Could not decode file. Please upload a UTF-8 CSV.")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/explain_waterfall_png")
def explain_waterfall_png(payload: RiskInput) -> StreamingResponse:
"""
Returns a SHAP waterfall plot as a PNG image for ONE row (the given payload).
"""
X = preprocess(payload)
# Compute SHAP Explanation
exp = explainer(X)
# Handle (n, f) vs (n, f, c)
# We need a single-row, single-class Explanation for the plot.
values = exp.values
base_values = exp.base_values
if values.ndim == 3:
class_idx = 1
row_exp = shap.Explanation(
values=values[0, :, class_idx],
base_values=base_values[0, class_idx],
data=X.iloc[0].to_numpy(),
feature_names=list(X.columns),
)
else:
row_exp = shap.Explanation(
values=values[0],
base_values=base_values[0],
data=X.iloc[0].to_numpy(),
feature_names=list(X.columns),
)
# Build the plot (matplotlib)
plt.figure()
shap.plots.waterfall(row_exp, max_display=10, show=False)
buf = io.BytesIO()
plt.savefig(buf, format="png", bbox_inches="tight", dpi=200)
plt.close()
buf.seek(0)
return StreamingResponse(buf, media_type="image/png")