【发布时间】:2019-01-02 21:47:33
【问题描述】:
我正在使用闪亮的应用程序在 R 上开发一个简单的 ML 模型,应用程序的结构将是:
1) 从本地文件加载数据 2)用加载的数据训练模型 3) 绘制结果
我的问题处于第 2 阶段,我可以使用以下代码绘制输入数据:
output$plot1 <- renderPlot({
ggplot(mydata(), aes(x=LotArea, y=SalePrice)) + geom_point()
})
但由于预测值不在原始DF中,我需要先添加它们。
我使用的代码是:
obsB <- reactive({
set.seed(0)
xgb_model = train(
mydata()["LotArea"], as.vector(t(mydata()["SalePrice"])),
trControl = xgb_trcontrol,
tuneGrid = xgbGrid,
method = "xgbTree"
)
predicted = predict(xgb_model, mydata()["LotArea"])
mydata()["predicted"] = predicted
})
这是我得到的错误:
Warning: Error in FUN: object 'predicted' not found
当我将“LotArea”更改为“predicted”时会发生这种情况
output$plot1 <- renderPlot({
ggplot(mydata(), aes(x=predicted, y=SalePrice)) + geom_point()
})
这是我拥有的完整代码:
library(shiny)
library(readxl)
library(tidyverse)
library(xgboost)
library(caret)
library(iml)
#### UI
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
tags$hr(),
checkboxInput("header", "Header", TRUE)
),
mainPanel(
#tableOutput("contents"),
plotOutput("plot1", click = "plot_brush")
)
)
)
server <- function(input, output) {
mydata <- reactive({
req(input$file1, input$header, file.exists(input$file1$datapath))
read.csv(input$file1$datapath, header = input$header)
})
output$contents <- renderTable({
req(mydata())
#mydata()
})
### test
xgb_trcontrol = trainControl(
method = "cv",
number = 5,
allowParallel = TRUE,
verboseIter = FALSE,
returnData = FALSE
)
#I am specifing the same parameters with the same values as I did for Python above. The hyperparameters to optimize are found in the website.
xgbGrid <- expand.grid(nrounds = c(10,14), # this is n_estimators in the python code above
max_depth = c(10, 15, 20, 25),
colsample_bytree = seq(0.5, 0.9, length.out = 5),
## The values below are default values in the sklearn-api.
eta = 0.1,
gamma=0,
min_child_weight = 1,
subsample = 1
)
obsB <- reactive({
set.seed(0)
xgb_model = train(
mydata()["LotArea"], as.vector(t(mydata()["SalePrice"])),
trControl = xgb_trcontrol,
tuneGrid = xgbGrid,
method = "xgbTree"
)
predicted = predict(xgb_model, mydata()["LotArea"])
mydata()["predicted"] = predicted
})
output$plot1 <- renderPlot({
ggplot(mydata(), aes(x=predicted, y=SalePrice)) + geom_point()
})
}
shinyApp(ui, server)
编辑:
我变了:
mydata()["predicted"] = predicted
为:
data = mydata()
data["predicted"] = predicted
但知道我得到了一个不同的错误:
Warning: Error in : You're passing a function as global data.
Have you misspelled the `data` argument in `ggplot()
编辑 2:这是我正在使用的数据示例:
https://drive.google.com/file/d/1R8GA0fW0pOgG8Cpykc8mAThvKOCRCVl0/view?usp=sharing
【问题讨论】:
-
这个
predict(xgb_model, mydata()["LotArea"])是否返回正确的值? -
@Parfait 实际上,我不确定。如果我使用反应函数,我将无法打印结果,如果我使用观察函数,那么我会在该行收到此错误:“警告:= 中的错误:赋值的无效(NULL)左侧”。
-
尝试在闪亮之外进行测试。
-
我认为问题在于 mydata() 不是数据框它是反应式表达,我认为你不能这样做。您可以在函数内部执行 data
-
mydata()["predicted"]导致错误,因为在mydata()中没有名为predicted的列,并且您无法像在任何普通数据框中那样动态创建新列。因此,您可以将predicated分配给现有列或尝试此answer