0% found this document useful (0 votes)
13 views3 pages

Unit-3 Machine Learning Model with FastAPI for Iris Dataset

i am sagar kuamr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views3 pages

Unit-3 Machine Learning Model with FastAPI for Iris Dataset

i am sagar kuamr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Machine Learning Model with FastAPI for Iris Dataset

# File 1: MLDemo.py → This file contains ML Training and its model using pickle

# Importing required libraries


import pandas as pd
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pickle

# Load the Iris dataset


iris = load_iris()
X = iris['data']
y = iris['target']

# Split the data into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initialize and train the Random Forest Classifier


model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# Evaluate the model


y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy * 100}%")

# Save the model to a file using pickle


with open('iris_model.pkl', 'wb') as f:
pickle.dump(model, f)
# File 2 : MLFastAPI.py → This file contains the loading of .pkl model created above and creating its
API

import pickle
from fastapi import FastAPI
from pydantic import BaseModel

# Define the request body for input data


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

# Load the pretrained model


with open("iris_model.pkl", "rb") as f:
model = pickle.load(f)

# Load the iris dataset to access target names


from sklearn.datasets import load_iris

iris = load_iris()
target_names = iris.target_names # ['setosa', 'versicolor', 'virginica']

# Create FastAPI instance


app = FastAPI()

# Root endpoint for testing


@app.get("/")
def root():
return {"message": "Welcome to the Iris Prediction API"}

# Prediction endpoint
@app.post("/predict/")
def predict_iris(data: IrisRequest):
# Prepare input data as a list of features
features = [[
data.sepal_length,
data.sepal_width,
data.petal_length,
data.petal_width
]]
# Predict the class
prediction = model.predict(features)
predicted_class = target_names[prediction[0]] # Map class number to class name

return {"predicted_class": predicted_class}

You might also like