2013-03-14 34 views
2

我想出來的NaiveBayes Python庫(Python 2.7版)的Python NaiveBayes:爲什麼我會得到一個ZeroDivisionError

我很奇怪,爲什麼運行這段代碼是給我一個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 

我是新來的分類器貝葉斯,那麼有沒有用我的輸入(即一個問題:數字的分佈,還是有沒有足夠的樣本?)

+0

(一射進黑暗)將問題如果強制身高和體重是花車堅持?例如'239.'而不是'239'等? – 2013-03-14 10:44:49

+0

我試過了,它適用於一些輸入,但不是全部輸入。我不知道爲什麼。 – dg123 2013-03-14 13:02:26

回答

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

並使用python3:

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