使用 naiveBayes 预测 class 变量

Predict the class variable using 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         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

到目前为止,一切都很好。在下一步中,我尝试创建一个新数据点并使用 naivebayes 模型 (model) 来预测 class 变量 (Species),我选择了一个训练数据点.

> test = c(5.1, 3.5, 1.4, 0.2) 
> prob <- predict(model, newdata = test, type=('raw'))

结果如下:

> 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 数据集的行。根据实际数据,该数据点的class变量为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 数据点时,它 returns 不正确的结果。当我只查找一个数据点的预测时,为什么它 returns 预测为四行?我做错了吗?

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

test2 = iris[1,1:4]

predict(model, newdata = test2, type=('raw'))
     setosa   versicolor    virginica
[1,]      1 2.981309e-18 2.152373e-25

"New" 测试数据定义为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