Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import joblib
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
# 1. Load the trained model
|
| 7 |
+
# Ensure 'iris_model.pkl' is uploaded to the same folder in Hugging Face
|
| 8 |
+
model = joblib.load("iris_model.pkl")
|
| 9 |
+
|
| 10 |
+
# 2. Define the class mapping based on your notebook encoding
|
| 11 |
+
# In your notebook: Iris-setosa=1, Iris-versicolor=2, Iris-virginica=3
|
| 12 |
+
class_names = {
|
| 13 |
+
1: "Iris-setosa",
|
| 14 |
+
2: "Iris-versicolor",
|
| 15 |
+
3: "Iris-virginica"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
# 3. Define the input data format using Pydantic
|
| 19 |
+
class IrisInput(BaseModel):
|
| 20 |
+
SepalLengthCm: float
|
| 21 |
+
SepalWidthCm: float
|
| 22 |
+
PetalLengthCm: float
|
| 23 |
+
PetalWidthCm: float
|
| 24 |
+
|
| 25 |
+
# 4. Initialize FastAPI
|
| 26 |
+
app = FastAPI()
|
| 27 |
+
|
| 28 |
+
# 5. Define the Home Route (Health Check)
|
| 29 |
+
@app.get("/")
|
| 30 |
+
def home():
|
| 31 |
+
return {"message": "Iris Species Prediction API is Live!"}
|
| 32 |
+
|
| 33 |
+
# 6. Define the Prediction Route
|
| 34 |
+
@app.post("/predict")
|
| 35 |
+
def predict_species(data: IrisInput):
|
| 36 |
+
# Extract features from the input object
|
| 37 |
+
features = np.array([[
|
| 38 |
+
data.SepalLengthCm,
|
| 39 |
+
data.SepalWidthCm,
|
| 40 |
+
data.PetalLengthCm,
|
| 41 |
+
data.PetalWidthCm
|
| 42 |
+
]])
|
| 43 |
+
|
| 44 |
+
# Make the prediction using the loaded model
|
| 45 |
+
prediction = model.predict(features)
|
| 46 |
+
|
| 47 |
+
# The model returns an array (e.g., [1]), so we take the first item
|
| 48 |
+
predicted_class = int(prediction[0])
|
| 49 |
+
|
| 50 |
+
# Map the number back to the name
|
| 51 |
+
species_name = class_names.get(predicted_class, "Unknown")
|
| 52 |
+
|
| 53 |
+
return {
|
| 54 |
+
"predicted_class": predicted_class,
|
| 55 |
+
"species_name": species_name
|
| 56 |
+
}
|