Update app/main.py
Browse files- 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
|
| 6 |
import uvicorn
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
app = FastAPI(title="API")
|
| 10 |
|
| 11 |
-
# Load the model
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
return pickle.load(f1), pickle.load(f2)
|
| 15 |
|
| 16 |
-
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
scaled_df = scaler.transform(df) # Scale the input data using a pre-defined scaler
|
| 21 |
|
| 22 |
-
|
| 23 |
-
prediction = model.predict_proba(scaled_df) # Make predictions using a pre-trained model
|
| 24 |
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
|
| 32 |
response = []
|
| 33 |
-
for
|
| 34 |
-
#
|
|
|
|
|
|
|
| 35 |
output = {
|
| 36 |
-
"
|
| 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 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
@classmethod
|
| 56 |
-
def return_list_of_dict(cls,
|
| 57 |
-
|
| 58 |
-
for
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
return
|
| 62 |
-
|
| 63 |
# Endpoints
|
| 64 |
# Root Endpoint
|
| 65 |
@app.get("/")
|
| 66 |
def root():
|
| 67 |
-
return {"Welcome to the
|
| 68 |
|
| 69 |
# Prediction endpoint
|
| 70 |
@app.post("/predict")
|
| 71 |
-
def
|
| 72 |
# Make prediction
|
| 73 |
-
data = pd.DataFrame(
|
| 74 |
-
|
| 75 |
-
return
|
| 76 |
|
| 77 |
# Multiple Prediction Endpoint
|
| 78 |
@app.post("/predict_multiple")
|
| 79 |
-
def
|
| 80 |
"""Make prediction with the passed data"""
|
| 81 |
-
data = pd.DataFrame(
|
| 82 |
-
|
| 83 |
-
return {"
|
| 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)
|