简体   繁体   中英

Naive Bayes with inputs in Shiny

I´m making a Shiny app with Naive Bayes Classifier, but when I execute it, I have the following error: [enter image description here][1]

The code is:

library(shiny)
library(shinydashboard)
library(e1071)

#Cargar datos
d <- read.csv("C:/Users/jerez/OneDrive/Escritorio/UAL/NB.csv", sep = ";", header = TRUE)
#data(datos)
daf <- as.data.frame(d)


# Define UI 
ui <- fluidPage(

    # Application title
    titlePanel("Clasificador Naive Bayes"),

    # Sidebar 
    sidebarPanel(
      h4("Clase"),
      selectInput(inputId = "clase",label = "Clase", multiple = FALSE, choices = daf$Tipo),
      h4("Atributos de los mensajes"),
      selectInput(inputId = "usuario", label = "Recibido de", multiple = FALSE, choices = daf$Usuario),
      selectInput(inputId = "fecha", label = "Mes de creacion", multiple = FALSE, choices =daf$Fecha)
        ),

        # Show a plot of the generated distribution
    mainPanel(
      p("Probabilidad a posteriori de que el mensaje sea clasificado del tipo seleccionado:"),
      verbatimTextOutput("prediccion"),
      br(),
      p("Clasificacion"),
      plotOutput("Grafico"),
      p("Looking for the problem:"),
      verbatimTextOutput("prueba")
    )
    
)

# Define server 
server <- function(input, output) {
    
    runMode <- reactive({naiveBayes(daf[input$clase] ~., data = d)}) 
    output$prueba <- renderPrint({naiveBayes( daf[input$clase]~., data = d)})
    
    output$Grafico <- renderPlot({
     
      dat <- daf[daf$Usuario == input$usuario & daf$Fecha == input$fecha, 3]
      mod <- runMode()
      grafbarr <- barplot(dat, beside = T, horiz = T, 
                          main = "Clasificacion del mensaje",
                          xlab = "tipo de mensaje",
                          ylab = "mensajes",
                          col = c("blue", "yellow"),
                          legend = c("Si pertenece a la categoria", "No pertenece a la categoria"))
    
    })
    
    output$prediccion <- renderPrint({
      mod1 <- runMode()
      prob <- predict(mod1, daf[daf$Tipo == input$clase & daf$Usuario == input$usuario & daf$Fecha == input$fecha, 1:3])
    })
}

And this is my data base: [enter image description here][2]

I want classifier at the first column (Tipo). This column is the Class in function by "Usuario" and "Fecha".

Where is my error and how can I to solve it?

Thank you everyone: :) [1]: https://i.stack.imgur.com/v8EvS.png [2]: https://i.stack.imgur.com/D8FUj.png

I see three potential issues.

  1. In your data screenshot, Usuario has the first letter capital, but in the subset you are doing daf$usuario with the first letter small - can you check if that is correct?

  2. There is an issue with the following line:

dat <- daf[daf$usuario == input$Usuario & daf$Fecha == input$fecha]

This needs a comma at the end.

In dataframes, you have one of the following two structures: daf[BOOL1, BOOL2] or daf[BOOL2]

BOOL1 defines which rows to pick up, BOOL2 defines which columns to pick up (they both act as filters).

Since you do not have a comma, you are running the second option, which means your usuario and Fecha filters are working as column filters - except you don't have that many columns, so it throws an error. You want to run them as row filters, so you need to make sure that R knows that is supposed to be BOOL1.

You can do it like so:

dat <- daf[daf$usuario == input$Usuario & daf$Fecha == input$fecha,]

Note the comma at the end. Now, R knows that the filter is BOOL1, and there is no filter for BOOL2 so it takes everything.

This needs to be corrected in both outputs, since you have the same filter in both.

  1. You might also want to check the first line (daf[input$clase]) since input$clase will again be passed as a column filter there. What are you trying to do with that?

mod1 <- naiveBayes(daf[input$clase] ~., data = d)

This will take input$clase (which has a value like personalFamiliayamigos) and try to pass it as a BOOL2, or column filter, to daf - but daf does not have any column called personalFamiliayamigos, and so it will throw an error.

If you want to train a Naive Bayes model to only learn for this one class, you should do something like the following:

mod1 <- naiveBayes(Tipo ~., data = daf[daf$Tipo %in% input$clase, ])

You can try this and see if it works.

  1. Some miscellaneous items

Why are you reading in a file from CSV and then converting it to data frame in a separate variable? Doesn't read.csv automatically make d a dataframe? If not, why not convert to dataframe and store back in d ? Why use a separate variable daf ?

You are not using the Naive Bayes model in the plot, so why train the model in output$Grafico ? It's not needed, right? You can remove that line if you're not doing anything with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM