手机版
你好,游客 登录 注册
背景:
阅读新闻

sklearn Pipeline使用

[日期:2017-06-19] 来源:Linux社区  作者:sa14023053 [字体: ]

简介

Pipeline按顺序构建一系列转换和一个模型,最后的一步是模型。Pipeline中间的步骤必须是转换过程,它们必须包含fit和transform方法。最后一步模型只要有fit方法。

Pipeline的目的是能组合好几个步骤,当设置不同参数的时候,可以在一起做交叉验证。可以通过【pipeline的名称+ “__” + 参数名称】(注意是两个下划线)的方式设置多个步骤的参数。

参数

名称类型说明
steps list 包含(name,transform)元组的list类型,按照元组的顺序形成一个链,最后一步是模型。
named_steps dict 只读的属性,用户通过设置的名称可以读取相应步骤的参数,keys是步骤名称,values是步骤参数

上手使用

from sklearn import svm
from sklearn.datasets import samples_generator
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from sklearn.pipeline import Pipeline

 

产生一些测试数据

X, y = samples_generator.make_classification(n_informative=5, n_redundant=0, random_state=42)

 

选择特征

# ANOVA SVM-C
anova_filter = SelectKBest(f_regression, k=5)

 

SVM模型

clf = svm.SVC(kernel='linear')

 

构建pipeline

anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)])

 

模型有两步,一步是最特征选择,一步是模型

设置参数

anova_svm.set_params(anova__k=10, svc__C=.1)

 

Pipeline(steps=[('anova', SelectKBest(k=10, score_func=<function f_regression at 0x4a0f0c8>)), ('svc', SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False))])

训练模型

anova_svm.fit(X,y)

 

Pipeline(steps=[('anova', SelectKBest(k=10, score_func=<function f_regression at 0x4a0f0c8>)), ('svc', SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False))])

预测结果

prediction = anova_svm.predict(X)
anova_svm.score(X,y)
0.77000000000000002

查看pipeline里的参数

anova_svm.named_steps['anova']

 

SelectKBest(k=10, score_func=<function f_regression at 0x4a0f0c8>)
anova_svm.named_steps['svc']

 

SVC(C=0.1, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma='auto', kernel='linear',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
anova_svm.named_steps['anova'].get_support()
array([ True,  True,  True, False, False,  True, False,  True,  True,
        True, False, False,  True, False,  True, False, False, False,
       False,  True], dtype=bool)

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-06/144939.htm

linux
相关资讯       sklearn  Pipeline 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款