我正在尝试在链接中复制论文的结果
https://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html
此链接说明了多项式朴素贝叶斯如何用于文本分类。
我尝试使用scikit Learn重现该示例。
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import preprocessing, decomposition, model_selection, metrics, pipeline
from sklearn.model_selection import GridSearchCV, cross_val_score, KFold
from sklearn.metrics import accuracy_score
from sklearn.metrics import make_scorer
from sklearn.naive_bayes import MultinomialNB
#TRAINING SET
dftrain = pd.DataFrame(data=np.array([["Chinese Beijing Chinese", "Chinese Chinese Shanghai", "Chinese Macao", "Tokyo Japan Chinese"],
["yes", "yes", "yes", "no"]]))
dftrain = dftrain.T
dftrain.columns = ['text', 'label']
#TEST SET
dftest = pd.DataFrame(data=np.array([["Chinese Chinese Chinese Tokyo Japan"]]))
dftest.columns = ['text']
count_vectorizer = CountVectorizer(min_df=0, token_pattern=r"\b\w+\b", stop_words = None)
count_train = count_vectorizer.fit_transform(dftrain['text'])
count_test = count_vectorizer.transform(dftest['text'])
clf = MultinomialNB()
clf.fit(count_train, df['label'])
clf.predict(count_test)
输出正确打印为:
array(['yes'],
dtype='<U3')
就像它在论文中提到的一样!
该论文预测为“是”,因为
P(yes | test set) = 0.0003 > P(no | test set) = 0.0001
我希望能够看到这两个概率!
当我键入:
clf.predict_proba(count_test)
我懂了
array([[ 0.31024139, 0.68975861]])
我认为这意味着:
P(test belongs to label 'no') = 0.31024139
和
P(test belongs to label 'yes') = 0.68975861
因此,
scikit-learn
预测文本属于标签yes
,但是我的问题是:为什么概率不同?
P(yes | test set) = 0.0003 > P(no | test set) = 0.0001
,我看不到数字0.0003
和0.0001
,而是看到0.31024139
和0.68975861
我在这里想念什么吗?这与
class_prior
参数有关吗?我确实阅读了文档!
http://scikit-learn.org/stable/modules/naive_bayes.html#multinomial-naive-bayes
显然,该参数是通过最大似然的平滑形式(即相对频率计数)估算的。
我想知道的是,无论如何,我是否可以复制并在研究论文中看到结果?
最佳答案
这更多与predict_proba
产生的概率的含义有关。 .0003和.0001的数字未规范化,即它们的总和不为1。如果将这些值归一化,您将获得相同的结果
请参见下面的代码段:
clf.predict_proba(count_test)
Out[63]: array([[ 0.31024139, 0.68975861]])
In [64]: p = (3/4)*((3/7)**3)*(1/14)*(1/14)
In [65]: p
Out[65]: 0.00030121377997263036
In [66]: p0 = (1/4)*((2/9)**3)*(2/9)*(2/9)
In [67]: p0
Out[67]: 0.00013548070246744223
#normalised values
In [68]: p/(p0+p)
Out[68]: 0.6897586117634674
In [69]: p0/(p0+p)
Out[69]: 0.3102413882365326
关于python - 无论如何,根据斯坦福大学自然语言处理研究论文,可以从scikit-learn多项朴素贝叶斯中提取出最大后验概率吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48570417/