使用naiveBayes预测类变量

时间:2015-06-29 15:40:45

标签: r naivebayes

我只是尝试在naiveBayes包中使用e1071函数。这是过程:

>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)来预测类变量(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数据集的行。根据实际数据,此数据点的类变量为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数据点时,会返回不正确的结果。当我在寻找一个数据点的预测时,为什么它会像预测的那样返回四行?我做错了吗?

1 个答案:

答案 0 :(得分:2)

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

test2 = iris[1,1:4]

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

&#34;新&#34;使用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
相关问题