Python NaiveBayes:为什么我得到一个零除法

2024-04-19 05:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试用NaiveBayesPython库(python2.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))

输出如下:

^{pr2}$

我不熟悉贝叶斯分类器,所以我的输入有问题吗(例如:数字的分布,还是样本不足?)在


Tags: instances代码addmodelresultreallabelattributes
1条回答
网友
1楼 · 发布于 2024-04-19 05:26:44

有两个问题:

首先,您使用的是python2.7,NaiveBayes需要python3。在python2中,它使用的除法变成整数除法并返回零。在

其次,每个标签的每个属性只有一个实例,因此sigma为零。在

为真实属性添加更多变化:

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))

用Python3:

^{pr2}$

相关问题 更多 >