How to deploy Machine Learning models as a Microservice using FastAPI

 As of today, FastAPI is the most popular web framework for building microservices with python 3.6+ versions. By deploying machine learning models as microservice-based architecture, we make code components re-usable, highly maintained, ease of testing, and of-course the quick response time. FastAPI is built over ASGI (Asynchronous Server Gateway Interface) instead of flask’s WSGI (Web Server Gateway Interface). This is the reason it is faster as compared to flask-based APIs.

Step 1. Make your model for which you want to create the API ready

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import pickle
# Load dataseturl = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']dataset = pd.read_csv(filepath_or_buffer=url,header=None,sep=',',names=names)# Split-out validation datasetarray = dataset.valuesX = array[:,0:4]y = array[:,4]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1, shuffle=True)classifier = LogisticRegression()classifier.fit(X_train,y_train)save the model to diskpickle.dump(classifier, open('LRClassifier.pkl', 'wb'))load the model from diskloaded_model = pickle.load(open('LRClassifier.pkl', 'rb'))result = loaded_model.score(X_test, y_test)print(result)
Logistic Regression python code snippet

Step 2. Create API using FastAPI framework

from fastapi import FastAPI
from pydantic import BaseModel
import pickle
import numpy as np
import pandas as pd
app = FastAPI()class IrisSpecies(BaseModel):sepal_length: floatsepal_width: floatpetal_length: floatpetal_width: float@app.post('/predict')async def predict_species(iris: IrisSpecies):data = iris.dict()loaded_model = pickle.load(open('LRClassifier.pkl', 'rb'))data_in = [[data['sepal_length'], data['sepal_width'], data['petal_length'], data['petal_width']]]prediction = loaded_model.predict(data_in)probability = loaded_model.predict_proba(data_in).max()return {'prediction': prediction[0],'probability': probability}
import requestsnew_measurement = {"sepal_length": 1.2,"sepal_width": 2.3,"petal_length": 1.4,"petal_width": 2.8}response = requests.post('http://127.0.0.1:8000/predict', json=new_measurement)print(response.content)>>> b'{"prediction":"Iris-setosa","probability":0.99}'

Comments

Popular posts from this blog

Flutter for Single-Page Scrollable Websites with Navigator 2.0

A Data Science Portfolio is More Valuable than a Resume

Better File Storage in Oracle Cloud