-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
75 lines (57 loc) · 2.26 KB
/
app.py
File metadata and controls
75 lines (57 loc) · 2.26 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
from fastapi import FastAPI, HTTPException
import joblib
import pandas as pd
import json
from utils.get_data import get_customer_features
from utils.get_shap import get_png, get_importances, plot
import base64
app = FastAPI(title="Home Credit Default Risk API")
DATA_FOLDER='data'
# load model
MODEL = joblib.load('api_model_info/model.pkl')
# get best threshold
with open('api_model_info/params/threshold.txt', 'rt') as f:
threshold_value = float(f.read().strip())
# global feature importance
with open("api_model_info/lgbm_importances.png", "rb") as image_file:
global_imp = base64.b64encode(image_file.read()).decode('utf-8')
@app.get('/check_api')
def running():
return "API is running."
@app.get("/predict/{sk_id}")
def predict(sk_id: int):
try:
# Transform ID into features
features_row = get_customer_features(sk_id)
if features_row is None or features_row.shape[0]==0:
raise HTTPException(status_code=404, detail="Customer ID not found")
# Predict
probability = MODEL.named_steps['lgbm'].predict_proba(features_row)[0][1]
prediction = 1 if probability >= threshold_value else 0
ev, importances, sv = get_importances(features_row, MODEL)
return {
"sk_id": sk_id,
"prediction": prediction,
"probability": round(float(probability), 4),
"threshold": round(threshold_value, 4),
"status": "Rejected" if prediction == 0 else "Approved",
"loc_imp": plot(features_row, ev, importances, sv), # get_png(features_row, MODEL)
"global_imp": global_imp
}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/explore/{sk_id}")
def explore(sk_id: int):
try:
features_row = get_customer_features(sk_id)
if features_row is None or features_row.shape[0]==0:
raise HTTPException(status_code=404, detail="Customer ID not found")
dic = features_row.iloc[0].to_dict()
dic = {k: (None if pd.isna(v) else v) for k, v in dic.items()}
return dic
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))