alathrop
7/28/2016 - 4:42 AM

AzureML package examples

AzureML package examples

# purpose: use the AzureML package to *publish* a web service 

# load the library to use the Boston dataset
library(MASS)
?Boston

# library for plotting
library(ggplot2) 
# plot distribution of the response variable
ggplot(Boston, aes(x=medv)) + 
  geom_histogram(binwidth=2) +
  ggtitle("Histogram of Response Variable")
  
# fit a model using all variables except medv as predictors
lm1 <- lm(medv ~ ., data = Boston)

# check model performance
summary(lm1)

# Now compute some error measures:
pred <- predict(lm1)
error <- pred - Boston$medv
mae <- mean(abs(error))
rmse <- sqrt(mean((error)^2))
rae <- mean(abs(error)) / mean(abs(Boston$medv - mean(Boston$medv)))
rse <- mean((error)^2) / mean((Boston$medv - mean(Boston$medv))^2)

cat("Mean Absolute Error:", round(mae, 6), "\n")
cat("Root Mean Squared Error:", round(rmse, 6), "\n")
cat("Relative Absolute Error:", round(rae, 6), "\n")
cat("Relative Squared Error:", round(rse, 6), "\n")

# publish web service
# load the library
library(AzureML)

# If you use workspace() in a Jupyter notebook, you don't need to specify credentials,
# since the settings are stored for you in a local file.
# If you use this function on your own machine, specify your credentials. See ?workspace.

if(file.exists("~/.azureml/settings.json")){
    ws <- workspace()
} else {
    workspace_id <- "a25b681362dc4addb793cea40c420ba4"
    authorization_token <- "e2dc7fcc92cc43fbbaac8394b06d969a"
    ws <- workspace(workspace_id, authorization_token)
}

# define predict function
mypredict <- function(newdata){
  predict(lm1, newdata)
}

# a sample with predictor information
newdata <- Boston[1:5, ]

# test the prediction function
data.frame(
    actual = newdata$medv, 
    prediction = mypredict(newdata))
    
    # publish the service
ep <- publishWebService(ws = ws, 
                        fun = mypredict, 
                        name = "HousePricePrediction", 
                        inputSchema = newdata)
# str(ep)
# purpose: use the AzureML package to *consume* a web service

library(AzureML)
ws <- workspace(
  id = "a25b681362dc4addb793cea40c420ba4",
  auth = "e2dc7fcc92cc43fbbaac8394b06d969a"
)
ws

experiments(ws)

services(ws)

(webservices <- services(ws, name = "HousePricePrediction"))
# (webservices <- services(ws, service_id = "ead52e34545011e691f10242ac11259b" ))

ep <- endpoints(ws, webservices[1, ])
class(ep)

names(ep)

# load the library to use the Boston dataset
library(MASS)

data("Boston")
# a sample with predictor information
newdata <- Boston[1:5, ]
newdata

s <- services(ws, name = "HousePricePrediction")
s <- tail(s, 1) # use the last published function, in case of duplicate function names
ep <- endpoints(ws, s)
# consume
pred <- consume(ep, newdata)$ans
# check predictions
data.frame(
    actual = newdata$medv, 
    prediction = pred)