如何计算naive_bayes MultinomialNB中的feature_log_prob_?

问题描述 投票:0回答:1

这是我的代码。

# Load libraries
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
# Create text
text_data = np.array(['Tim is smart!',
                      'Joy is the best',
                      'Lisa is dumb',
                      'Fred is lazy',
                      'Lisa is lazy'])
# Create target vector
y = np.array([1,1,0,0,0])
# Create bag of words
count = CountVectorizer()
bag_of_words = count.fit_transform(text_data)    # 

# Create feature matrix
X = bag_of_words.toarray()

mnb = MultinomialNB(alpha = 1, fit_prior = True, class_prior = None)
mnb.fit(X,y)

print(count.get_feature_names())
# output:['best', 'dumb', 'fred', 'is', 'joy', 'lazy', 'lisa', 'smart', 'the', 'tim']


print(mnb.feature_log_prob_) 
# output 
[[-2.94443898 -2.2512918  -2.2512918  -1.55814462 -2.94443898 -1.84582669
  -1.84582669 -2.94443898 -2.94443898 -2.94443898]
 [-2.14006616 -2.83321334 -2.83321334 -1.73460106 -2.14006616 -2.83321334
  -2.83321334 -2.14006616 -2.14006616 -2.14006616]]

我的问题是: 比如说:"最好 "这个词:"最好 "的概率是多少?class 1 : -2.14006616. 要计算出这个分数,要用什么公式来计算。

我使用的是 LOG (P(best|y=class=1)) -> Log(1/2) -> 不能得到 -2.14006616

machine-learning scikit-learn naivebayes
1个回答
0
投票

文件 由此可知 feature_log_prob_ 对应于给定一个类的特征的经验对数概率。我们以一个 "最佳 "特征为例来说明,这个特征就是 log 该特征在类的概率 1-2.14006616 (正如你所指出的),现在如果我们把它转换成实际的概率分数,它将是 np.exp(1)**-2.14006616 = 0.11764. 让我们再退一步,看看 "最佳 "的概率是如何以及为什么会出现在班级中的 10.11764. 根据文件中的规定。多项式奈夫贝叶斯,我们看到,这些概率是用下面的公式计算出来的。

enter image description here

其中,分子大致对应于特征 "最佳 "在类中出现的次数。1 (本例中我们感兴趣的),分母对应于类的所有特征的总计数。1. 此外,我们还增加了一个小的平滑值。alpha 以防止概率为零和 n 对应于总的特征数,即词汇量的大小。计算这些数字的例子,我们有。

N_yi = 1  # "best" appears only once in class `1`
N_y = 7   # There are total 7 features (count of all words) in class `1`
alpha = 1 # default value as per sklearn
n = 10    # size of vocabulary

Required_probability = (1+1)/(7+1*10) = 0.11764

你可以用类似的方式对任何给定的特征和类进行计算。

希望这能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.