朴素贝叶斯模型适用场景
- 海量文本分类任务
- 假设数据特征与目标之间存在线性关系
数据集
- sklearn 中的 fetch_20newsgroups
代码
"""
20 news groups classify
模型
朴数贝叶斯
"""
from sklearn.datasets import fetch_20newsgroups
news = fetch_20newsgroups(subset='all')
print(len(news.data))
print(news.data[0])
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25, random_state=33)
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer()
X_train = vec.fit_transform(X_train)
X_test = vec.transform(X_test)
from sklearn.naive_bayes import MultinomialNB
mnb = MultinomialNB()
mnb.fit(X_train, y_train)
y_predict = mnb.predict(X_test)
from sklearn.metrics import classification_report
print('The accuracy of Naive Bayes Classifier is', mnb.score(X_test, y_test))
print(classification_report(y_test, y_predict, target_names = news.target_names))
效果
![](https://img-blog.csdn.net/20170430202452441?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnMyMjUwMjI1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)