Introduction
Deploying a small machine learning model as an API can help you leverage the power of machine learning in your web applications. In this article, we'll guide you through the process of deploying a simple machine learning model as a REST API using FastAPI, a modern, high-performance web framework in Python. We'll cover setting up a basic model, creating an API endpoint, and handling requests and responses. By the end of this article, you should be able to deploy and use your model as an API without any major issues.
Setting Up Your Environment
Before we dive into the code, ensure you have the following installed on your machine:
- Python 3.x (3.7 or newer)
- FastAPI
- A machine learning model (for this example, we'll use a simple logistic regression model)
- A Python machine learning library (e.g., scikit-learn)
You can install FastAPI and its dependencies by running:
pip install fastapi uvicorn Step 1: Prepare Your Machine Learning Model
For this example, we'll use a simple logistic regression model to classify data points. First, we need to import the necessary libraries and load our dataset:
from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.datasets import load_iris import numpy as np Load the iris dataset:
iris = load_iris() X = iris.data y = iris.target Split the dataset into training and testing sets:
def preprocess_data(X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) return X_train, X_test, y_train, y_test X_train, X_test, y_train, y_test = preprocess_data(X, y) Train the logistic regression model:
model = LogisticRegression() model.fit(X_train, y_train) # Evaluate the model y_pred = model.predict(X_test) print(accuracy_score(y_test, y_pred)) Step 2: Create the API Endpoint
Now that we have our model ready, let's create an API endpoint using FastAPI. We'll create a simple API with two endpoints:
-
get_data: To fetch the data for training the model -
predict: To predict the target using the loaded model
First, set up a FastAPI application and define routes:
python def create_api_app() -> FastAPI: app = FastAPI() app.include_router(create_predict_router(), prefix="/api/predict") return app @app.post("/api/predict/get_data") def get_data(data: RequestDataIn): # In a real-world scenario, you'd fetch data from a database or external source # For this example, we'll simulate fetching data data = np.random.rand(10, 4) return { 
