我正在切磋如何使用Plumber和Swagger将一个R机器学习分类模型作为网络服务公开。我已经训练了一个模型,并将其保存为 "j48.model.rda"。我现在将模型加载到一个名为 "myFile.R "的文件中。这个文件包含以下R代码。
library(rJava)
jsDirData <- "C:/AA Research/Playpen/Data"
setwd(jsDirData)
#Load the saved model
load(file="j48.model.rda", envir = parent.frame(), verbose = FALSE)
#' @param naasra90th:numeric The 90th Percentile Naasra value for the segment
#' @param rut90th:numeric The 90th Percentile Rut Depth for the segment
#' @param surfAge:numeric The surface age of the segment, in years (fractions are OK)
#' @param rutRate90th:numeric The rut rate on the 90th Percentile Rut depth (mm/year)
#' @param maintCount:int The number of maintenance acions
#' @get /getTreatment
#' @html
#' @response 200 Returns the treatment class (ThinAC or none) prediction from the j48 model;
#' @default Bonk!
getTreatment <- function(naasra90th, rut90th, surfAge, rutRate90th, maintCount) {
xVals <- list(naasra90th = naasra90th, rut90th = rut90th, surfAge = surfAge,
rutRate90th = rutRate90th, maintCount = maintCount)
nData <- as.data.frame(xVals)
pred <- predict(j48.model,newdata = nData)
res <- as.character(pred)
return(res)
}
t <- getTreatment(50,8.8,5,0.3,0) #should return "none"
t #"none" Correct!
t <- getTreatment(888,888,888,888,888) #should return "ThinAC"
t #"ThinAC" Correct!
从最后几行可以看出,当我在R -Studio中直接调用这个函数时,它给出了正确的分类。但现在我尝试通过PlumberSwagger网络服务来调用这个方法,如下图。
library(plumber)
jsDirData <- "C:/AA Research/Playpen/Data"
setwd(jsDirData)
r <- plumb("myfile.R")
r$run(port=8000)
当我运行这段代码时,Swagger打开浏览器,正确显示API。但是,当我使用 "Try It "按钮来测试API时,那么无论我向方法中传递什么参数,结果总是显示为 "none"。例如,如果我输入与上面第二个方法调用相同的参数集(即所有参数都是888),那么它就会返回 "none",而它应该返回 "ThinAC"。
我到底做错了什么?
我相信你从swagger调用中接收到的值仍然是字符类的,因为plumber不对查询字符串参数进行任何转换。
在做 as.data.frame
,尝试改变xVals中的值的类别。
xVals <- lapply(xVals, as.numeric)
为了证实这个假设,你可以插入一个...。browser()
之后 as.data.frame
中的值的类别,并检查 nData
与 lapply(nData, class)
.
运气好