ikoghoemmanuell commited on
Commit
093cf05
1 Parent(s): e290449

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +71 -50
app/main.py CHANGED
@@ -1,86 +1,107 @@
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
 
8
- # call the app
9
- app = FastAPI(title="API")
10
 
11
- # Load the model and scaler
12
- def load_model_and_scaler():
13
- with open("model.pkl", "rb") as f1, open("scaler.pkl", "rb") as f2:
14
- return pickle.load(f1), pickle.load(f2)
15
 
16
- model, scaler = load_model_and_scaler()
 
 
17
 
18
- def predict(df, endpoint="simple"):
19
- # Scaling
20
- scaled_df = scaler.transform(df) # Scale the input data using a pre-defined scaler
21
 
22
- # Prediction
23
- prediction = model.predict_proba(scaled_df) # Make predictions using a pre-trained model
24
 
25
- highest_proba = prediction.max(axis=1) # Get the highest probability for each prediction
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- # Assign predicted labels based on the highest probabilities
28
- predicted_labels = ["Patient does not have sepsis" if i == 0 else "Patient has sepsis" for i in highest_proba]
29
- print(f"Predicted labels: {predicted_labels}") # Print the predicted labels to the terminal
30
- print(highest_proba) # Print the highest probabilities to the terminal
 
 
31
 
32
  response = []
33
- for label, proba in zip(predicted_labels, highest_proba):
34
- # Create a response for each prediction with the predicted label and probability
 
 
35
  output = {
36
- "prediction": label,
37
- "probability of prediction": str(round(proba * 100)) + '%' # Convert the probability to a percentage
38
  }
39
  response.append(output) # Add the response to the list of responses
40
 
41
  return response # Return the list of responses
42
 
43
-
44
- class Patient(BaseModel):
45
- Blood_Work_R1: int
46
- Blood_Pressure: int
47
- Blood_Work_R3: int
48
- BMI: float
49
- Blood_Work_R4: float
50
- Patient_age: int
51
-
52
- class Patients(BaseModel):
53
- all_patients: list[Patient]
 
 
 
 
 
 
54
 
55
  @classmethod
56
- def return_list_of_dict(cls, patients: "Patients"):
57
- patient_list = []
58
- for patient in patients.all_patients: #for each item in all_patients,
59
- patient_dict = patient.dict() #convert to a dictionary
60
- patient_list.append(patient_dict) #add it to the empty list called patient_list
61
- return patient_list
62
-
63
  # Endpoints
64
  # Root Endpoint
65
  @app.get("/")
66
  def root():
67
- return {"Welcome to the Sepsis Prediction API! This API provides endpoints for predicting sepsis based on patient data."}
68
 
69
  # Prediction endpoint
70
  @app.post("/predict")
71
- def predict_sepsis(patient: Patient):
72
  # Make prediction
73
- data = pd.DataFrame(patient.dict(), index=[0])
74
- parsed = predict(df=data)
75
- return {"output": parsed}
76
 
77
  # Multiple Prediction Endpoint
78
  @app.post("/predict_multiple")
79
- def predict_sepsis_for_multiple_patients(patients: Patients):
80
  """Make prediction with the passed data"""
81
- data = pd.DataFrame(Patients.return_list_of_dict(patients))
82
- parsed = predict(df=data, endpoint="multi")
83
- return {"output": parsed}
84
 
85
  if __name__ == "__main__":
86
  uvicorn.run("main:app", reload=True)
 
1
  from fastapi import FastAPI
2
  from pydantic import BaseModel
 
3
  import pandas as pd
4
+ import pickle
5
  import uvicorn
6
+ from sklearn.preprocessing import StandardScaler, QuantileTransformer
7
+ import category_encoders as ce
8
 
9
+ # Call the app
10
+ app = FastAPI(title="Product Demand Prediction API")
11
 
12
+ # Load the model
13
+ with open("model.pkl", "rb") as f:
14
+ model = pickle.load(f)
 
15
 
16
+ # Define columns
17
+ categorical_cols = ['center_id', 'meal_id', 'emailer_for_promotion', 'homepage_featured', 'city_code', 'region_code', 'center_type', 'category', 'cuisine']
18
+ numeric_cols = ['week', 'base_price', 'discount', 'op_area']
19
 
20
+ # Fit transformers
21
+ encoder = ce.BinaryEncoder(drop_invariant=False, return_df=True)
 
22
 
23
+ quantile_transformer = QuantileTransformer(output_distribution='normal')
 
24
 
25
+ scaler = StandardScaler()
26
+ scaler.set_output(transform="pandas")
27
+
28
+ # Define your predict function
29
+ def predict(df, endpoint="simple"):
30
+ # Preprocess input data
31
+ df_cat = encoder.fit_transform(df[categorical_cols])
32
+ df_num_quantile = quantile_transformer.fit_transform(df[numeric_cols])
33
+ df_num_quantile = pd.DataFrame(df_num_quantile, columns=numeric_cols)
34
+ df_num_scaled = scaler.fit_transform(df_num_quantile)
35
+
36
+ # Concatenate encoded categorical and scaled numerical data
37
+ preprocessed_df = pd.concat([df_num_scaled, df_cat], axis=1)
38
 
39
+ # Ensure the DataFrame has all the columns that the model was trained on
40
+ model_columns = preprocessed_df.columns.tolist()
41
+ preprocessed_df = preprocessed_df.reindex(columns=model_columns, fill_value=0)
42
+
43
+ # Prediction
44
+ prediction = model.predict(preprocessed_df) # Make predictions using the pre-trained model
45
 
46
  response = []
47
+ for num_orders in prediction:
48
+ # Convert NumPy float to Python native float
49
+ num_orders = int(num_orders)
50
+ # Create a response for each prediction with the predicted number of orders
51
  output = {
52
+ "predicted_num_orders": num_orders
 
53
  }
54
  response.append(output) # Add the response to the list of responses
55
 
56
  return response # Return the list of responses
57
 
58
+ class Demand(BaseModel):
59
+ week: int
60
+ center_id: str
61
+ meal_id: str
62
+ base_price: float
63
+ emailer_for_promotion: int
64
+ homepage_featured: int
65
+ discount: float
66
+ city_code: str
67
+ region_code: str
68
+ center_type: str
69
+ op_area: float
70
+ category: str
71
+ cuisine: str
72
+
73
+ class Demands(BaseModel):
74
+ all_demands: list[Demand]
75
 
76
  @classmethod
77
+ def return_list_of_dict(cls, demands: "Demands"):
78
+ demand_list = []
79
+ for demand in demands.all_demands: # for each item in all_demands
80
+ demand_dict = demand.dict() # convert to a dictionary
81
+ demand_list.append(demand_dict) # add it to the empty list called demand_list
82
+ return demand_list
83
+
84
  # Endpoints
85
  # Root Endpoint
86
  @app.get("/")
87
  def root():
88
+ return {"message": "Welcome to the Product Demand Prediction API! This API provides endpoints for predicting product demand based on input data."}
89
 
90
  # Prediction endpoint
91
  @app.post("/predict")
92
+ def predict_demand(demand: Demand):
93
  # Make prediction
94
+ data = pd.DataFrame(demand.dict(), index=[0])
95
+ predicted_demand = predict(df=data)
96
+ return predicted_demand
97
 
98
  # Multiple Prediction Endpoint
99
  @app.post("/predict_multiple")
100
+ def predict_demand_for_multiple_demands(demands: Demands):
101
  """Make prediction with the passed data"""
102
+ data = pd.DataFrame(Demands.return_list_of_dict(demands))
103
+ predicted_demand = predict(df=data, endpoint="multi")
104
+ return {"predicted_demand": predicted_demand}
105
 
106
  if __name__ == "__main__":
107
  uvicorn.run("main:app", reload=True)