Appearance
FastAPI for Machine Learning
Deploy ML models with FastAPI.
Overview
FastAPI is an excellent choice for serving machine learning models due to its high performance and automatic documentation features.
Features
- High performance
- Automatic API documentation
- Type hints for ML models
- Async support for model inference
- Easy integration with ML libraries
Getting Started
bash
pip install fastapi "uvicorn[standard]" scikit-learn numpy pandasBasic Example
python
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import numpy as np
app = FastAPI(title="ML Model API")
# Load the trained model
model = joblib.load("model.pkl")
class PredictionRequest(BaseModel):
features: list[float]
class PredictionResponse(BaseModel):
prediction: float
confidence: float
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest):
# Convert features to numpy array
features = np.array(request.features).reshape(1, -1)
# Make prediction
prediction = model.predict(features)[0]
# Get prediction probability if available
if hasattr(model, 'predict_proba'):
confidence = model.predict_proba(features)[0].max()
else:
confidence = 1.0
return PredictionResponse(
prediction=float(prediction),
confidence=float(confidence)
)
@app.get("/")
async def root():
return {"message": "ML Model API", "version": "1.0.0"}PAPER-CODE Integration
PAPER-CODE provides:
- FastAPI ML project templates
- Model serving patterns
- Docker configurations
- Testing setups