🚀 FastAPI से ML Model को Web API बनाना
Machine Learning models को train करने के बाद सबसे बड़ी challenge होती है उन्हें production में deploy करना ताकि अन्य applications या users उनका use कर सकें। FastAPI Python का एक high-performance web framework है जो APIs बनाने के लिए lightweight और fast solution देता है। इस ब्लॉग में हम step-by-step सीखेंगे कि FastAPI से ML model को Web API कैसे बनाएं।
🔹 FastAPI क्या है?
FastAPI एक modern web framework है जो Python 3.7+ पर चलता है और API बनाने के लिए design किया गया है। यह asynchronous support और automatic documentation (Swagger, Redoc) देता है।
- High performance (Node.js और Go के बराबर speed)
- Built-in validation (Pydantic का use)
- Swagger UI support
- Easy deployment with Docker
📂 Prerequisites
FastAPI से ML model को deploy करने के लिए आपको चाहिए:
- Python 3.7+
- Trained ML model (Pickle या Joblib file)
- FastAPI और Uvicorn library
- Basic understanding of REST APIs
⚡ Installation
pip install fastapi uvicorn pip install scikit-learn pandas joblib
📝 Step 1: ML Model को Save करना
सबसे पहले, एक simple ML model train करके उसे save करें:
from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import joblib data = load_iris() X, y = data.data, data.target model = RandomForestClassifier() model.fit(X, y) joblib.dump(model, "iris_model.pkl")
📝 Step 2: FastAPI App बनाना
अब FastAPI app create करें और model load करें।
from fastapi import FastAPI import joblib import numpy as np from pydantic import BaseModel # Load model model = joblib.load("iris_model.pkl") # Initialize FastAPI app app = FastAPI(title="Iris ML API") # Input schema class InputData(BaseModel): sepal_length: float sepal_width: float petal_length: float petal_width: float @app.post("/predict") def predict(data: InputData): features = np.array([[data.sepal_length, data.sepal_width, data.petal_length, data.petal_width]]) prediction = model.predict(features) return {"prediction": int(prediction[0])}
📝 Step 3: Run Server
API server run करने के लिए command:
uvicorn main:app --reload
अब आप http://127.0.0.1:8000/docs पर Swagger UI में अपनी API test कर सकते हैं।
📌 Example Request
POST /predict { "sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2 }
🚀 MLOps Deployment में FastAPI का महत्व
FastAPI ML models को production में serve करने के लिए perfect choice है:
- Fast और lightweight
- Docker के साथ आसानी से integrate
- Built-in API docs
- Scalable और cloud-ready
🏆 निष्कर्ष
FastAPI एक modern और आसान framework है जो ML models को Web API में बदलने में मदद करता है। इसके साथ Docker use करके आप अपने models को production-ready बना सकते हैं और किसी भी platform पर deploy कर सकते हैं।