Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example: add time-series models with statsmodels #4979

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions examples/arima-model/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Serving ARIMA model with BentoML

This project shows how to apply a continuous learning ARIMA model
for time-series data in BentoML to forecasts future values.

## Requirements

Install requirements with:

```bash
pip install -r ./requirements.txt
```

## Instruction

1. Train and save model:

```bash
python ./train.py
```

2. Run the service:

```bash
bentoml serve
```

## Test the endpoint

Open in browser http://0.0.0.0:3000 to predict forecast of 5 future values.

```bash
curl -X 'POST' 'http://0.0.0.0:3000/predict' -H 'accept: application/json' -H 'Content-Type: application/json' -d '{"data": [5]}'
```

Sample result:
```
[
21.32297249948254,
39.103166807895505,
51.62030696797619,
57.742863144656305,
57.316390331155915
]

```

## Build Bento

Build Bento using the bentofile.yaml which contains all the configurations required:

```bash
bentoml build -f ./bentofile.yaml
```

Once the Bento is built, containerize it as a Docker image for deployment:

```bash
bentoml containerize arima_forecast_model:latest
```
5 changes: 5 additions & 0 deletions examples/arima-model/bentofile.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
service: "service.py:ArimaForecast"
include:
- "service.py"
python:
requirements_txt: ./requirements.txt
3 changes: 3 additions & 0 deletions examples/arima-model/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
bentoml>=1.2.0
statsmodels
scikit-learn
33 changes: 33 additions & 0 deletions examples/arima-model/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import numpy as np

import bentoml


@bentoml.service(
resources={
"cpu": "2",
"memory": "2Gi",
},
)
class ArimaForecast:
"""
A simple ARIMA model to forecast future predictions
"""

# Load in the class scope to declare the model as a dependency of the service
arima_model = bentoml.picklable_model.get("arima_forecast_model:latest")

def __init__(self):
"""
Initialize the service by loading the model from the model store
"""
self.model = self.arima_model.load_model()

@bentoml.api
def forecast(self, data: np.ndarray) -> np.ndarray:
"""
Define API with input as number of forecasts to predict in the future
"""
model_fit = self.model.fit()
predictions = model_fit.forecast(int(data))
return predictions
58 changes: 58 additions & 0 deletions examples/arima-model/train.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# import libraries
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.metrics import mean_squared_error
from statsmodels.tsa.arima.model import ARIMA

import bentoml


def main():
# Load the dataset
data = sm.datasets.sunspots.load_pandas().data
# Prepare dataset
data.index = pd.Index(sm.tsa.datetools.dates_from_range("1700", "2008"))
data.index.freq = data.index.inferred_freq
del data["YEAR"]

# Split into train and test sets
X = data.values
size = int(len(X) * 0.66)
train, test = X[0:size], X[size : len(X)]
# Create a list of records to train ARIMA
history = [x for x in train]
# Create a list to store the predicted values
predictions = list()

# Iterate over the test data
for t in range(len(test)):
model = ARIMA(history, order=(5, 1, 0))
# fit the model and create forecast
model_fit = model.fit()
output = model_fit.forecast()
yhat = output[0]
predictions.append(yhat)
obs = test[t]
# update history with test data
history.append(obs)

y_test = test
y_pred = predictions

# Calculate root mean squared error
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
print("Root Mean Squared Error:", rmse)

# Save model with BentoML
saved_model = bentoml.picklable_model.save_model(
"arima_forecast_model",
model,
signatures={"predict": {"batchable": True}},
)
Comment on lines +48 to +52
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recommended API here is using bentoml.models.create with our latest API. https://docs.bentoml.org/en/latest/guides/model-store.html


print(f"Model saved: {saved_model}")


if __name__ == "__main__":
main()