Skip to content

Instantly share code, notes, and snippets.

@randyphoa
Created June 7, 2022 02:12
Show Gist options
  • Save randyphoa/93e7ae5068cb9935fbde14fe89e8c2dc to your computer and use it in GitHub Desktop.
Save randyphoa/93e7ae5068cb9935fbde14fe89e8c2dc to your computer and use it in GitHub Desktop.
Deploy R in online mode - predict function
#!/usr/bin/env Rscript
library(xgboost)
library(jsonlite)
args <- commandArgs(trailingOnly = TRUE)
if (length(args) == 0) {
stop("Insufficient arguments.", call. = FALSE)
}
data <- fromJSON(args[1])
df <- data.frame(data)
colnames(df) <- data$fields
classes <- c("setosa", "versicolor", "virginica")
model <- xgb.load("iris_xgb.model")
pred <- predict(model, as.matrix(df), reshape=T)
pred <- as.data.frame(pred)
colnames(pred) <- classes
pred$probability <- apply(pred, 1, function(x) max(x))
pred$prediction <- apply(pred, 1, function(x) colnames(pred)[which.max(x)])
toJSON(pred)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment