这在 sklearn 中看起来是一个非常糟糕的设计决策,因为他们正在执行通常的 不比较浮点数 的东西 (what every computer scientist should know about floating-point arithmetic),这让我感到惊讶(因为 sklearn 通常是高质量的代码)!
(尽管使用了列表,但我没有看到您的任何错误用法。文档需要一个数组,而不是像在许多其他情况下那样的数组,但是他们的代码正在做数组转换)
Their code:
if self.priors is not None:
priors = np.asarray(self.priors)
# Check that the provide prior match the number of classes
if len(priors) != n_classes:
raise ValueError('Number of priors must match number of'
' classes.')
# Check that the sum is 1
if priors.sum() != 1.0:
raise ValueError('The sum of the priors should be 1.')
# Check that the prior are non-negative
if (priors < 0).any():
raise ValueError('Priors must be non-negative.')
self.class_prior_ = priors
else:
# Initialize the priors to zeros for each class
self.class_prior_ = np.zeros(len(self.classes_),
dtype=np.float64)
所以:
- 你给出一个列表,但他们的代码会创建一个 numpy-array
- 因此
np.sum() 将用于求和
- 可能有 与 fp-math 相关的求和数字错误,就像您的情况一样
- fp-comparison
x == 1.0 被认为是坏的!
- numpy 带来了
np.isclose(),这是执行此操作的常用方法
演示:
import numpy as np
priors = np.array([0.08, 0.14, 0.03, 0.16, 0.11, 0.16, 0.07, 0.14, 0.11, 0.0])
my_sum = np.sum(priors)
print('my_sum: ', my_sum)
print('naive: ', my_sum == 1.0)
print('safe: ', np.isclose(my_sum, 1.0))
输出:
('my_sum: ', 1.0000000000000002)
('naive: ', False)
('safe: ', True)
编辑:
由于我认为此代码不好,我发布了一个问题here,您可以关注它以查看它们是否符合。
numpy.random.sample(),也采用这样的向量,实际上也在执行 fp-safe 方法(数值上更稳定的求和 + epsilon-check;但不使用 np.isclose()),如 here 所示。