sklearn Pipeline使用

栏目: 数据库 · 发布时间: 9年前

内容简介:sklearn Pipeline使用

简介

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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mobilizing Web Sites

Mobilizing Web Sites

Layon, Kristofer / 2011-12 / 266.00元

Everyone has been talking about the mobile web in recent years, and more of us are browsing the web on smartphones and similar devices than ever before. But most of what we are viewing has not yet bee......一起来看看 《Mobilizing Web Sites》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码