【问题标题】:GaussianNB :- ValueError: The sum of the priors should be 1GaussianNB :- ValueError: 先验之和应为 1
【发布时间】:2018-02-04 09:21:39
【问题描述】:

我想做什么?

我正在尝试使用 GaussianNB 分类器训练具有 10 个标签的数据集,但是在调整我的 gaussianNB 先前参数时出现此错误:-

文件“/home/mg/anaconda2/lib/python2.7/site-packages/sklearn/naive_bayes.py”,第 367 行,在 _partial_fit raise ValueError('先验的总和应该是 1。') ValueError:先验之和应为 1。

代码:- clf = GaussianNB(先验 = [0.08, 0.14, 0.03, 0.16, 0.11, 0.16, 0.07, 0.14, 0.11, 0.0])

你可以清楚地看到总和是 1,但它显示了这个错误,你能指出错误吗?

【问题讨论】:

  • 你能分享除上述行之外的完整代码吗?也许问题出在别的地方。我尝试用你的先验初始化分类器,它工作正常。

标签: python-2.7 machine-learning scikit-learn gaussian


【解决方案1】:

这在 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 相关的求和数字错误,就像您的情况一样
    • 你的总和在技术上是 != 1.0;但非常接近!
  • 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 所示。

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多