应用scikit-learn做文本分类.docxVIP

  • 8
  • 0
  • 约1.13万字
  • 约 11页
  • 2020-04-09 发布于湖北
  • 举报
? 应用scikit-learn做文本分类 分类:? Data Mining? Machine Learning? Python2014-04-13 20:53?12438人阅读? 评论(16)? \o 收藏 收藏? \o 举报 举报 20newsgroups 文本挖掘 Python scikit scipy 文本挖掘的paper没找到统一的benchmark,只好自己跑程序,走过路过的前辈如果知道20newsgroups或者其它好用的公共数据集的分类(最好要所有类分类结果,全部或取部分特征无所谓)麻烦留言告知下现在的benchmark,万谢! 嗯,说正文。 20newsgroups官网上给出了3个数据集,这里我们用最原始的 20news-19997.tar.gz。 分为以下几个过程: 加载数据集 提feature 分类 Naive Bayes KNN SVM 聚类 说明:? scipy官网上有参考,但是看着有点乱,而且有bug。本文中我们分块来看。 Environment:Python 2.7 + Scipy (scikit-learn) 1.加载数据集 从 20news-19997.tar.gz下载数据集,解压到scikit_learn_data文件夹下,加载数据,详见code注释。 [python]? \o view plain view plain \o copy copy #first?extract?the?20?news_group?dataset?to?/scikit_learn_data?? from?sklearn.datasets?import?fetch_20newsgroups?? #all?categories?? #newsgroup_train?=?fetch_20newsgroups(subset=train)?? #part?categories?? categories?=?[comp.graphics,?? ?comp.os.ms-windows.misc,?? ?comp.sys.ibm.pc.hardware,?? ?comp.sys.mac.hardware,?? ?comp.windows.x];?? newsgroup_train?=?fetch_20newsgroups(subset?=?train,categories?=?categories);?? 可以检验是否load好了: [python]? \o view plain view plain \o copy copy #print?category?names?? from?pprint?import?pprint?? pprint(list(newsgroup_train.target_names))?? 结果: [comp.graphics, ?comp.os.ms-windows.misc, ?comp.sys.ibm.pc.hardware, ?comp.sys.mac.hardware, ?comp.windows.x] 2. 提feature: 刚才load进来的newsgroup_train就是一篇篇document,我们要从中提取feature,即词频啊神马的,用fit_transform Method 1. HashingVectorizer,规定feature个数 [python]? \o view plain view plain \o copy copy #newsgroup_train.data?is?the?original?documents,?but?we?need?to?extract?the??? #feature?vectors?inorder?to?model?the?text?data?? from?sklearn.feature_extraction.text?import?HashingVectorizer?? vectorizer?=?HashingVectorizer(stop_words?=?english,non_negative?=?True,?? ???????????????????????????????n_features?=?10000)?? fea_train?=?vectorizer.fit_transform(newsgroup_train.data)?? fea_test?=?vectorizer.fit_transform(newsgroups_test.data);?? ?? ?? #return?feature?vector?fea_train?[n_samples,n_

文档评论(0)

1亿VIP精品文档

相关文档