Caret and shiny:无法创建由插入符号模型驱动的预测应用

时间:2016-12-16 02:16:27

标签: r machine-learning shiny r-caret

我试图开发一个简单的应用程序,闪亮,预测乘客在泰坦尼克号存活的概率,给定一定的年龄,等级,票价等。我希望这些变量是动态的,并希望计算预测的生存概率使用底层插入符号模型。

运行此代码时,收到以下错误消息:

  

警告:[.data.frame:未定义列选择堆栈跟踪时出错   (最里面的):       70:[。data.frame       69:[       68:横扫       67:predict.preProcess       66:预测       65:probFunction       64:predict.train       63:预测       62:预测       61:is.data.frame       60:data.matrix       59:observerFunc [#17]        4:        3:do.call        2:print.shiny.appobj        1:错误:[on_request_read]连接由对等方重置

我的代码如下。是什么原因造成了这个错误?非常感谢。

require(shiny)
require(plyr)
require(dplyr)
require(ggplot2)
require(caret)
require(xgboost)

require(titanic)
df=na.omit(titanic_train)
y=data.matrix(select(df, Survived))
y[y==0]="N"
y[y==1]="Y"
x=data.matrix(select(df, Pclass, Age, SibSp, Parch, Fare))

tCtrl <- trainControl(method = "repeatedcv", number = 3, repeats=3, summaryFunction = twoClassSummary, verbose=TRUE, classProbs = TRUE)
fit_xgbTree= train(x, y, method = "xgbTree" , family= "binomial", trControl = tCtrl, metric = "ROC", preProc = c("center", "scale"))

ui = pageWithSidebar(
  headerPanel("Titanic"),
  sidebarPanel(
    radioButtons("Pclass", "Passenger Class", choices=c("1", "2", "3"),selected = "1", inline = TRUE,width = NULL),
    sliderInput("Age", "Passenger Age", min=0, max=80, value=30),
    radioButtons("SibSp", "SibSp", choices=c("0", "1", "2", "3", "4", "5")),
    radioButtons("Parch", "Parch", choices=c("0", "1", "2", "3", "4", "5", "6")),
    sliderInput("Fare", "Passenger Fare", min=0, max=520, value=35)
  ),
  mainPanel(
    dataTableOutput('testTable'),
    textOutput('outputBox')
  )
)

server=function(input, output){

  values <- reactiveValues()

  newEntry <- observe({ # use observe pattern

    x=as.data.frame(matrix(0, nrow=1, ncol=5))
    colnames(x)=c("Pclass", "Age",    "SibSp", "Parch",  "Fare")

    x[1,1]=as.numeric(input$Pclass)
    x[1,2]=input$Age
    x[1,3]=as.numeric(input$SibSp)
    x[1,4]=as.numeric(input$Parch)
    x[1,5]=input$Fare


    pred <- data.matrix(predict(object=fit_xgbTree, x, type="prob")[,2])
    isolate(values$df <- x)
    #isolate(values$df2 <- x)
  })

  output$testTable <- renderDataTable({values$df})
}

shinyApp(ui=ui, server=server)

1 个答案:

答案 0 :(得分:2)

服务器中的以下修改对我来说非常适合(添加生存概率列,我认为这就是你想要的):

server=function(input, output){

  values <- reactiveValues()

  newEntry <- observe({ # use observe pattern

    x=as.data.frame(matrix(0, nrow=1, ncol=6))
    colnames(x)=c("Pclass", "Age",    "SibSp", "Parch",  "Fare", "SurvProb")

    x[1,1]=as.numeric(input$Pclass)
    x[1,2]=input$Age
    x[1,3]=as.numeric(input$SibSp)
    x[1,4]=as.numeric(input$Parch)
    x[1,5]=input$Fare

    pred <- data.matrix(predict(object=fit_xgbTree, x[-length(x)], type="prob")[,2])
    x[1,6] <- round(pred,2)

    isolate(values$df <- x)
    #isolate(values$df2 <- x)
  })

  output$testTable <- renderDataTable({values$df})
}

带输出 enter image description here