【问题标题】:Prediction values not reacting to user inputs Rshiny预测值对用户输入没有反应 R Shiny
【发布时间】:2019-06-30 23:22:12
【问题描述】:

我正在尝试构建一个闪亮的应用程序,它可以根据各种用户输入提供新的预测。 然而,即使输入值随着输入而更新,预测值也不会更新。我很难找出原因。

该模型是一个随机森林回归模型,在示例中我使用的是数字变量,但在我的情况下,输入是分类的(我认为这种更改不会影响任何东西)这就是为什么侧边栏都是选择输入而不是选择数字

我用 mtcars 数据集做了一个可重现的例子

model <- ranger(mpg ~ disp + hp + wt, data = mtcars)



ui <- fluidPage(
  sidebarPanel(
    selectInput('disp', 'disp',
              choices = unique(mtcars$disp),
            selected = unique(mtcars$disp)[1]),
selectInput('hp', 'hp',
            choices = unique(mtcars$hp),
            selected = unique(mtcars$hp)[1]),
selectInput('wt', 'wt',
            choices = unique(mtcars$wt)),
actionButton("Enter", "Enter Values"),
width = 2
  ),
  mainPanel(
tableOutput('mpg')
)
)

server <- function(input, output, session) {




  val <- reactive({

new <- mtcars[1, ]
new$disp <- input$disp
new$hp <- input$hp
new$wt <- input$wt

new
  })

  out <- eventReactive(
    input$Enter,
    {
      val <- val()
      val$pred <- predict(model, data = val)$predictions
      val

    })

  output$mpg <- renderTable({


    out()

  })


}

shinyApp(ui, server)

【问题讨论】:

  • predict() 的参数应该是newdata=,而不是data=
  • 将代码更改为val$pred &lt;- predict(model, newdata = val)$predictions 会引发此错误:错误:非分位数预测需要参数“数据”。
  • 在闪亮之外运行时,数据参数也可以正常工作
  • 抱歉,我猜ranger() 必须使用与使用predict() 的所有其他对象不同的约定。请务必明确列出您使用的任何非基础 R 包。放入所有library() 命令,以便我们可以复制/粘贴代码进行测试。
  • 是的,我应该使用 caret 包包含该即时消息

标签: r shiny random-forest predict


【解决方案1】:

这里有几个问题。

1) 您错误地使用了 selectInput。见下文。基本上,使用 mtcars$disp[1] 之类的索引将创建静态值,无论选择什么。

2) 当您只生成一个值作为输出时,您正在使用 renderTable()。为什么不直接使用 renderText()?见下文。

3) 需要使用 eventReactive 触发器(即 input$enter)来创建输入值的数据框。模型预测可以稍后在数据帧上运行,但初始触发器实际上是从 selectInput 中拉取值,因此触发器需要在创建数据帧的同一块中。

这运行正确并在我的机器上产生了所需的输出:

library(shiny)
library(ranger)

model <- ranger(mpg ~ disp + hp + wt, data = mtcars)

ui <- fluidPage(

        sidebarPanel(

                selectInput('disp', 'disp',
                            unique(mtcars$disp)),

                selectInput('hp', 'hp',
                            unique(mtcars$hp)),

                selectInput('wt', 'wt',
                            unique(mtcars$wt)),

                actionButton("enter", label = "Enter Values"),
                width = 2
        ),

        mainPanel(

                textOutput('mpg')

        )

)

server <- function(input, output, session) {

        val <- eventReactive(

                input$enter, {

                data.frame(

                        disp = input$disp,
                        hp = input$hp,
                        wt = input$wt,
                        stringsAsFactors = F

                )}

        )

        output$mpg <- renderText({

                predict(model, val())[[1]]

        })

}

shinyApp(ui, server)

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多