前两篇分别将“加载数据”和“提取tf、tf-idf,进而构建分类器”,其实这个过程,vectorizer => transformer => classifier,早已被“scikit-learnprovides aPipelineclass”一下就可以搞定:
本篇翻译:
http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html,
1、Building a pipeline(构建生产线)
- >>> from sklearn.pipeline import Pipeline
- >>> text_clf = Pipeline([('vect',CountVectorizer()),... ('tfidf',TfidfTransformer()),... ('clf',MultinomialNB()),... ])
- 注意:vect、tfidf、clf这三个名字可以随意。
- text_clf = text_clf.fit(rawData.data,rawData.target)
- predicted = text_clf.predict(rawData.data) #假设预测数据就是rawData.data(不想再生成数据了。。)
- 输出准确率:
- import numpy as np
- np.mean(predicted == rawData.target)
- Out[70]: 1.0
- 更详尽的分析:
- from sklearn import metrics
- print(metrics.classification_report(rawData.target,predicted,... target_names=rawData.target_names))
- precision recall f1-score support
- category_1_folder 1.00 1.00 1.00 2
- category_2_folder 1.00 1.00 1.00 2
- category_3_folder 1.00 1.00 1.00 2
- avg / total 1.00 1.00 1.00 6
- 混淆矩阵:
- metrics.confusion_matrix(rawData.target,predicted)
- Out[73]:
- array([[2,0],[0,2,2]])
2、Parameter tuning using grid search(使用网格搜索调参)
思想: run an exhaustive search of the best parameters on a grid of possible values。
- 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),}
- 注意:n_jobs=-1,高速网格搜索自动检测机器是几个核,并使用所有的核并行跑程序。。。
- gs_clf = GridSearchCV(text_clf,parameters,n_jobs=-1)
- gs_clf = gs_clf.fit(rawData.data[:4],rawData.target[:4])
- twenty_train.target_names[gs_clf.predict(['i love this'])]
- 'category_2_folder'
- 输出效果最好的参数:
- 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
- 1.000...
至此,一个完整的,完全有scikit-learn写出来的机器学习过程搞定了。。。。。
学习中。。。