Partilhar via


Quickstart: Deploy an R Model as a web service with mrsdeploy

Important

This content is being retired and may not be updated in the future. The support for Machine Learning Server will end on July 1, 2022. For more information, see What's happening to Machine Learning Server?

Applies to: R Client 3.x, R Server 9.x, Machine Learning Server 9.x

Learn how to publish an R model as a web service with Machine Learning Server, formerly known as Microsoft R Server. Data scientists work locally with Microsoft R Client in their preferred R IDE and favorite version control tools to build scripts and models. Using the mrsdeploy package that ships with Microsoft R Client and Machine Learning Server, you can develop, test, and ultimately deploy these R analytics as web services in your production environment.

A Machine Learning Server R web service is an R code execution on the operationalization compute node. Each web service is uniquely defined by a name and version. You can use the functions in the mrsdeploy package to gain access a service's lifecycle from an R script. A set of RESTful APIs is also available to provide direct programmatic access to a service's lifecycle directly.

Time estimate

If you have completed the prerequisites, this task takes approximately 10 minutes to complete.

Prerequisites

Before you begin this QuickStart, have the following ready:

Example code

This article walks through the deployment of a simple R model as a web service hosted in Machine Learning Server. Here is the entire R code for the example that we walk through in the sections that follow.

Important

Be sure to replace the remoteLogin() function with the correct login details for your configuration. Connecting to Machine Learning Server using the mrsdeploy package is covered in this article.

##########################################################
#       Create & Test a Logistic Regression Model        #
##########################################################
    
# Use logistic regression equation of vehicle transmission 
# in the data set mtcars to estimate the probability of 
# a vehicle being fitted with a manual transmission 
# based on horsepower (hp) and weight (wt)

# If on R Server 9.0, load mrsdeploy package now
library(mrsdeploy)

# Create glm model with `mtcars` dataset
carsModel <- glm(formula = am ~ hp + wt, data = mtcars, family = binomial)

# Produce a prediction function that can use the model
manualTransmission <- function(hp, wt) {
     newdata <- data.frame(hp = hp, wt = wt)
     predict(carsModel, newdata, type = "response")
}
   
# test function locally by printing results
print(manualTransmission(120, 2.8)) # 0.6418125

##########################################################
#            Log into Server                 #
##########################################################
   
# Use `remoteLogin` to authenticate with Server using 
# the local admin account. Use session = false so no 
# remote R session started
remoteLogin("https://localhost:12800", 
            username = "admin", 
            password = "{{YOUR_PASSWORD}}",
            session = FALSE)

##########################################################
#             Publish Model as a Service                 #
##########################################################

# Generate a unique serviceName for demos 
# and assign to variable serviceName
serviceName <- paste0("mtService", round(as.numeric(Sys.time()), 0))

# Publish as service using publishService() function from 
# mrsdeploy package. Name service "mtService" and provide
# unique version number. Assign service to the variable `api`
api <- publishService(
     serviceName,
     code = manualTransmission,
     model = carsModel,
     inputs = list(hp = "numeric", wt = "numeric"),
     outputs = list(answer = "numeric"),
     v = "v1.0.0"
)

##########################################################
#                 Consume Service in R                   #
##########################################################
   
# Print capabilities that define the service holdings: service 
# name, version, descriptions, inputs, outputs, and the 
# name of the function to be consumed
print(api$capabilities())
   
# Consume service by calling function, `manualTransmission`
# contained in this service
result <- api$manualTransmission(120, 2.8)

# Print response output named `answer`
print(result$output("answer")) # 0.6418125   

##########################################################
#         Get Service-specific Swagger File in R         #
##########################################################
   
# During this authenticated session, download the  
# Swagger-based JSON file that defines this service
swagger <- api$swagger()
cat(swagger, file = "swagger.json", append = FALSE)

# Now share this Swagger-based JSON so others can consume it

A. Model locally

Now let's dive into this example down. Let's start by creating the model locally, then publish it, and then share it with other authenticated users.

  1. Launch your R IDE or Rgui so you can start entering R code.

  2. If you have R Server 9.0.1, load the mrsdeploy package. In later releases, this package is preloaded for you.

    library(mrsdeploy)
    
  3. Create a GLM model called carsModel using the dataset mtcars, which is a built-in data frame in R. Using horsepower (hp) and weight (wt), this model estimates the probability that a vehicle has been fitted with a manual transmission.

    # Create glm model with `mtcars` dataset
    carsModel <- glm(formula = am ~ hp + wt, data = mtcars, family = binomial)
    
    # Produce a prediction function that can use the model
    manualTransmission <- function(hp, wt) {
      newdata <- data.frame(hp = hp, wt = wt)
      predict(carsModel, newdata, type = "response")
    }
    
    # test function locally by printing results
    print(manualTransmission(120, 2.8)) # 0.6418125
    
  4. Examine the results of the locally executed code. You can compare these results to the results of the web service later.


B. Publish model as a web service

  1. From your local R IDE, log in to Machine Learning Server with your credentials. Use the appropriate authentication function from the mrsdeploy package (remoteLogin or remoteLoginAAD) for your authentication method.

    For simplicity, the following code uses the basic local 'admin' account for authentication with the remoteLogin function and session = false so that no remote R session is started. Learn more about authenticating with Active Directory LDAP or Azure Active Directory in the article "Connecting to Machine Learning Server from mrsdeploy."

    Important

    Be sure to replace the remoteLogin() function with the correct login details for your configuration.

    # Use `remoteLogin` to authenticate with Server using 
    # the local admin account. Use session = false so no 
    # remote R session started
    remoteLogin("https://localhost:12800", 
             username = "admin", 
             password = "{{YOUR_PASSWORD}}",
             session = FALSE)
    

    Now, you are successfully connected to the remote Machine Learning Server.

  2. Publish the model as a web service to Machine Learning Server using the publishService() function from the mrsdeploy package.

    In this example, you publish a web service called "mtService" using the model carsModel and the function manualTransmission. As an input, the service takes a list of vehicle horsepower and vehicle weight represented as an R numerical. As an output, a percentage as an R numeric for the probability each vehicle has of being fitted with a manual transmission.

    When publishing a service, specify its name and version, the R code, the inputs, and the outputs needed for application integration as well as other parameters.

    Note

    To publish a web service while in a remote R session, carefully review these guidelines.

    api <- publishService(
      "mtService",
      code = manualTransmission,
      model = carsModel,
      inputs = list(hp = "numeric", wt = "numeric"),
      outputs = list(answer = "numeric"),
      v = "v1.0.0"
    )
    

C. Consume the service in R to test

Consume the service in R directly after publishing it to verify that the results are as expected.

# Print capabilities that define the service holdings: service 
# name, version, descriptions, inputs, outputs, and the 
# name of the function to be consumed
print(api$capabilities())
   
# Consume service by calling function, `manualTransmission`
# contained in this service
result <- api$manualTransmission(120, 2.8)

# Print response output named `answer`
print(result$output("answer")) # 0.6418125   

The results should match the results obtained when the model was run locally earlier. As long as the package versions are the same on Machine Learning Server as they are locally, you should get the same results. You can check for differences using a remote session "diff report."

Warning

If you get an alphanumeric error code, such as Message: b55088c4-e563-459a-8c41-dd2c625e891d, when consuming a service, search for that code in the compute node's log file to reveal the full error message.

D. Get the Swagger-based JSON file

Anyone can test and consume the service using its auto-generated Swagger-based JSON file. This Swagger-based JSON file is specific to a given version of a service. You can easily get this file during the same authenticated session in which you published the service. It can be downloaded to the local file system. You can get this Swagger file as long as the web service exists as described in the article "How to interact with and consume web services in R."

In this example, we executed these commands to download the Swagger-based JSON file:

swagger <- api$swagger()
cat(swagger, file = "C:\\temp\\swagger.json", append = FALSE) 

Note

Learn how to get and share this Swagger-based JSON file after the session ends.

Next steps

After it has been deployed, the web service can be:

How to execute R code remotely

You can use Microsoft R Client to run your R code locally and from R Client you can connect remotely to Machine Learning Server to run your code there. You can easily switch between the local context and the remote context using pause() and resume() functions. Learn more in this article, Remote Execution in Microsoft Machine Learning Server.

Requirements for remote execution include:

More resources

This section provides a quick summary of useful links for data scientists operationalizing R analytics with Machine Learning Server.