2

NaiveBayesPythonライブラリ(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

私はベイズ分類器を初めて使用するので、入力に問題がありますか(つまり、数値の分布、または十分なサンプルがありませんか?)

4

1 に答える 1

3

2 つの問題があります。

まず、python 2.7 を使用しており、NaiveBayesには python 3 が必要です。python 2 では、使用する除算が整数除算に変わり、ゼロが返されます。

次に、ラベルごとに各属性のインスタンスが 1 つしかないため、シグマはゼロです。

実際の属性にバリエーションを追加します。

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を使用します:

$ python3 bayes.py
The result is {'Sex=M': 1.0, 'Sex=F': 0.0}
于 2013-03-14T10:49:05.273 に答える