Linear Regression

Here's a quick example for how to build linear model. We're using the iris dataset and trying to predict "Petal Width" with the features "Sepal Length", "Sepal Width" and "Petal Length"

First, we fit/train our model:

import pandas as pd
from sklearn import linear_model
from sklearn import datasets

iris = datasets.load_iris()
X = pd.DataFrame([:,0:3], columns=iris.feature_names[0:3])
#    sepal length (cm)  sepal width (cm)  petal length (cm)
# 0                5.1               3.5                1.4
# 1                4.9               3.0                1.4
# 2                4.7               3.2                1.3
y = pd.DataFrame([:,3:4], columns=iris.feature_names[3:4])
#    petal width (cm)
# 0               0.2
# 1               0.2
# 2               0.2
regr = linear_model.LinearRegression(), y)

fit <- lm(Petal.Width ~ Sepal.Length + Sepal.Width + Petal.Length, data=iris)

Add in ScienceOps part. Note the REQUIREMENTS specify the 3rd party packages we need.

from yhat import Yhat, YhatModel, preprocess, df_to_json

class LinReg(YhatModel):
    @preprocess(in_type=pd.DataFrame, out_type=pd.DataFrame)
    def execute(self, data):
       prediction = regr.predict(pd.DataFrame(data))[0][0]
       return {"prediction":prediction}
model.predict <- function(data) {
  pred <- predict(fit, newdata=data.frame(data))
  result <- data.frame(prediction=pred)

Test your model locally:

We recommend you test your model locally before deploying. After all, if it doesn't work locally, it won't work on ScienceOps!

#   prediction
#0    0.216136
testcase <- data.frame(iris[1,1:3])


Deploy your model to ScienceOps

yh = Yhat("USERNAME", "API_KEY", "")
yh.deploy("LinearRegression", LinReg, globals(), autodetect=False)
yhat.config  <- c(
yhat.deploy ("LinearModelR", confirm = FALSE)

Get Predictions via the REST API

Predictions from the model can be sent and received from the languages below in addition to others found on the REST API page.

curl -X POST -H "Content-Type: application/json" \
    --user USERNAME:API_KEY \
    --data '{"sepal length (cm)":[6.1],"sepal width (cm)":[3.5],"petal length (cm)":[1.4]}' \

results matching ""

    No results matching ""