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(iris.data[:,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(iris.data[:,3:4], columns=iris.feature_names[3:4])
#    petal width (cm)
# 0               0.2
# 1               0.2
# 2               0.2
regr = linear_model.LinearRegression()
regr.fit(X, y)
library(datasets)
library(yhatr)

head(iris)
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):
    REQUIREMENTS=["pandas","scikit-learn"]
    @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)
  result
}

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!

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

Deployment

Deploy your model to ScienceOps

yh = Yhat("USERNAME", "API_KEY", "https://sandbox.yhathq.com")
yh.deploy("LinearRegression", LinReg, globals(), autodetect=False)
yhat.config  <- c(
  username="USERNAME",
  apikey="API_KEY",
  env="https://sandbox.yhathq.com/"
)
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]}' \
    https://sandbox.yhathq.com/USERNAME/models/LinearRegression/

results matching ""

    No results matching ""