应用scikit-learn做文本分类(转)
文本挖掘的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
应用scikit-learn做文本分类(转)的更多相关文章
- 《机器学习系统设计》之应用scikit-learn做文本分类(上)
前言: 本系列是在作者学习<机器学习系统设计>([美] WilliRichert)过程中的思考与实践,全书通过Python从数据处理.到特征project,再到模型选择,把机器学习解决这个 ...
- 使用CNN做文本分类——将图像2维卷积换成1维
使用CNN做文本分类 from __future__ import division, print_function, absolute_import import tensorflow as tf ...
- 应用scikit-learn做文本分类
文本挖掘的paper没找到统一的benchmark,只好自己跑程序,走过路过的前辈如果知道20newsgroups或者其它好用的公共数据集的分类(最好要所有类分类结果,全部或取部分特征无所谓)麻烦留言 ...
- 如何使用scikit—learn处理文本数据
答案在这里:http://www.tuicool.com/articles/U3uiiu http://scikit-learn.org/stable/modules/feature_extracti ...
- 文本分类实战(十)—— BERT 预训练模型
1 大纲概述 文本分类这个系列将会有十篇左右,包括基于word2vec预训练的文本分类,与及基于最新的预训练模型(ELMo,BERT等)的文本分类.总共有以下系列: word2vec预训练词向量 te ...
- Tensorflor实现文本分类
Tensorflor实现文本分类 下面我们使用CNN做文本分类 cnn实现文本分类的原理 下图展示了如何使用cnn进行句子分类.输入是一个句子,为了使其可以进行卷积,首先需要将其转化为向量表示,通常使 ...
- scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类 (python代码)
scikit learn 模块 调参 pipeline+girdsearch 数据举例:文档分类数据集 fetch_20newsgroups #-*- coding: UTF-8 -*- import ...
- R语言做文本挖掘 Part4文本分类
Part4文本分类 Part3文本聚类提到过.与聚类分类的简单差异. 那么,我们需要理清训练集的分类,有明白分类的文本:測试集,能够就用训练集来替代.预測集,就是未分类的文本.是分类方法最后的应用实现 ...
- 基于Naive Bayes算法的文本分类
理论 什么是朴素贝叶斯算法? 朴素贝叶斯分类器是一种基于贝叶斯定理的弱分类器,所有朴素贝叶斯分类器都假定样本每个特征与其他特征都不相关.举个例子,如果一种水果其具有红,圆,直径大概3英寸等特征,该水果 ...
随机推荐
- Android 广播(内部类)
1.广播定义在一个单独的文件中 源码: public class MessageReceiver extends BroadcastReceiver{ @Override public void on ...
- Android 时间格式的正则表达式
//日期格式yyyy PatternsDict.date_y= /^(\d{4})$/; //日期格式yyyy-mm PatternsDict.date_ym= /^(\d{4})-(0\d{1} ...
- ubuntu 12.04安装vncserver
1.安装桌面 apt-get install ubuntu-desktop 2.安装vncserver apt-get install vnc4server 3.设置vncserver密码 vncpa ...
- java string,需要进行首字母大写改写
java string,需要进行首字母大写改写,网上大家的思路基本一致,就是将首字母截取,转化成大写然后再串上后面的,类似如下代码 //首字母大写 public static String c ...
- c# 获取数组中最大数的值
求数组中最大的数的值:1.数组的max函数: class Program { static void Main(string[] args) { ,,,,,,,,,}; int max= GetMax ...
- python lambda函数详细解析(面试经常遇到)
1 作用:通常是用来在python中创建匿名函数的 2 格式: lambda 参数[,参数] : 表达式 3 注意: (1)lambda定义的是单行函数, 如果需要复杂的函数,应该定义普通函数 (2) ...
- JSON 之 SuperObject(2): 构建方式与 AsJSon
SuperObject 构建一个 JSON 的常用方法: 从字符串.从文件.从流. unit Unit1; interface uses Windows, Messages, SysUtils, ...
- android 开发如何做内存优化
不少人认为JAVA程序,因为有垃圾回收机制,应该没有内存泄露.其实如果我 们一个程序中,已经不再使用某个对象,但是因为仍然有引用指向它,垃圾回收器就无法回收它,当然该对象占用的内存就无法被使用,这就造 ...
- Android高手进阶教程(二十八)之---Android ViewPager控件的使用(基于ViewPager的横向相册)!!!
分类: Android高手进阶 Android基础教程 2012-09-14 18:10 29759人阅读 评论(35) 收藏 举报 android相册layoutobjectclassloade ...
- HDU 1394 (逆序数) Minimum Inversion Number
原来求逆序数还可以用线段树,涨姿势了. 首先求出原始序列的逆序数,然后递推每一个序列的逆序数. #include <cstdio> #include <cstring> #in ...