Prediction function R: why does it return a zero-length prediction?

Update: I am using e1071 package for naiveBayes

I am new to R and am trying to build a Naive Bayes model around these toys. Then I tried to call the “anticipation” of this model. The problem I saw is this: the result from “predicts ()” is zero length. See Simple R Code. Thanks for your details!

df<-NULL df <- rbind(df, c(0,3)) df <- rbind(df, c(1,1)) df <- rbind(df, c(1,3)) model <- naiveBayes(df[,2], df[,1]) prediction <- predict(model, df[,-1]) length(prediction) ## [1] 0 
+4
source share
2 answers

The problem is that the dependent variable is expected to be a factor. Instead of using a matrix to store data, I will use a data frame (below df), which can store several types of variables (for example, number and factors). I store in df the coefficient Y and the number X and run the model ...

 df<-data.frame(Y=factor(c(0,1,1)),X=c(3,1,3)) model<-naiveBayes(Y~X,df) predict(model,df) 

Alternatively, to show that this is a factor that fixed the problem (i.e. not using a formula) ...

 model<-naiveBayes(df[,2],df[,1]) predict(model,df) 

Still working.

+6
source

I think the problem arises because naiveBayes assumes y is a categorical variable.

There is no (obvious) categorical data or account assignment table data in your example data.

If you take an example from the help using iris , the fifth column of Species is a factor variable.

 library(e1071) data(iris) m <- naiveBayes(iris[,-5], iris[,5]) m table(predict(m, iris), iris[,5]) setosa versicolor virginica setosa 50 0 0 versicolor 0 47 3 virginica 0 3 47 

It works as expected.

+2
source

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


All Articles