ModelHandler provides ML APIs

ModelHandler exposes machine learning models as APIs that applications can use over a REST API. (From v1.46.)

Expose Endpoints

Gramex allows for users to create models over an API interface. To do so, add a modelhandler endpoint to the gramex app

    pattern: /$YAMLURL/model/(.*?)/(.*?)
    handler: ModelHandler
      path: $YAMLPATH  # The local directory to store model files/training data etc.

Post this, users can create models by sending the appropriate requests to the endpoint /model/name/,


URL Query Parameters can be sent as they usually are in formhandler - /model/<name>/?col1=val1&col2=val2&col1=val3..

Example Usage

for example, the following requests via httpie will let you create a model around the iris dataset assuming that the server has a iris.csv inside the app folder

http PUT \
model_class=sklearn.linear_model.SGDClassifier \
output=species Model-Retrain:true url=iris.csv

If no input is sent, it will assume all columns except the output column are the input columns.

If no output is sent, it will assume the right-most or last column of the table is the output column.

Post which, visiting this link wil return the model parameters and visiting this link will return a prediction as a json object. (Answer should be setosa)

This form applies the URL query parameters directly. Try it.

API Reference

Method Endpoint Input Format Response/Action Parameters Header
GET /model/<name>/ - JSON, model kwargs
GET /model/<name>/data URL Query Parameter ?_format=json Formhandler Format, training data
POST /model/<name> JSON Body Train a model (Model-Retrain in headers) else Get Prediction model_class, input, output, url, labels, model_kwargs Model-Retrain: true
POST /model/<name>/data JSON Body Inserts rows into training data
PUT /model/<name>/ JSON Body Train a model model_class, input, output, url, labels, model_kwargs Model-Retrain: true
PUT /model/<name>/data JSON Body Filters rows by columns in id and updates with rest of args id,
DELETE /model/<name> Delete a model
DELETE /model/<name>/data JSON Body Delete rows based on id, id needs to be a primary or composite key and in the case of files, a string/object type column


To train a machine learning model in python, run:

import pandas as pd
from import Classifier

# Read the data into a Pandas DataFrame
data = pd.read_csv('data.csv')
# Construct the model
model = Classifier(
  model_class='sklearn.svm.SVC',        # Any sklearn model works
  model_kwargs={'kernel': 'sigmoid'},   # Optional model parameters
  input=['var1', 'var2', 'var3'],       # Input column names in data
  output='output_column'                # Output column name in data
model.train(data)                       # data is any pandas dataframe'model.pkl')                 # Once the model is trained, save it

and to make predictions in python,


model ='iris.pkl')
result = model.predict([{
  'sepal_length': 5.7,
  'sepal_width': 4.4,
  'petal_length': 1.5,
  'petal_width': 0.4,
# result should be ['setosa']

GroupMeans provides access to the groupmeans() function that allows you to see the most significant influencers of various metrics in your data. (1.42)

groupmeans accepts the following parameters-

For more information, see autolysis.groupmeans

For example, Groupmeans used in an FormHandler

    pattern: /$YAMLURL/
    handler: FormHandler
      url: $YAMPATH/yourdatafile.csv
      modify: groupmeans_app.groupmeans_insights(data, handler)

    pattern: /$YAMLURL/data
    handler: FormHandler
      url: $YAMPATH/yourdatafile.csv
        _format: html

And in


def groupmeans_insights(data, handler):
    args = handler.argparse(
        groups={'nargs': '*', 'default': []},
        numbers={'nargs': '*', 'default': []},
        cutoff={'type': float, 'default': .01},
        quantile={'type': float, 'default': .95},
        minsize={'type': int, 'default': None},
        weight={'type': float, 'default': None})
    return, args.groups, args.numbers,
                                args.cutoff, args.quantile, args.weight)

Links to Machine Learning and Analytics Usecases

Groupmeans Applied to the National Acheivement Survey Dataset