File size: 1,199 Bytes
9018775
 
 
4e49afd
9018775
 
4e49afd
 
 
9018775
 
f9d5b98
9018775
4e49afd
 
9018775
 
 
 
 
 
 
 
 
 
4e49afd
 
9018775
 
 
 
4e49afd
9018775
 
 
 
 
 
 
 
4e49afd
f9d5b98
 
 
 
 
 
9018775
f9d5b98
5e77405
f9d5b98
9018775
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
from fastapi import FastAPI
from pydantic import BaseModel
import numpy as np
import joblib

app = FastAPI(
    title="Iris KNN Prediction API",
    description="API for predicting Iris species using KNN model",
    version="1.0.0"
)

# Load model & class names
try:
    model, target_names = joblib.load("iris_knn.pkl")
except:
    model = None
    target_names = []

class IrisData(BaseModel):
    sepal_length: float
    sepal_width: float
    petal_length: float
    petal_width: float

@app.get("/")
def root():
    return {"message": "Iris KNN API Running! Visit /docs to test the API."}

@app.post("/predict")
def predict_iris(data: IrisData):
    if model is None:
        return {"error": "Model not found on server"}

    arr = np.array([[
        data.sepal_length,
        data.sepal_width,
        data.petal_length,
        data.petal_width
    ]])

    pred = model.predict(arr)[0]
    proba = model.predict_proba(arr)[0]

    probability_dict = {
        str(target_names[i]): float(proba[i]) for i in range(len(target_names))
    }

    return {
        "predicted_class": str(target_names[pred]),
        "input": data.dict(),
        "class_probabilities": probability_dict
    }