【问题标题】:Getting probability of class using naive Bayes使用朴素贝叶斯获得类概率
【发布时间】:2023-03-08 00:37:01
【问题描述】:

我正在尝试用两个类对输入进行分类,这是代码。 dinocrypto 是两个类:

for w, cnt in list(counts.items()): #count is dict with word and it's count value
    p_word = vocab[w] / sum(vocab.values()) 
    p_w_given_dino = (word_counts["dino"].get(w, 0.0) + 1) / (sum(word_counts["dino"].values()) + v) 
    p_w_given_crypto = (word_counts["crypto"].get(w, 0.0) + 1) / (sum(word_counts["crypto"].values()) + v)

    log_prob_dino += math.log(cnt * p_w_given_dino / p_word)
    log_prob_crypto += math.log(cnt * p_w_given_crypto / p_word)

print("Score(dino)  :", math.exp(log_prob_dino + math.log(prior_dino)))
print("Score(crypto):", math.exp(log_prob_crypto + math.log(prior_crypto)))

另一种方法是:

prior_dino = (priors["dino"] / sum(priors.values()))
prior_crypto = (priors["crypto"] / sum(priors.values()))
for w, cnt in list(counts.items()):
    p_word = vocab[w] / sum(vocab.values())
    p_w_given_dino = (word_counts["dino"].get(w, 0.0) + 1) / (sum(word_counts["dino"].values()) + v) 
    p_w_given_crypto = (word_counts["crypto"].get(w, 0.0) + 1) / (sum(word_counts["crypto"].values()) + v)
    prob_dino *= p_w_given_dino
    prob_crypto *= p_w_given_crypto
t_prior_dino = prob_dino * prior_dino
t_prior_crypto = prob_crypto * prior_crypto

在第二种方法中,我得到的值非常小。

哪一个是正确的,还是两个都正确?

【问题讨论】:

  • 第二种方法将概率相乘,可能略高于零,相乘后的总结果接近于零。使用 log() 可以避免这个问题。
  • @user3760780:两者的结果都相当可观吧?只是表示方式正在改变
  • 使用 log() 后,您仍然应该在最可能的类中获得最高分。另外,我认为您没有在第二种方法中使用p_word。您也仅在第一种方法中使用cnt

标签: machine-learning classification probability text-classification naivebayes


【解决方案1】:

这些是完全等效的方法。然而,第一个是更可取的,因为处理概率的对数会使整个过程在数值上更稳定。结果应该是相同的(直到数值错误)。

但是,您在第二种方法中似乎有错误

prob_dino *= p_w_given_dino

不使用您有cnt 出现的事实;应该是这样的

prob_dino *= pow(p_w_given_dino, cnt) 

【讨论】:

  • 哦,谢谢哥们,其实我以为用for循环迭代时它会相乘,没想到我已经得到了计数值并且每个单词只迭代了一次
猜你喜欢
  • 2014-01-13
  • 2013-08-06
  • 2021-03-05
  • 2015-10-09
  • 2018-08-05
  • 1970-01-01
  • 2013-11-13
  • 2016-02-05
  • 2021-07-16
相关资源
最近更新 更多