sklearn——朴素贝叶斯文本分类6

使用了countVectorizer和TfidfVectorizer两个统计统计模型,来比较使用哪个模型效果更好(其实都知道tfidf比较好,数学之美中比较好讲解),我们将通过图像可以看出两个统计模型的效果,并且使用了交叉验证
#使用交叉验证
from sklearn.datasets import fetch_20newsgroups
from sklearn.cross_validation import cross_val_score
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
import matplotlib.pyplot as plt
from sklearn.naive_bayes import MultinomialNB
news=fetch_20newsgroups(subset='all')
X,Y=news.data,news.target
k=list(range(10000,180000,10000))
k_count_score=[]
k_tfidf_score=[]
for i in k:
    #tfidf分类器
    tfidf=TfidfVectorizer(analyzer='word',stop_words='english' ,max_features=i)
    X_tfidf=tfidf.fit_transform(X)
    mnb_tfidf=MultinomialNB()
    scores_tfidf=cross_val_score(mnb_tfidf,X_tfidf,Y,cv=10,scoring='accuracy')
    score_tfidf=scores_tfidf.mean()
    k_tfidf_score.append(score_tfidf)

    #tf分类器
    count=CountVectorizer(analyzer='word',stop_words='english' ,max_features=i)
    X_count=count.fit_transform(X)
    mnb_count=MultinomialNB()
    scores_count=cross_val_score(mnb_count,X_count,Y,cv=10,scoring='accuracy')
    score_count=scores_count.mean()
    print(score_count)
    d=()
    d=X_count.get_shape()
    print("维数",d[1])
    k_count_score.append(score_count)
plt.xlabel('dimension')
plt.ylabel('accuracy')
plt.plot(k,k_count_score)
plt.plot(k,k_tfidf_score,color='red')
plt.legend()
plt.show()

结果:


红线是tfidf

蓝线是tf

横坐标是选择输入的词的维度

可以看出使用tfidf只要选择40000时效果最好,增加之后会出现过拟合

tf则选择100000时最佳

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值