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

来源:互联网 发布:2015年建筑业数据分析 编辑:程序博客网 时间:2024/05/08 23:13
使用了countVectorizer和TfidfVectorizer两个统计统计模型,来比较使用哪个模型效果更好(其实都知道tfidf比较好,数学之美中比较好讲解),我们将通过图像可以看出两个统计模型的效果,并且使用了交叉验证
#使用交叉验证from sklearn.datasets import fetch_20newsgroupsfrom sklearn.cross_validation import cross_val_scorefrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerimport matplotlib.pyplot as pltfrom sklearn.naive_bayes import MultinomialNBnews=fetch_20newsgroups(subset='all')X,Y=news.data,news.targetk=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 0
原创粉丝点击