0

I have a script to run naive bayes sentiment analysis. I success to run the script. However, when I call the script on rshiny. My script has an error "cannot coerce class naive bayes to a data frame". Can someone help me?

    corpus.clean <- twitclean %>%
      tm_map(content_transformer(tolower)) %>% 
      tm_map(removePunctuation) %>%
      tm_map(removeNumbers) %>%
      tm_map(removeWords, stopwords::stopwords("id", source = "stopwords-iso")) %>%
      tm_map(stripWhitespace)
    
    dtm <- DocumentTermMatrix(corpus.clean)
    {
      m <- as.matrix(dtm)
      v <- sort(rowSums(m),decreasing=TRUE)
      d <- data.frame(word = names(v),freq=v)
    }
    dataframe<-data.frame(text=unlist(sapply(corpus.clean, `[`)), stringsAsFactors=FALSE)
    corpus.txt<-dataframe
    
    inspect(dtm[40:50, 10:15])
    
    df.train <- df[1:7500,]
    df.test <- df[7501:10000,]
    
    dtm.train <- dtm[1:7500,]
    dtm.test <- dtm[7501:10000,]
    
    corpus.train <- corpus[1:7500]
    corpus.test <- corpus[7501:10000]
    
    dim(dtm.train)
    
    fivefreq <- findFreqTerms(dtm.train, 10)
    length((fivefreq))
    fivefreq
    ## [1] 12144
    
    # Use only 5 most frequent words (fivefreq) to build the DTM
    
    dtm.train.nb <- DocumentTermMatrix(corpus.train, control=list(dictionary = fivefreq))
    
    dim(dtm.train.nb)
    ## [1]  1500 12144
    
    dtm.test.nb <- DocumentTermMatrix(corpus.test, control=list(dictionary = fivefreq))
    
    dim(dtm.train.nb)
    
    # Function to convert the word frequencies to yes (presence) and no (absence) labels
    convert_count <- function(x) {
      y <- ifelse(x > 0, 1,0)
      y <- factor(y, levels=c(0,1), labels=c("No", "Yes"))
      y
    }
    
    # Apply the convert_count function to get final training and testing DTMs
    trainNB <- apply(dtm.train.nb, 2, convert_count)
    testNB <- apply(dtm.test.nb, 2, convert_count)
    trainNBm <- as.data.frame(as.matrix(trainNB))
    # Train the classifier
    system.time( classifier <-naiveBayes(trainNB, df.train$klasifikasi, laplace = 1) )
    
    # Use the NB classifier we built to make predictions on the test set.
    system.time(pred <- predict(classifier, newdata=testNB) )
    # Use the NB classifier we built to make predictions on the test set.
system.time(pred <- predict(classifier, newdata=testNB) )

# Create a truth table by tabulating the predicted class labels with the actual class labels 
table("Predictions"= pred,  "Actual" = df.test$klasifikasi )

# Prepare the confusion matrix
conf.mat <- confusionMatrix(pred, df.test$klasifikasi)

conf.mat

I think I got an error here, but I didn't find a solution until now.

system.time( classifier <-naiveBayes(trainNB, df.train$klasifikasi, laplace = 1) )

This is my rshiny ui.R

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

    # Application title
    titlePanel("Analysis Sentimen"),

    # Sidebar with a slider input for number of bins
    sidebarLayout(
        sidebarPanel(
        ),
        mainPanel(
            tabsetPanel(type="tab", 
                        tabPanel("Data File", tableOutput("negpos"), tableOutput("table")), 
                        tabPanel("Preprocessing Data",  tableOutput("corpustxt")), 
                        tabPanel("Confusion Matrix", tableOutput("confmat"), tableOutput("confacc")),
                        tabPanel("Hasil Prediksi", tableOutput("testpred")),
                        tabPanel("Plot", plotOutput("plotpred")))
    )
)))

server.R

library(shiny)

source("C:/Documents/latihan.R")
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
    
    output$table <- renderTable({
        df
    })
    
    output$corpustxt <- renderTable({
        corpus.txt()
    })
    
    output$confmat <- renderTable({
        conf.mat
    })
    
    output$negpos <- renderTable({
        table(df$klasifikasi)
        
    output$plotpred <- renderPlot({
        plotpred
    })
    })
})

This is my error

Warning: Error in as.data.frame.default: cannot coerce class ‘"naiveBayes"’ to a data.frame
  81: stop
  80: as.data.frame.default
  78: data.frame
  77: write.table
  72: observeEventHandler [C:\Users\Documents\AnalisisSentimen\AnalisisSentimenApp/server.R#211]
   1: runApp
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Agt
  • 1
  • 1
  • Welcome to SO! Without a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), it is difficult to say where the error is. Try to get the stacktrace, so you know exactly where the error occurs. The error message means that you try to use the output of your naiveBayes function as a data.frame, so maybe something in the `renderTable` calls goes wrong. You could place a `browser` in the different functions to analyse it. – starja Aug 12 '20 at 06:22
  • thanks @starja ! To be honest i have checked it many times. What I find strange is that the script can be run outside of shiny. This makes it difficult for me to identify any possible errors. I think if data.frame is error, then the script can't be run outside of shiny. However, with this error the script can be run outside of shiny. It make me feel the data.frame is correct. – Agt Aug 12 '20 at 10:42
  • The thing is, how to get from a feeling to know where the error is ;) Have a look at the [debugging part](https://mastering-shiny.org/action-workflow.html#debugging) of this shiny tutorial, try to get the traceback to see where exactly the error arises or work with `browser()` in your shiny app at different positions in your `server` function – starja Aug 12 '20 at 11:46
  • Hello @starja . I've rechecked my script and I think I'm having an error in the confusion matrix in this row conf.mat <- confusionMatrix(pred, df.test$klasifikasi). Do you have any suggestions for displaying confusion matrix in shiny? – Agt Aug 13 '20 at 04:59

0 Answers0