HerbertAIHug commited on
Commit
d66b821
·
1 Parent(s): 4bd27e5

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +90 -0
main.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+ import pickle
4
+ import pandas as pd
5
+ import numpy as np
6
+ import uvicorn
7
+ import os
8
+
9
+ # call the app
10
+ app = FastAPI(title="API")
11
+
12
+
13
+ # Load the model and scaler
14
+ #def load_model_and_scaler():
15
+ def load_model():
16
+ with open("model.pkl", "rb") as f1, open("scaler.pkl", "rb") as f2:
17
+ return pickle.load(f1), pickle.load(f2)
18
+
19
+ model = load_model
20
+ scaler = ()
21
+
22
+ #model, scaler = load_model_and_scaler()
23
+
24
+ def predict(df, endpoint="simple"):
25
+ # Scaling
26
+ scaled_df = scaler.transform(df)
27
+
28
+ # Prediction
29
+ prediction = model.predict_proba(scaled_df)
30
+
31
+ highest_proba = prediction.max(axis=1)
32
+
33
+ predicted_labels = ["Patient does not have sepsis" if i == 0 else f"Patient has sepsis" for i in highest_proba]
34
+ print(f"Predicted labels: {predicted_labels}")
35
+ print(highest_proba)
36
+
37
+ response = []
38
+ for label, proba in zip(predicted_labels, highest_proba):
39
+ output = {
40
+ "prediction": label,
41
+ "probability of prediction": str(round(proba * 100)) + '%'
42
+ }
43
+ response.append(output)
44
+
45
+ return response
46
+
47
+
48
+ class Patient(BaseModel):
49
+ Blood_Work_R1: int
50
+ Blood_Pressure: int
51
+ Blood_Work_R3: int
52
+ BMI: float
53
+ Blood_Work_R4: float
54
+ Patient_age: int
55
+
56
+ class Patients(BaseModel):
57
+ all_patients: list[Patient]
58
+
59
+ @classmethod
60
+ def return_list_of_dict(cls, patients: "Patients"):
61
+ patient_list = []
62
+ for patient in patients.all_patients:
63
+ patient_dict = patient.dict()
64
+ patient_list.append(patient_dict)
65
+ return patient_list
66
+
67
+ # Endpoints
68
+ # Root Endpoint
69
+ @app.get("/")
70
+ def root():
71
+ return {"API": "This is an API for sepsis prediction."}
72
+
73
+ # Prediction endpoint
74
+ @app.post("/predict")
75
+ def predict_sepsis(patient: Patient):
76
+ # Make prediction
77
+ data = pd.DataFrame(patient.dict(), index=[0])
78
+ parsed = predict(df=data)
79
+ return {"output": parsed}
80
+
81
+ # Multiple Prediction Endpoint
82
+ @app.post("/predict_multiple")
83
+ def predict_sepsis_for_multiple_patients(patients: Patients):
84
+ """Make prediction with the passed data"""
85
+ data = pd.DataFrame(Patients.return_list_of_dict(patients))
86
+ parsed = predict(df=data, endpoint="multi")
87
+ return {"output": parsed}
88
+
89
+ if __name__ == "__main__":
90
+ uvicorn.run("main:app", reload=True)