I have trained a neural network on an image classification task and now try to build an API with plumber to pass data to the model and get back the predictions.
But I am stuck on how to pass a three-dimensional array (the image) to the API. I tried different httr::POST
calls and conversions from/to JSON, but could not get it working. The postBody
of the request is a list of numbers and not an array anymore.
access_api.R
# Pass array to API
X <- array(rnorm(300 * 200 * 3), dim = c(300, 200, 3))
res <- httr::POST("http://127.0.0.1:6060/predict",
body = list(X),
encode = "json")
predict.R
#* @param X array
#* @post /predict
predict <- function(req) {
req$postBody
# Train model ...
}
plumber.R
library(plumber)
r <- plumb("predict.R")
r$run(port = 6060, host = "0.0.0.0")
I also tried converting the array to JSON, but then the structure of the array is lost and need to be restored:
A <- RJSONIO::toJSON(X)
B <- RJSONIO::fromJSON(A)
str(B)
D <- lapply(B, function(x) {
Reduce(rbind, x)
})
E <- array(unlist(D), dim = dim(X))
str(E)