Search code examples
rnaivebayes

The length of trainPred is not correct in prediction function with R


This is my code for part of Naive Bayes a

trainPred<- predict(NBclassfier, newdata = train, type = "raw")

but I am getting wrong number for length of trainPred which two times biger than the actual size of the trainPre.

Even when I am using

trainPred<- predict(NBclassfier, newdata = train, type = "class")

I only get 0 for length of trainPred

so when I am running bellow code I get an error

trainTable <- table(train$prog, trainPred)

The Code for NBclassifer is NBclassfier = naiveBayes(prog~., data= train)

the whole code an an error

 library(caret)
library(e1071)

 set.seed(25)
trainIndex=createDataPartition(NaiveData$prog, p=0.8)$Resample1
train=NaiveData[trainIndex, ]
test=NaiveData[-trainIndex, ]

check the balance

print(table(NaiveData$prog))



 0   1 
496 261 

Check the train table

print(table(train$prog))



 0   1 
388 218 

NBclassfier = naiveBayes(prog~., data= train)
trainPred <- predict(NBclassfier, newdata = train, type = "raw")
trainPred<- trainPred
trainTable <- table(train$prog, trainPred)


Error in table(train$prog, trainPred) :   all arguments must have the same length

Solution

  • I just solved the problem and wanted to share the answer as well,

    NBclassfier = naiveBayes(as.factor(prog)~., data= train)
    confusionMatrix(as.factor(trainPred), as.factor(train$prog), mode = "prec_recall")
    

    Justmake them Factor.