Defining an API service for a model with BentoML

AppliedModel deployment and servingModel deployment

Goal: Turning a model into an HTTP service that can be packaged in a container.

Python — example.py
# service.py
import bentoml
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

@bentoml.service(resources={"cpu": "1"})
class Classifier:
    def __init__(self):
        X, y = load_iris(return_X_y=True)
        self.model = LogisticRegression(max_iter=500).fit(X, y)

    @bentoml.api
    def predict(self, features: list[list[float]]) -> list[int]:
        return self.model.predict(np.array(features)).tolist()

Code explanation

The class decorated with @bentoml.service represents the service, and each @bentoml.api function becomes an endpoint. Run the service with bentoml serve service:Classifier. We did not run the server in the test environment, so no output is shown.

Requirements

Shell
pip install bentoml scikit-learn

How to run

Save the code in a file example.py then run it:

Shell
python example.py

This example was not run in the test environment: needs an HTTP server running (bentoml serve). Check it against the library documentation before relying on it.

Libraries used

Related examples