使用R语言的NaiveBayes包

马上要用朴素贝叶斯模型了,由于急于想知道数据的结果,因此最简单的希望能够有包来看一下数据,

我的数据结构大概——

1. 特征是有连续型的,有离散型的

2. 因变量参考的是我需要把因变量离散化的

3. 我不确定NaiveBayes是否可以跑混合数据(因为我的数据类型是混合的)

因此我使用了例子中的irisi数据集,并做了简单的修改,来看看NaiveBayes是否可以跑成功

library(naivebayes)
data(iris)
iris$hui <- NA
iris$hui[iris$Sepal.Width < 3] <- 'big'
iris$hui[iris$Sepal.Width == 3] <- 'big'
iris$hui[iris$Sepal.Width > 3] <- 'mouse'

iris <- iris[,-2]


ind_iris <- sample(1:nrow(iris), size = round(0.3 * nrow(iris)))
iris_train <- iris[-ind_iris, ]
iris_test <- iris[ind_iris, ]

nb_iris <- naive_bayes(Species ~ ., iris_train)
result <- predict(nb_iris, iris_test)
result

ac<- cbind(iris_test,result)

acure<- ac$Species == ac$result

ac2<- cbind(ac,acure)

nrow(ac2[ac2$result != ac2$Species,]) #计算不正确的数量

nrow(ac2)

f1 <- nrow(ac2[ac2$result != ac2$Species,]) / nrow(ac2)
f1

#head(predict(nb_iris, iris_test))

实践证明,是可以的

猜你喜欢

转载自www.cnblogs.com/candy3026/p/9099907.html