scikit-learn:构建文本分类的“pipeline”简化分类过程、网格搜索调参

前端之家收集整理的这篇文章主要介绍了scikit-learn:构建文本分类的“pipeline”简化分类过程、网格搜索调参前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前两篇分别将“加载数据”和“提取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(构建生产线)

  1. >>> from sklearn.pipeline import Pipeline
  2. >>> text_clf = Pipeline([('vect',CountVectorizer()),... ('tfidf',TfidfTransformer()),... ('clf',MultinomialNB()),... ])
  3. 注意:vecttfidfclf这三个名字可以随意。
  4.  
  5. text_clf = text_clf.fit(rawData.data,rawData.target)
  6. predicted = text_clf.predict(rawData.data) #假设预测数据就是rawData.data(不想再生成数据了。。)
  7. 输出准确率:
  8. import numpy as np
  9. np.mean(predicted == rawData.target)
  10. Out[70]: 1.0
  11. 更详尽的分析:
  12. from sklearn import metrics
  13. print(metrics.classification_report(rawData.target,predicted,... target_names=rawData.target_names))
  14. precision recall f1-score support
  15.  
  16. category_1_folder 1.00 1.00 1.00 2
  17. category_2_folder 1.00 1.00 1.00 2
  18. category_3_folder 1.00 1.00 1.00 2
  19.  
  20. avg / total 1.00 1.00 1.00 6
  21.  
  22. 混淆矩阵:
  23. metrics.confusion_matrix(rawData.target,predicted)
  24. Out[73]:
  25. 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。

  1. from sklearn.grid_search import GridSearchCV
  2. parameters = {'vect__ngram_range': [(1,1),(1,2)],... 'tfidf__use_idf': (True,False),... 'clf__alpha': (1e-2,1e-3),}
  3. 注意:n_jobs=-1,高速网格搜索自动检测机器是几个核,并使用所有的核并行跑程序。。。
  4. gs_clf = GridSearchCV(text_clf,parameters,n_jobs=-1)
  5. gs_clf = gs_clf.fit(rawData.data[:4],rawData.target[:4])
  6. twenty_train.target_names[gs_clf.predict(['i love this'])]
  7. 'category_2_folder'
  8. 输出效果最好的参数:
  9. best_parameters,score,_ = max(gs_clf.grid_scores_,key=lambda x: x[1])
  10. for param_name in sorted(parameters.keys()):
  11. ... print("%s: %r" % (param_name,best_parameters[param_name]))
  12. clf__alpha: 0.001
  13. tfidf__use_idf: True
  14. vect__ngram_range: (1,1)
  15. >>> score
  16. 1.000...



至此,一个完整的,完全有scikit-learn写出来的机器学习过程搞定了。。。。。

学习中。。。

猜你在找的设计模式相关文章