sklearn Pipeline使用

_

简介

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

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

参数

名称类型说明
stepslist包含(name,transform)元组的list类型,按照元组的顺序形成一个链,最后一步是模型。
named_stepsdict只读的属性,用户通过设置的名称可以读取相应步骤的参数,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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值