我似乎不知道如何修复这个“ZeroDivisionError:DivisionbyZero”

2024-04-19 23:15:20 发布

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

我一直认为这是我的代码中的一个错误,我不知道如何修复它,当我试图修复它时,它最终会弄乱整个程序,我如何修复它

def p_appears_in_spam(word):
    count = 0
    total_spams = 0
    for t in train_set:
        text = t[0]
        if t[1] == 1:
            total_spams += 1
            if word in text:
                count += 1
    return count/total_spams
def p_appears_in_ham(word):
    count = 0
    total_hams = 0
    for t in train_set:
        text = t[0]
        if t[1] == 0:
            total_hams += 1
            if word in text:
                count += 1
    return count/total_hams
def total_spams_and_hams(tset):
    spams = 0
    hams = 0
    for t in tset:
        spams += 1 if t[1] == 1 else 0
        hams += 1 if t[1] == 0 else 0
    return spams, hams

p_spam = total_spams_and_hams(train_set)[0]/len(train_set) # Probability that a message is spam
p_ham = total_spams_and_hams(train_set)[1]/len(train_set) # Probability that a message is ham

def p_is_spam_given_word(word):
    return (p_appears_in_spam(word)*p_spam)/((p_appears_in_spam(word)*p_spam + p_appears_in_ham(word)*p_ham))

word = 'free'
print('Probability that a message is spam given the word "{}" is: {}'.format(word, p_is_spam_given_word(word)))

这就是我得到的错误

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-102-eaaafc1fa61f> in <module>
     31     return (p_appears_in_spam(word)*p_spam)/((p_appears_in_spam(word)*p_spam + p_appears_in_ham(word)*p_ham))
     32 word = 'free'
---> 33 print('Probability that a message is spam given the word "{}" is: {}'.format(word, p_is_spam_given_word(word)))

<ipython-input-102-eaaafc1fa61f> in p_is_spam_given_word(word)
     29 p_ham = total_spams_and_hams(train_set)[1]/len(train_set) # Probability that a message is ham
     30 def p_is_spam_given_word(word):
---> 31     return (p_appears_in_spam(word)*p_spam)/((p_appears_in_spam(word)*p_spam + p_appears_in_ham(word)*p_ham))
     32 word = 'free'
     33 print('Probability that a message is spam given the word "{}" is: {}'.format(word, p_is_spam_given_word(word)))

<ipython-input-102-eaaafc1fa61f> in p_appears_in_spam(word)
      8             if word in text:
      9                 count += 1
---> 10     return count/total_spams
     11 def p_appears_in_ham(word):
     12     count = 0

ZeroDivisionError: division by zero

在我为此编写的SPAM和hams函数中,计数的除法误差都为零


Tags: inreturnifiscounttrainspamgiven