I am trying to use shiny to create a randomforest prediction app to check for loan default

时间:2016-10-20 12:52:36

标签: r shiny

I am trying to create a shiny app where anyone providing a certain number of input variables would be able to click on an actionButton and then see if the person would default on loan payment or not.

I am using a randomforest to train the model. The user would be able to enter the values of the attributes and click on Analyze to generate a numeric value where 1 would be defaulting and 0 would be not defaulting. Default is the target variable and all the other variables are numeric in nature. I get an error that a particular object not found. pr <- predict(rf, newdata=na.omit(values$df)) causes the error.

library(shiny)

ui <- shinyUI(fluidPage(

   # Application title
   titlePanel("Loan Defaulter Data"),

   # Sidebar with a slider input 
   sidebarLayout(
      sidebarPanel(
        numericInput("FounderBusiness",label="No Of Other Business Held By the Founder",value="5"),
        numericInput("BusinessMargins",label="Business Margins",value="1"),
        numericInput("RecurringOtherIncome",label="Other.Incomes...Recurring",value="2"),
        numericInput("OwnedCapital",label="Owned.Capital",value="3"),
        numericInput("SecuredDebt",label="Secured.Debts.",value="6"),
        numericInput("RunningPBDIT",label="Running.PBDIT.As.per.Banking.",value="1"),
        numericInput("RunningPBDITDSCR",label="Running.PBDIT.DSCR.As.per.Banking.",value="3"),
        numericInput("TotalBorrowingEquity",label="Total.borrowings..Equity",value="3"),
        numericInput("ProposedExposure",label="Proposed.Exposure.POS.",value="1"),
        actionButton("Action", "Analyze")
      ),

      mainPanel(
        textOutput('dynamicText')
      )
   )
))

server <- shinyServer(function(input, output) {
  dataset <- read.csv("Updated_Imputed_DataSet.csv")
  nobs <- nrow(dataset)
  sample <- train <- sample(nrow(dataset), 0.8*nobs) # 836 observations
  validate <- NULL
  test <- setdiff(setdiff(seq_len(nrow(dataset)), train), validate) # 210 observations

  # The following variable selections have been noted.

  input_att <- c("No.of.other.businesses.held.by.the.founder", "Business.Margins", "Other.Incomes...Recurring", "Owned.Capital",
             "Secured.Debts.", "Running.PBDIT.As.per.Banking.", "Running.PBDIT.DSCR.As.per.Banking.", "Total.borrowings..Equity",
             "Proposed.Exposure.POS.")

  numeric <- c("No.of.other.businesses.held.by.the.founder", "Business.Margins", "Other.Incomes...Recurring", "Owned.Capital",
               "Secured.Debts.", "Running.PBDIT.As.per.Banking.", "Running.PBDIT.DSCR.As.per.Banking.", "Total.borrowings..Equity",
               "Proposed.Exposure.POS.")

  target  <- "Default"

  # Build the Random Forest model.
  rf <- randomForest::randomForest(as.factor(Default) ~ .,
                                   data=dataset[sample,c(input_att, target)], 
                                   ntree=500,
                                   mtry=3,
                                   importance=TRUE,
                                   na.action=randomForest::na.roughfix,
                                   replace=FALSE)

  # Obtain probability scores for the Random Forest model on Updated_Imputed_DataSet.csv [test].
  values <- reactiveValues()
  observe({
    if(input$Action>0){
      newLine<-isolate(c(input$FounderBusiness,input$BusinessMargins,input$RecurringOtherIncome,input$OwnedCapital,input$SecuredDebt,input$RunningPBDIT,input$RunningPBDITDSCR,input$TotalBorrowingEquity,input$ProposedExposure))
      isolate(values$df <- unlist(newLine))

    }
  })


  output$dynamicText<-renderText({
    pr <- predict(rf, newdata=na.omit(values$df))
    pr<-as.numeric(pr)
      ({pr-1})
  })

})

# Run the application 
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

问题似乎是values$df在评估renderText时不存在,因为它会在点击&#34; Action&#34;后创建。要解决这个问题,您有两种选择。

1)您可以定义默认值,例如:

values <- reactiveValues(df = rep(0,9)) # a vector with 9 zeros.

2)使用以下内容验证renderText

output$dynamicText <- renderText({
    if (is.null(values$df)) 
      return()
    pr <- predict(rf, newdata=na.omit(values$df))
    pr <- as.numeric(pr)
      ({pr-1})
  })