您的位置:首页 > 其它

第三章:WORKING WITH TEXT DATA

2016-04-11 13:38 316 查看
这一章是完整的进行一个数据挖掘的过程:

在这一章中,学习1,如何加载一个文件组件和分类,2,抽取特征向量,3,训练一个线性模型,4使用网格搜索调优。

3.2 加载一个20新闻组数据

20,000 newsgroup documents,  

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

>>>
from
sklearn.datasets
import
fetch_20newsgroups
>>>
twenty_train =
fetch_20newsgroups(subset='train',
...
categories=categories, shuffle=True,
random_state=42) 

>>>
twenty_train.target_names
['alt.atheism', 'comp.graphics', 'sci.med', 'soc.religion.christian'] 

>>>
len(twenty_train.data)
2257
>>>
len(twenty_train.filenames)2257 

打印第一个加载文件的前三行

>>>
print("\n".join(twenty_train.data[0].split("\n")[:3])) 

>>>
print(twenty_train.target_names[twenty_train.target[0]]) 

>>>
twenty_train.target[:10]
array([1, 1, 3, 3, 3, 3, 3, 2, 2, 2]) 

for
t in
twenty_train.target[:10]:
...
print(twenty_train.target_names[t]) 

3.3 Extracting features from text files 

抽取特征,最直接的方式便是词袋模型,出现的问题是数据的稀疏问题,解决方法是只存储不为0的数据。

scipy.sparse   是专门解决这个问题的。
过滤停用词

>>>
from
sklearn.feature_extraction.text
import
CountVectorizer
>>>
count_vect =
CountVectorizer()
>>>
X_train_counts =
count_vect.fit_transform(twenty_train.data)
>>>
X_train_counts.shape
(2257, 35788)

>>> count_vect.vocabulary_.get(u'algorithm')
返回索引4690 
3.3.3 词频

>>> 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
(2257, 35788) 
首先使用fit(..) 这个函数来fit评估目标,然后使用transform(..) 来改变count-matrix 统计矩阵到tf-idf表示,然后fit_transform(..)是这两部的完整版,达到同样的效果, 即使用一部达到结果
>>> tfidf_transformer = TfidfTransformer()
>>> X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)>>> X_train_tfidf.shape
3.4 训练一个分类器,使用贝叶斯
>>> 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']

>>> from sklearn.feature_extraction.text import CountVectorizer
>>> count_vect = CountVectorizer()

>>> 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]))...
3.5 对代码的封装 pipeline

>>> 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) 3.6 评估代码的效果>>> 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)
0.834... 
使用svm来进行分类,进行对比

>>> 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, random_state=42)),])


>>> _ = text_clf.fit(twenty_train.data, twenty_train.target)>>> predicted = text_clf.predict(docs_test)>>> np.mean(predicted == twenty_test.target)0.912...特征选择是减少模型复杂度的一个特殊种类。其他的方法是:(a)减少线性回归多项式模型的次数,(b)减少人工神经网络节点的个数/层数,(c)增加RBF核的带宽等等。
减少过拟合的另外一种选择:增加分类器的正则化(减少线性SVC的C的系数)
我们有了1000个样本,要预测一个类别,并且有了标签,使用LinearSVC(LinearSVC代表线性核的支持向量分类)。LinearSVC需要选择正则化;我们使用标准L2范数惩罚和C=10.

对于更多的特征和样本,LinearSVC在这样大小的数据集上会有一点慢;使用SGDClassifier。这个分类器学习到一个线性模型(就像LinearSVC或logistic回归),但是它在训练中使用随机梯度下降(就像反向传播的人工神经网络一样)。
SGDClassifier允许小批量扫描数据,这对于数据量太大不能放到内存中时有帮助。交叉验证和这项技术不兼容;使用逐步验证代替:这里,估计器总是在训练数据集的下一块上进行测试(在用它进行训练之前)。训练之后,会再次进行测试来检查它适应数据的能力。但是SGDClassifier很不幸的不兼容核技巧rbf。替代方法是可以使用一个多层的感知机,它也可以使用随机梯度下降进行训练。sklearn提供的更全面的衡量标准:
>>> from sklearn import metrics
>>> print(metrics.classification_report(twenty_test.target, predicted,... target_names=twenty_test.target_names))

>>> metrics.confusion_matrix(twenty_test.target, predicted) 

3.7 参数
使用梯度下降找到最优参数

>>> 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'])]'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]))
... 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: