Naive Bays in R

I get an error when starting the naive gulf classifier in R. I use the following code -

mod1 <- naiveBayes(factor(X20) ~ factor(X1) + factor(X2) +factor(X3) +factor(X4)+factor(X5)+factor(X6)+factor(X7) +factor(X8)+factor(X9) +factor(X10)+factor(X11)+ factor(X12)+factor(X13)+factor(X14) +factor(X15) +factor(X16)+factor(X17) +factor(X18)+factor(X19),data=intent.test) res1 <- predict(mod1)$posterior 

The first part of this code is working fine. But when he tries to predict the rear probability, he gives the following error -

 **Error in as.data.frame(newdata) : argument "newdata" is missing, with no default** 

I tried to run something like

 res1 <- predict(mod1,new_data=intent.test)$posterior 

but it also gives the same error.

+4
source share
1 answer

It seems you are using the e1071::naiveBayes , which expects the newdata argument to predict, therefore, two errors occur when you run your code. (You can check the source code of the predict.naiveBayes function on CRAN, the second line in the code expects newdata , as newdata <- as.data.frame(newdata) .) Also, as @Vincent pointed out, you better convert your variables into a factor before calling NB algorithm, although this certainly has nothing to do with the above errors.

Using NaiveBayes from the klar package, there will be no such problem. For instance,

 data(spam, package="ElemStatLearn") library(klaR) # set up a training sample train.ind <- sample(1:nrow(spam), ceiling(nrow(spam)*2/3), replace=FALSE) # apply NB classifier nb.res <- NaiveBayes(spam ~ ., data=spam[train.ind,]) # predict on holdout units nb.pred <- predict(nb.res, spam[-train.ind,]) # but this also works on the training sample, ie without using a `newdata` head(predict(nb.res)) 
+8
source

Source: https://habr.com/ru/post/1394975/


All Articles