当预测变量不是二进制时,Sklearn 朴素贝叶斯伯努利分类器如何工作?

How does Sklearn Naive Bayes Bernoulli Classifier work when the predictors are not binary?

众所周知,伯努利朴素贝叶斯分类器使用二元预测变量(特征)。我没有得到的是,即使预测变量不是二进制的,scikit-learn 中的 BernoulliNB 是如何给出结果的。以下示例逐字摘自 documentation:

import numpy as np
rng = np.random.RandomState(1)
X = rng.randint(5, size=(6, 100))
Y = np.array([1, 2, 3, 4, 4, 5])
from sklearn.naive_bayes import BernoulliNB
clf = BernoulliNB()
clf.fit(X, Y)

print(clf.predict(X[2:3]))

输出:

array([3])

这是X的前10个特征,它们显然不是二进制的:

3   4   0   1   3   0   0   1   4   4   1
1   0   2   4   4   0   4   1   4   1   0
2   4   4   0   3   3   0   3   1   0   2
2   2   3   1   4   0   0   3   2   4   1
0   4   0   3   2   4   3   2   4   2   4
3   3   3   3   0   2   3   1   3   2   3

即使预测变量不是二元的,BernoulliNB 在这里如何工作?

这是由于 binarize 参数;来自 docs:

binarize : float or None, default=0.0

Threshold for binarizing (mapping to booleans) of sample features. If None, input is presumed to already consist of binary vectors.

当使用其默认值 binarize=0.0 调用时,就像您的代码中的情况一样(因为您没有明确指定),它将导致转换 X 的每个元素大于 0到 1,因此将用作 BernoulliNB 分类器的实际输入的转换后的 X 确实将包含二进制值。

binarize 参数与独立 preprocessing function of the same name 的工作方式完全相同;这里是一个简化的例子,改编你自己的:

from sklearn.preprocessing import binarize
import numpy as np

rng = np.random.RandomState(1)
X = rng.randint(5, size=(6, 1))
X
# result
array([[3],
       [4],
       [0],
       [1],
       [3],
       [0]])

binarize(X) # here as well, default threshold=0.0
# result (binary values):
array([[1],
       [1],
       [0],
       [1],
       [1],
       [0]])