Pipeline(…)
sklearn.pipeline模块中的函数
带有最终评估器的转移管道。连续运用一系列的转换操作和一个最终的评估器。管道的中间操作必须是’transform’,也就是说,它们必须实现fit和transform方法。最后的估计器只需要实现fit方法。管道中的转换器可以使用内存参数进行缓存。
管道的目的是组装几个步骤,这些步骤可以设置不同的参数同时进行交叉验证,因此,它可以使用它们的名称和”_“分隔的参数名称来设置各种步骤的参数,如下面的示例所示。步骤的估计器可以完全替换,通过将参数设置为另一个估计其,或者通过设置为None移除一个转换器。
在用户指南中阅读更多信息。
>>> from sklearn import svm #导入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
>>> # generate some data to play with
>>> 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)
>>> clf = svm.SVC(kernel='linear')
#以下是pipeline的关键部分
>>> anova_svm = Pipeline([('anova', anova_filter), ('svc', clf)])
>>> # You can set the parameters using the names issued
>>> # For instance, fit using a k of 10 in the SelectKBest
>>> # and a parameter 'C' of the svm
# 修改转换器的参数
>>> anova_svm.set_params(anova__k=10, svc__C=.1).fit(X, y)
...
Pipeline(memory=None,
steps=[('anova', SelectKBest(...)),
('svc', SVC(...))])
>>> prediction = anova_svm.predict(X)
>>> anova_svm.score(X, y)
0.829...
>>> # getting the selected features chosen by anova_filter
>>> anova_svm.named_steps['anova'].get_support()
...
array([False, False, True, True, False, False, True, True, False,
True, False, True, True, False, True, False, True, True,
False, False], dtype=bool)
>>> # Another way to get selected features chosen by anova_filter
>>> anova_svm.named_steps.anova.get_support()
...
array([False, False, True, True, False, False, True, True, False,
True, False, True, True, False, True, False, True, True,
False, False], dtype=bool)