Skip to main content

Flask-derived wrapper to serve sklearn models

Project description

skserve - A Flask API wrapper for deploying sklearn models

Created by Adam Grbac.

This package uses Flask to create an easy frame to deploy existing Machine Learning models created in scikit-learn, and expose them via a RESTful API.

The main object of this package is the ModelServer class, which is a subclass of the Flask class, and can therefore be treated & customised the same way as a regular Flask server instance.

Usage

Basic

To use this package, start by creating a scikit-learn model (or a model type that has a similar predict / predict_proba API to that of sklearn).

Once the model is trained, use the dump() function from the joblib module to save the model as a file.

One you have a model file that you would like to deploy e.g. A simple logistic regression model with 7 inputs - logreg.model, the following code is an example of a barebones deployment:

from skserve import ModelServer
from joblib import load

model = load('logreg.model')

app = ModelServer(model=model)

if __name__ == "__main__":
    app.run()

This code will start a Flask API on 127.0.0.1:5000 with the following routes:

  • '/' : The root of the server will return a small welcome message and can be used to test connectivity.
  • '/help': The help route packages up and documentation supplied to the API i.e. An input data dictionary & any Docstrings that exist in the pre/post processing functions.
  • '/predict': The predict route invokes the predict method of the model being deployed by being sent a POST request. The request should include data as a JSON object with the feature names and values.
  • '/predict_proba': The predict_proba route invokes the predict_proba method of the model being deployed by being sent a POST request. The request should include data as a JSON object with the feature names and values.

To solicit a prediction from the model, we send a POST request to the /predict route with a JSON object as data, which contains the 7 required fields:

curl -d {"""Age""":42,"""Fare""":52.00,"""Sex""":"""male""","""Parch""":2,"""Pclass""":1,"""SibSp""":2} -H "Content-Type: application/json" 127.0.0.1:5000/predict

Advanced

The ModelServer class can also be initialised with other parameters:

  • pre : A preprocessing function which takes a pandas DataFrame of the data passed in with the POST request and should return a similar DataFrame that the model can accept.
  • post : A postprocessing function which takes the results of model scoring (a list) and will be returned as the "scores" element of a JSON object as a response to the initiating POST request.
  • data_dict : A dictionary that maps feature names to descriptions of the features. This dictionary is used as part of the /help route (for users information) as well as ordering the data for the model (so POST data does not need to be in order).

The Host and Port of the server can also be changed by passing host & port parameters to the run() function.

An example of the above extensions to the base functionality is shown below:

from skserve import ModelServer
from joblib import load

model = load('logreg.model')

data_dict = {"Pclass":"Passenger Class",
            "Age":"Passenger Age",
            "Fare":"Fare Paid",
            "Parch":"Parents / Children",
            "SibSp":"Siblings",
            "Sex":"Gender Code - 0: Male - 1: Female"}

def pre_process(data):
    """Pre-Processor:

    This should show up on the help page.

	The function changes the string into a Binary value."""
    data["Sex"] = data["Sex"].apply(lambda x: 0 if x == "male" else 1)
    return data

def post_process(data):
    """Post-Processer:

    This should also show up on the help page.

	This function takes the scores, and shifts from 0 <-> 1 to -1 <-> 1"""
    return(data*2 - 1)

app = ModelServer(model=model,
                  pre=pre_process,
                  post=post_process,
                  data_dict=data_dict)

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=1337)

These changes will also make an impact on the page returned on the /help route e.g.:

SSSSS K   K SSSSS EEEEE RRRRR V   V EEEEE
S     K  K  S     E     R   R V   V E
SSSSS KKK   SSSSS EEEEE RRRRR V   V EEEEE
    S K  K      S E     R RR   V V  E
SSSSS K   K SSSSS EEEEE R   R   V   EEEEE

This model API can be used to predict outputs (Regression + Classification) or probabilities (Classification).

These are accessed by sending a POST request to <host>/predict or <host>/predict_proba respectively.

The input data should be a JSON object with the following fields:

Pclass: Passenger Class
Age: Passenger Age
Fare: Fare Paid
Parch: Parents / Children
SibSp: Siblings
Sex: Gender Code - 0: Male - 1: Female

The data sent will be pre-processed using a pre-defined function:

Pre-Processor:

    This should show up on the help page
The model results will be post-processed using a pre-defined function:

Post-Processer:

    This should also show up on the help page

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

skserve-0.11.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

skserve-0.11-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file skserve-0.11.tar.gz.

File metadata

  • Download URL: skserve-0.11.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.5

File hashes

Hashes for skserve-0.11.tar.gz
Algorithm Hash digest
SHA256 c3b5bdcb1414d25744c8b13a41e73ed8aa2110d0a57717f94ef9968c07f141e2
MD5 020b4f6168376ebff28f5a57f077f248
BLAKE2b-256 126580e0752f8010ea026a2b817218b77c28547123947bfec15886a2f39cc409

See more details on using hashes here.

File details

Details for the file skserve-0.11-py3-none-any.whl.

File metadata

  • Download URL: skserve-0.11-py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/47.1.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.5

File hashes

Hashes for skserve-0.11-py3-none-any.whl
Algorithm Hash digest
SHA256 a724042ca0ce3c752c1fdb5d9d25c8006eed50db96c49048ac76d8b55906202d
MD5 7234326bad5df31297ae11ab4ddd3424
BLAKE2b-256 c8eeceb8ec20af1ce152a0a145ee6c18e272a952565f74f2831d34425a1d4029

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page