Python NaiveBayes:为什么会出现ZeroDivisionError?

2 投票
1 回答
583 浏览
提问于 2025-04-17 19:04

我正在尝试使用 NaiveBayes 这个 Python 库(python 2.7)。

我想知道为什么运行这段代码会出现 ZeroDivisionError 的错误。

#!/usr/bin/env python
import NaiveBayes

model = NaiveBayes.NaiveBayes()

model.set_real(['Height'])
model.set_real(['Weight'])
model.add_instances({'attributes':
                         {'Height': 239,
                          'Weight': 231,
                          },
                     'cases': 32,
                     'label':  'Sex=M'})

model.add_instances({'attributes':
                         {'Height': 190,
                          'Weight': 152
                          },
                     'cases': 58,
                     'label': 'Sex=F'
                     })

model.train()
result = model.predict({'attributes': {'Height': 212, 'Weight': 200}})

print("The result is %s" % (result))

这是输出结果:

Traceback (most recent call last):
  File "/tmp/py4127eDT", line 24, in <module>
    result = model.predict({'attributes': {'Height': 212, 'Weight': 200}})
  File "/usr/local/lib/python2.7/dist-packages/NaiveBayes.py", line 152, in predict
    scores[label] /= sumPx
ZeroDivisionError: float division by zero

我对贝叶斯分类器还不太了解,所以我在想我的输入有没有问题(比如:数字的分布,或者样本数量不够?)

1 个回答

3

这里有两个问题:

首先,你正在使用的是 Python 2.7,而 NaiveBayes 这个库需要 Python 3。使用 Python 2 的话,里面的除法运算会变成整数除法,结果可能会返回零。

第二,每个标签下的属性只有一个实例,所以计算出来的标准差(sigmas)都是零。

你需要给你的真实属性增加更多的变化:

import NaiveBayes

model = NaiveBayes.NaiveBayes()

model.set_real(['Height'])
model.set_real(['Weight'])
model.add_instances({'attributes':
                         {'Height': 239,
                          'Weight': 231,
                          },
                     'cases': 32,
                     'label':  'Sex=M'})

model.add_instances({'attributes':
                         {'Height': 233,
                          'Weight': 234,
                          },
                     'cases': 32,
                     'label':  'Sex=M'})
model.add_instances({'attributes':
                         {'Height': 190,
                          'Weight': 152
                          },
                     'cases': 58,
                     'label': 'Sex=F'
                     })
model.add_instances({'attributes':
                         {'Height': 191,
                          'Weight': 153
                          },
                     'cases': 58,
                     'label': 'Sex=F'
                     })

model.train()
result = model.predict({'attributes': {'Height': 212, 'Weight': 200}})

print ("The result is %s" % (result))

并且请使用 Python 3:

$ python3 bayes.py
The result is {'Sex=M': 1.0, 'Sex=F': 0.0}

撰写回答