Deploying R Models/Functions With the AzureML R Package

Posted By:

Today we will be covering how to create and deploy a custom R web service in Azure Machine Learning by leveraging the AzureML R package. This functionality can be incredibly useful, especially in scenarios where you want to quickly deploy a function you have written in R as a service that can interface with other applications. This functionality is commonly used to deploy models that were developed in a local R environment, or to deploy other non-machine learning functions for interfacing with applications. Today I will show you how to take an existing R function and publish it as a web service with the AzureML R package.

Step 1: Install the AzureML R Package

Before beginning this exercise, we will need to install the AzureML R package and load it into our workspace. Run the following code to install and load the package.

# install the package
install.packages(“AzureML“)

# load the package
library(“AzureML“)

Step 2: Write a Function to Deploy

For today’s exercise, let’s assume we have a linear model that has been trained on the mtcars dataset. This model takes a set of inputs, and predicts the mpg for the car. In this example, we have also developed a function which scores new observations against the existing linear model.

Trained Model

The following code block selects a feature set and trains a model to predict the mpg for a car. I split the mtcars data into training and testing datasets prior to this exercise. The output of this codeblock is a trained model object mpg_lm.

library(“dplyr“)

# Choose a set of features to train model with
features_to_select <- c(“makemodel”,“mpg”, “cyl”, “hp”, “wt”, “am”)

train <- train %>% select(one_of(features_to_select))
test <- test %>% select(one_of(features_to_select))

# Train linear model
mpg_lm <- lm(data = train, formula = mpg ~ cyl + hp + wt + as.factor(am))

Scoring Function

Now that we have a trained model, we would like to score new data against it. The code below creates a function that accepts a data frame containing the data to be scored and returns another data frame that has a score column appended to it. Take a look at the function below. Notice how we reference our trained model object, which resides in the workspace on our local machine. This will become interesting as we begin to interface with Azure Machine Learning via the AzureML R package.

# Scoring Function
predict_mpg <- function(new_cars){

predictions <- predict.lm(mpg_lm, new_cars)

output <- data.frame(new_cars, ScoredLabels =predictions)

output
}

# test the scoring function
predict_mpg(test)

##        makemodel  mpg cyl  hp    wt am ScoredLabels
## 9       Merc 230 22.8   4  95 3.150  0     21.96872
## 28  Lotus Europa 30.4   4 113 1.513  1     27.29876
## 14   Merc 450SLC 15.2   8 180 3.780  0     15.92451
## 2  Mazda RX4 Wag 21.0   6 110 2.875  1     23.43554
## 12    Merc 450SE 16.4   8 180 4.070  0     15.27626

Step 3: Connect to Azure ML

The AzureML R package includes several useful functions for interfacing with your favorite R IDE. The first function we will use is workspace, which allows us to remotely connect to our AML workspace. All that is required to execute this function is the workspace ID and the authentication token, which can be found under the settings pane in AML Studio. After connecting to your workspace, try using the experiments function to list all of the experiments in your workspace.

ws <- workspace(
id = “insert workspace id here”,
auth = “insert workspace authentication key here”
)

Step 4: Deploy Function as a Web Service

We can deploy our scoring function using the publishWebService function. We pass our function’s name to the fun argument and the test dataset to the inputSchema argument. We must also specify a name for our web service. The last thing that must be specified is that the input and output are a data frame. After running this function, you should receive messages that the input schema and the output function have been converted to data frame.

Note: Remember how we referenced our trained model object in our scoring function? The publishWebService function is able to save a copy of the referenced object and publish it with the scoring function. This allows us to do things like publish trained models to Azure ML. Cool, right?

api <- publishWebService(
ws,
fun = predict_mpg,
  name = “Score New Cars – MPG LM”,
  inputSchema = test,
data.frame = TRUE
  )

## converting `inputSchema` to data frame

## converting `function_output` to data frame

Step 5: Consume the Web Service

After the web service has been published, we can test that it works by using the consume function. We pass the web service object we just created, as well as the dataset that we would like to score to the function. We should receive back the input dataset along with the scored labels.

consume(api, test)

##       makemodel  mpg cyl  hp    wt am ScoredLabels
## 1      Merc 230 22.8   4  95 3.150  0     21.96872
## 2  Lotus Europa 30.4   4 113 1.513  1     27.29876
## 3   Merc 450SLC 15.2   8 180 3.780  0     15.92451
## 4 Mazda RX4 Wag 21.0   6 110 2.875  1     23.43554
## 5    Merc 450SE 16.4   8 180 4.070  0     15.27626

Step 6 (Optional): Make Updates to the Web Service

Let’s say that you would like to change the feature set to your machine learning model, or that you have received more data and would like to retrain your model using all of the available data. The AzureML R package also allows you to update an existing web service to account for these scenarios. To update an existing web service, use the getWebServices function to find the serviceId of your web service, and then run the updateWebService function with the details of your existing web service to update it. You should now be able to use the consume function with your newly updated web service.

# Find the serviceid of the previously deployed web service
  getWebServices(ws)

api <- updateWebService(
ws,
  fun = predict_mpg,
  name = “Score New Cars – MPG LM”,
inputSchema = test,
data.frame = TRUE
  )
,
serviceId = “insert web service id here”
)

Step 7 (Optional): Delete the Web Service

If you ever find that you no longer need the web service that was created, you can delete it using the deleteWebService function. Just pass the workspace and the web service name as arguments to delete. This can also be useful if you want to be absolutely certain that the web service is being updated. In these cases, delete the existing web service and then recreate it as usual.

deleteWebService(ws, “Score New Cars – MPG LM”)

Concluding Remarks

This tutorial has gone over how to take an existing R function that you use every day and turn it into a web service that can interface with production level applications. You should be on your way to publishing your own web services and integrating them into your applications. Happy Coding!

For questions, please email: edwin@nealanalytics.com.