【scikit-learn】05:sklearn文本分类及评价指标


今天看到一句话:

你能留给岁月的,岁月能留给你的,除了一个更好的自己,别无其他。

还能什么比这更能激励自己学习呢?

在windows下安装sklearn,直接下载winpython安装就行了。自行选择32或64位。
http://sourceforge.net/projects/winpython/

后面本文都把sklearn简称sk。sk已经自带了一些数据集,先看iris和digits:

from sklearn import datasets
iris = datasets.load_iris()
digits = datasets.load_digits()

iris中文指鸢尾植物,这里存储了其萼片和花瓣的长宽,一共4个属性,鸢尾植物又分三类。与之相对,iris里有两个属性iris.data,iris.target,data里是一个矩阵,每一列代表了萼片或花瓣的长宽,一共4列,每一列代表某个被测量的鸢尾植物,一共采样了150条记录,所以查看这个矩阵的形状iris.data.shape,返回:

(150, 4)

target是一个数组,存储了data中每条记录属于哪一类鸢尾植物,所以数组的长度是150,数组元素的值因为共有3类鸢尾植物,所以不同值只有3个。

digits存储了数字识别的数据,包含了1797条记录,每条记录又是一个8行8列的矩阵,存储的是每幅数字图里的像素点信息,digits.image.shape返回

(1797, 8, 8)

因为sk的输入数据必须是(n_samples, n_features)的形状,所以需要对digits.image做一个编号,把8*8的矩阵,变成一个含有64个元素的向量,具体方法:

import pylab as pl
data = digits.images.reshape((digits.images.shape[0], -1))

data.shape返回

(1797, 64)

以上是最常用的两个数据集。

在sk中所有的分类器或聚类工具都是一个Estimator对象,初始参数设置:

estimator = Estimator(param1=1, param2=2)
estimator.param1

训练数据时,接收一个二维数组:

estimator.fit(data)

训练结构的参数:

estimator.estimated_param_

sk还有一个文本分类的数据集,叫Twenty Newsgroups,获取方法:

from sklearn.datasets import fetch_20newsgroups

categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']

twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)

twenty_train.target_names

len(twenty_train.data)

len(twenty_train.filenames)

这个数据里一共有2257条记录,每条记录都是一个文档。要对这些文档进行分类,也需要预处理,两种办法:
•统计每个词出现的次数
•用tf-idf统计词频,tf是在一个文档里每个单词出现的次数除以文档的单词总数,idf是总的文档数除以包含该单词的文档数,再取对数;tf * idf就是这里用到的值,值越大表明单词越重要,或越相关。

一个完整的文本分类的例子:

from sklearn.feature_extraction.text import CountVectorizer

count_vect = CountVectorizer()

X_train_counts = count_vect.fit_transform(twenty_train.data)

X_train_counts.shape
Out[28]: (2257, 35788)

count_vect.vocabulary_.get(u'algorithm')
Out[29]: 4690

from sklearn.feature_extraction.text import TfidfTransformer

tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)

X_train_tf = tf_transformer.transform(X_train_counts)

X_train_tf.shape
Out[33]: (2257, 35788)

tfidf_transformer = TfidfTransformer()

X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

X_train_tfidf.shape
Out[36]: (2257, 35788)

from sklearn.naive_bayes import MultinomialNB

clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target)

docs_new = ['God is love', 'OpenGL on the GPU is fast']

X_new_counts = count_vect.transform(docs_new)

X_new_tfidf = tfidf_transformer.transform(X_new_counts)

predicted = clf.predict(X_new_tfidf)

for doc, category in zip(docs_new, predicted):
    print('%r => %s' % (doc, twenty_train.target_names[category]))

'God is love' => soc.religion.christian
'OpenGL on the GPU is fast' => comp.graphics

上面的例子:

  • 先计算了每个单词出现的次数
  • 然后计算了tf-idf值
  • 然后带入模型进行训练
  • 最后预测了两个新文档的类型

看起来预测结果基本靠谱。
linux下处理文本的时候经常使用管道”|”,这里也可以用管道把前面的几个步骤串联起来:

from sklearn.pipeline import Pipeline

text_clf = Pipeline([('vect', CountVectorizer()),
...                      ('tfidf', TfidfTransformer()),
...                      ('clf', MultinomialNB()),
... ])

text_clf = text_clf.fit(twenty_train.data, twenty_train.target)

import numpy as np

twenty_test = fetch_20newsgroups(subset='test',
...     categories=categories, shuffle=True, random_state=42)

docs_test = twenty_test.data

predicted = text_clf.predict(docs_test)

np.mean(predicted == twenty_test.target)
Out[51]: 0.83488681757656458

from sklearn.linear_model import SGDClassifier

text_clf = Pipeline([('vect', CountVectorizer()),
...                      ('tfidf', TfidfTransformer()),
...                      ('clf', SGDClassifier(loss='hinge', penalty='l2',
...                                            alpha=1e-3, n_iter=5)),
... ])

_ = text_clf.fit(twenty_train.data, twenty_train.target)

predicted = text_clf.predict(docs_test)

np.mean(predicted == twenty_test.target)
Out[56]: 0.9127829560585885

from sklearn import metrics

print(metrics.classification_report(twenty_test.target, predicted,
...     target_names=twenty_test.target_names))
                        precision    recall  f1-score   support

           alt.atheism       0.94      0.82      0.87       319
         comp.graphics       0.88      0.98      0.92       389
               sci.med       0.95      0.89      0.92       396
soc.religion.christian       0.90      0.95      0.92       398

           avg / total       0.92      0.91      0.91      1502


metrics.confusion_matrix(twenty_test.target, predicted)
Out[59]: 
array([[261,  10,  12,  36],
       [  5, 380,   2,   2],
       [  7,  32, 353,   4],
       [  6,  11,   4, 377]])

from sklearn.grid_search import GridSearchCV

parameters = {'vect__ngram_range': [(1, 1), (1, 2)],
...               'tfidf__use_idf': (True, False),
...               'clf__alpha': (1e-2, 1e-3),
... }

gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1)

gs_clf = gs_clf.fit(twenty_train.data[:400], twenty_train.target[:400])

twenty_train.target_names[gs_clf.predict(['God is love'])]
Out[64]: 'soc.religion.christian'

best_parameters, score, _ = max(gs_clf.grid_scores_, key=lambda x: x[1])

for param_name in sorted(parameters.keys()):
...     print("%s: %r" % (param_name, best_parameters[param_name]))
...
clf__alpha: 0.001
tfidf__use_idf: True
vect__ngram_range: (1, 1)

score
Out[67]: 0.90249999999999997

上面的代码

  • 首先用pipeline串联了3个处理器,一条命令搞定
  • 用MultinomialNB分类器训练完,计算了误差
  • 又用SVM训练一遍,计算误差,比前面的效果好
  • 打印分类结果报表
  • 计算confusion_matrix(混淆矩阵、观测状态转移概率矩阵)
  • 用GridSearchCV搜索最优参数
  • 显示分数

基本上,这就是用sk进行模型训练和预测的主要流程。

上面的程序输出中有以下内容:

                         precision    recall  f1-score   support
           alt.atheism       0.94      0.82      0.87       319
           comp.graphics     0.88      0.98      0.92       389
           sci.med           0.95      0.89      0.92       396
soc.religion.christian       0.90      0.95      0.92       398
 avg / total       0.92      0.91      0.91      1502

这是SVM分类结果报表,其中:

  • 准确率=被识别为该分类的正确分类记录数/被识别为该分类的记录数
  • 召回率=被识别为该分类的正确分类记录数/测试集中该分类的记录总数
  • F1-score=2(准确率 * 召回率)/(准确率 +召回率),F1-score是F-measure(又称F-score)beta=1时的特例
  • support=测试集中该分类的记录总数

Out[59]:
array([[261, 10, 12, 36],
          [ 5, 380, 2, 2],
          [ 7, 32, 353, 4],
          [ 6, 11, 4, 377]])

这是SVM分类结果的混淆矩阵,因为一共有4类,所以是一个4*4的矩阵,每一行的所有数字之和表示测试集中该分类的记录总数,等于上面报表中的support值,可以看出:

  • 第一类alt.atheism有261个被分类正确,10个被分到了comp.graphics里,12个被分到了sci.med,36个被分到了soc.religion.christian
  • 第二类comp.graphics有380个正确分类
  • 第三类sci.med有353个正确分类
  • 第四类soc.religion.christian有377个正确分类

看起来与计算机图形学(comp.graphics)相比,atheism(无神论)和christian(基督教)更容易被错分类。

最后使用的GridSearchCV会对每一种参数组合进行打分,取分数最优的参数作为模型的参数。

  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值