python sklearn做文本分类
文本挖掘的paper没找到统一的benchmark,只好自己跑程序,走过路过的前辈如果知道20newsgroups或者其它好用的公共数据集的分类(最好要所有类分类结果,全部或取部分特征无所谓)麻烦留言告知下现在的benchmark,万谢!
嗯,说正文。20newsgroups官网上给出了3个数据集,这里我们用最原始的20news-19997.tar.gz。
分为以下几个过程:
- 加载数据集
- 提feature
- 分类
- Naive Bayes
- KNN
- SVM
- 聚类
- #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);
- #print category names
- from pprint import pprint
- pprint(list(newsgroup_train.target_names))
结果:
'comp.os.ms-windows.misc',
'comp.sys.ibm.pc.hardware',
'comp.sys.mac.hardware',
'comp.windows.x']
- #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_features]
- print 'Size of fea_train:' + repr(fea_train.shape)
- print 'Size of fea_train:' + repr(fea_test.shape)
- #11314 documents, 130107 vectors for all categories
- print 'The average feature sparsity is {0:.3f}%'.format(
- fea_train.nnz/float(fea_train.shape[0]*fea_train.shape[1])*100);
结果:
Size of fea_train:(1955, 10000)
The average feature sparsity is 1.002%
上面代码注释说TF-IDF在train和test上提取的feature维度不同,那么怎么让它们相同呢?有两种方法:
- #----------------------------------------------------
- #method 1:CountVectorizer+TfidfTransformer
- print '*************************\nCountVectorizer+TfidfTransformer\n*************************'
- from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
- count_v1= CountVectorizer(stop_words = 'english', max_df = 0.5);
- counts_train = count_v1.fit_transform(newsgroup_train.data);
- print "the shape of train is "+repr(counts_train.shape)
- count_v2 = CountVectorizer(vocabulary=count_v1.vocabulary_);
- counts_test = count_v2.fit_transform(newsgroups_test.data);
- print "the shape of test is "+repr(counts_test.shape)
- tfidftransformer = TfidfTransformer();
- tfidf_train = tfidftransformer.fit(counts_train).transform(counts_train);
- tfidf_test = tfidftransformer.fit(counts_test).transform(counts_test);
*************************
the shape of train is (2936, 66433)
the shape of test is (1955, 66433)
- #method 2:TfidfVectorizer
- print '*************************\nTfidfVectorizer\n*************************'
- from sklearn.feature_extraction.text import TfidfVectorizer
- tv = TfidfVectorizer(sublinear_tf = True,
- max_df = 0.5,
- stop_words = 'english');
- tfidf_train_2 = tv.fit_transform(newsgroup_train.data);
- tv2 = TfidfVectorizer(vocabulary = tv.vocabulary_);
- tfidf_test_2 = tv2.fit_transform(newsgroups_test.data);
- print "the shape of train is "+repr(tfidf_train_2.shape)
- print "the shape of test is "+repr(tfidf_test_2.shape)
- analyze = tv.build_analyzer()
- tv.get_feature_names()#statistical features/terms
*************************
TfidfVectorizer
*************************
the shape of train is (2936, 66433)
the shape of test is (1955, 66433)
但是这种方法不能挑出几个类的feature,只能全部20个类的feature全部弄出来:
- print '*************************\nfetch_20newsgroups_vectorized\n*************************'
- from sklearn.datasets import fetch_20newsgroups_vectorized
- tfidf_train_3 = fetch_20newsgroups_vectorized(subset = 'train');
- tfidf_test_3 = fetch_20newsgroups_vectorized(subset = 'test');
- print "the shape of train is "+repr(tfidf_train_3.data.shape)
- print "the shape of test is "+repr(tfidf_test_3.data.shape)
fetch_20newsgroups_vectorized
*************************
the shape of train is (11314, 130107)
the shape of test is (7532, 130107)
- ######################################################
- #Multinomial Naive Bayes Classifier
- print '*************************\nNaive Bayes\n*************************'
- from sklearn.naive_bayes import MultinomialNB
- from sklearn import metrics
- newsgroups_test = fetch_20newsgroups(subset = 'test',
- categories = categories);
- fea_test = vectorizer.fit_transform(newsgroups_test.data);
- #create the Multinomial Naive Bayesian Classifier
- clf = MultinomialNB(alpha = 0.01)
- clf.fit(fea_train,newsgroup_train.target);
- pred = clf.predict(fea_test);
- calculate_result(newsgroups_test.target,pred);
- #notice here we can see that f1_score is not equal to 2*precision*recall/(precision+recall)
- #because the m_precision and m_recall we get is averaged, however, metrics.f1_score() calculates
- #weithed average, i.e., takes into the number of each class into consideration.
注意我最后的3行注释,为什么f1≠2*(准确率*召回率)/(准确率+召回率)
其中,函数calculate_result计算f1:
- def calculate_result(actual,pred):
- m_precision = metrics.precision_score(actual,pred);
- m_recall = metrics.recall_score(actual,pred);
- print 'predict info:'
- print 'precision:{0:.3f}'.format(m_precision)
- print 'recall:{0:0.3f}'.format(m_recall);
- print 'f1-score:{0:.3f}'.format(metrics.f1_score(actual,pred));
3.2 KNN:
- ######################################################
- #KNN Classifier
- from sklearn.neighbors import KNeighborsClassifier
- print '*************************\nKNN\n*************************'
- knnclf = KNeighborsClassifier()#default with k=5
- knnclf.fit(fea_train,newsgroup_train.target)
- pred = knnclf.predict(fea_test);
- calculate_result(newsgroups_test.target,pred);
3.3 SVM:
- ######################################################
- #SVM Classifier
- from sklearn.svm import SVC
- print '*************************\nSVM\n*************************'
- svclf = SVC(kernel = 'linear')#default with 'rbf'
- svclf.fit(fea_train,newsgroup_train.target)
- pred = svclf.predict(fea_test);
- calculate_result(newsgroups_test.target,pred);
结果:
*************************
Naive Bayes
*************************
predict info:
precision:0.764
recall:0.759
f1-score:0.760
*************************
KNN
*************************
predict info:
precision:0.642
recall:0.635
f1-score:0.636
*************************
SVM
*************************
predict info:
precision:0.777
recall:0.774
f1-score:0.774
4. 聚类
- ######################################################
- #KMeans Cluster
- from sklearn.cluster import KMeans
- print '*************************\nKMeans\n*************************'
- pred = KMeans(n_clusters=5)
- pred.fit(fea_test)
- calculate_result(newsgroups_test.target,pred.labels_);
结果:
*************************
KMeans
*************************
predict info:
precision:0.264
recall:0.226
f1-score:0.213
本文全部代码下载:在此
貌似准确率好低……那我们用全部特征吧……结果如下:
*************************
Naive Bayes
*************************
predict info:
precision:0.771
recall:0.770
f1-score:0.769
*************************
KNN
*************************
predict info:
precision:0.652
recall:0.645
f1-score:0.645
*************************
SVM
*************************
predict info:
precision:0.819
recall:0.816
f1-score:0.816
*************************
KMeans
*************************
predict info:
precision:0.289
recall:0.313
f1-score:0.266
python sklearn做文本分类相关推荐
- python sklearn svm_文本分类和预测 sklearn.svm.LinearSVC(1)
参考代码manoveg/ML_with_pythongithub.com 数据来源https://github.com/gaussic/text-classification-cnn-rnngit ...
- 手把手教你在Python中实现文本分类(附代码、数据集)
作者: Shivam Bansal 翻译:申利彬 校对:丁楠雅 本文约2300字,建议阅读8分钟. 本文将详细介绍文本分类问题并用Python实现这个过程. 引言 文本分类是商业问题中常见的自然语言处 ...
- Python中实现文本分类(附代码、数据集)
本文将详细介绍文本分类问题并用Python实现这个过程. 引言 文本分类是商业问题中常见的自然语言处理任务,目标是自动将文本文件分到一个或多个已定义好的类别中.文本分类的一些例子如下: 分析社交媒体中 ...
- bert使用做文本分类_使用BERT进行深度学习的多类文本分类
bert使用做文本分类 Most of the researchers submit their research papers to academic conference because its ...
- Word Averaging模型做文本分类 稳定效果好模型简单
利用WORDAVG模型做文本分类 模型简单 效果号 简单思想就是 将每个词向量在 句子维度进行求平均 可以用avgpool来做平均池化 然后用平均后的向量作为句子向量 进行文本分类 后面我们还 ...
- 贝叶斯分类器做文本分类案例
贝叶斯分类器做文本分类 文本分类是现代机器学习应用中的一大模块,更是自然语言处理的基础之一.我们可以通过将文字数据处理成数字数据,然后使用贝叶斯来帮助我们判断一段话,或者一篇文章中的主题分类,感情倾向 ...
- python文本分类_手把手教你在Python中实现文本分类.pdf
手把手教你在Python 中实现文本分类(附代码.数 据集) 引言 文本分类是商业问题中常见的自然语言处理任务,目标是自动将文本文件分到一个 或多个已定义好的类别中.文本分类的一些例子如下: • 分析 ...
- 使用CNN做文本分类——将图像2维卷积换成1维
使用CNN做文本分类from __future__ importdivision, print_function, absolute_importimporttensorflow as tfimpor ...
- tf第十二讲:TextCNN做文本分类的实战代码
大家好,我是爱编程的喵喵.双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中.从事机器学习以及相关的前后端开发工作.曾在阿里云.科大讯飞.CCF等比赛获得多次Top名次.现 ...
- bert模型可以做文本主题识别吗_GitHub - jkszw2014/TextClassify_with_BERT: 使用BERT模型做文本分类;面向工业用途...
TextClassify_with_BERT 使用BERT模型做文本分类:面向工业用途 自己研究了当前开源的使用BERT做文本分类的许多存储库,各有各的缺点.通病就是面向学术,不考虑实际应用. 使用t ...
最新文章
- 使用Redis搭建电商秒杀系统
- 跟锦数学2017年04月
- MTK Read/Write IMEI from App
- 牛客小白月赛16 小石的签到题(博弈)
- 看完这13张图,不得不佩服还是外国人会玩人工智能
- Flash of Unstyled Content (FOUC)
- How to use wget to download mail archives?
- 今天谈谈用户故事地图,不是用户故事
- 面试中几个基本的重要问题总结
- idea新建一个springboot项目_SpringBoot(二):第一个Spring Boot项目
- PotPlayer LAV MadVR SVP4/BFRC播放器设置(极为详细,硬解,渲染,插帧按CPU性能评级)
- 世界上有没有正五面体?
- Bestcoder13 1003.Find Sequence(hdu 5064) 解题报告
- 笔耕不辍 elementUI el-tree实现懒加载和直接查询实现
- MMORPG传奇类手游《空空西游》完整源码(客户端cocos2d-js+服务端pomelo+cocosStudio工程+搭建教程)
- Ford-Fulkerson 标号法求网络最大流
- 微信小程序开发入门(连载)—— 开发前的准备工作
- ps制作双重曝光海报
- 强烈推荐一部电影《贫民窟的百万富翁》
- Java学习 day11 (继承与多态)接口、多态
热门文章
- Tomcat反射时报错java.lang.ClassNotFoundException
- java虚拟机内存_java虚拟机内存区域的划分以及作用详解
- python判断中文函数_如何判断(或如何编写)一个没有副作用的python函数?
- python实例方法不可以用类调用_为什么python静态/类方法不可调用?
- C# 从string变量中获取数字
- c++ primer plus 复合类型之数组
- 责任分配矩阵和raci的区别_数字音频处理器和调音台的区别是什么
- C语言-用指针实现内存动态分配
- 3-unit2 高级网络配置
- 《Excel数据可视化:一样的数据不一样的图表》——第 2 章 数理统计中的常见统计量 2.1 比平均值更稳定的中位数和众数...