R 使用朴素贝叶斯预测类变量

R 使用朴素贝叶斯预测类变量,r,naivebayes,R,Naivebayes,我刚刚尝试在e1071包中使用naiveBayes函数。过程如下: >library(e1071) >data(iris) >head(iris, n=5) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4

我刚刚尝试在
e1071
包中使用
naiveBayes
函数。过程如下:

>library(e1071)
>data(iris)
>head(iris, n=5)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
>model <-naiveBayes(Species~., data = iris)
> pred <- predict(model, newdata = iris, type = 'raw')
> head(pred, n=5)
         setosa   versicolor    virginica
[1,]      1.00000 2.981309e-18 2.152373e-25
[2,]      1.00000 3.169312e-17 6.938030e-25
[3,]      1.00000 2.367113e-18 7.240956e-26
[4,]      1.00000 3.069606e-17 8.690636e-25
[5,]      1.00000 1.017337e-18 8.885794e-26
结果如下:

> prob
        setosa versicolor virginica
[1,] 0.3333333  0.3333333 0.3333333
[2,] 0.3333333  0.3333333 0.3333333
[3,] 0.3333333  0.3333333 0.3333333
[4,] 0.3333333  0.3333333 0.3333333
而且很奇怪。我用作
test
的数据点是
iris
数据集的行。根据实际数据,该数据点的类变量为
setosa

Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
naiveBayes
预测正确:

             setosa   versicolor    virginica
   [1,]      1.00000 2.981309e-18 2.152373e-25

但当我试图预测
test
数据点时,它返回了错误的结果。当我只寻找一个数据点的预测时,为什么它返回预测的四行?我做错了吗?

您需要与培训数据列名相对应的列名。你的训练数据

test2 = iris[1,1:4]

predict(model, newdata = test2, type=('raw'))
     setosa   versicolor    virginica
[1,]      1 2.981309e-18 2.152373e-25
“新”测试数据定义为
data.frame

test1 = data.frame(Sepal.Length = 5.1, Sepal.Width = 3.5, Petal.Length =  1.4, Petal.Width = 0.2)

predict(model, newdata = test1, type=('raw'))
     setosa   versicolor    virginica
[1,]      1 2.981309e-18 2.152373e-25
如果你只给它一个维度,那么它可以通过贝叶斯规则进行预测

predict(model, newdata = data.frame(Sepal.Width = 3), type=('raw'))

        setosa versicolor virginica
[1,] 0.2014921  0.3519619  0.446546
如果你给它一个在训练数据中找不到的维度,你会得到同样可能的类。输入一个更长的向量只会给你更多的预测

predict(model, newdata = 1, type=('raw'))

        setosa versicolor virginica
[1,] 0.3333333  0.3333333 0.3333333

完美的解决方案!谢谢。
predict(model, newdata = 1, type=('raw'))

        setosa versicolor virginica
[1,] 0.3333333  0.3333333 0.3333333