从管道中获取模型属性

62

我通常会得到类似这样的PCA载荷:

pca = PCA(n_components=2)
X_t = pca.fit(X).transform(X)
loadings = pca.components_

如果我使用scikit-learn管道运行PCA

from sklearn.pipeline import Pipeline
pipeline = Pipeline(steps=[    
('scaling',StandardScaler()),
('pca',PCA(n_components=2))
])
X_t=pipeline.fit_transform(X)

能否获取载荷(loadings)?

尝试使用loadings = pipeline.components_这样简单的方法会失败:

AttributeError: 'Pipeline' object has no attribute 'components_'

(还对从管道中提取类似于 coef_ 的属性感兴趣。)

2个回答

112

你有查看过文档吗: http://scikit-learn.org/dev/modules/pipeline.html 我感觉它非常清晰。

更新: 在0.21中,您只需使用方括号即可:

pipeline['pca']

或索引

pipeline[1]

有两种方法可以到达流水线中的步骤,一种是使用索引,另一种是使用您提供的字符串名称:

pipeline.named_steps['pca']
pipeline.steps[1][1]

这将为您提供PCA对象,您可以在其上获取组件。 使用named_steps,您还可以使用.进行属性访问,从而允许自动完成:

pipeline.named_steps.pca.<tab here gives autocomplete>


1
好的,谢谢。在这个文档中使用named_steps是吗?感激不尽。 - lmart999
1
我想插入一句话,如果你的管道中有一个 regr = TransformedTargetRegressor,那么语法就不同了,你必须在访问命名步骤之前使用 regressor_ 访问回归器,例如 regr.regressor_.named_steps['pca'].components_ - Ari Cooper-Davis
奇怪的是它没有在文档页面上,但在这些文档中的“用户指南”中有。 - agent18
@agent18 它是在哪里丢失的?也许可以向sklearn提出一个问题(或者更好的是一个PR),以更新文档 :) - Andreas Mueller

7

使用 Neuraxle

使用 Neuraxle 更简单地处理管道。例如,您可以这样做:

from neuraxle.pipeline import Pipeline

# Create and fit the pipeline: 
pipeline = Pipeline([
    StandardScaler(),
    PCA(n_components=2)
])
pipeline, X_t = pipeline.fit_transform(X)

# Get the components: 
pca = pipeline[-1]
components = pca.components_

您可以根据需要使用以下三种不同的方式访问PCA:

  • pipeline['PCA']
  • pipeline[-1]
  • pipeline[1]

Neuraxle是一个基于scikit-learn构建的管道库,可将管道提升到新的水平。它允许轻松管理超参数分布空间、嵌套管道、保存和重新加载、REST API服务等等。整个东西也被设计为使用深度学习算法并允许并行计算。

嵌套管道:

您可以在管道中使用另一个管道,如下所示。

# Create and fit the pipeline: 
pipeline = Pipeline([
    StandardScaler(),
    Identity(),
    Pipeline([
        Identity(),  # Note: an Identity step is a step that does nothing. 
        Identity(),  # We use it here for demonstration purposes. 
        Identity(),
        Pipeline([
            Identity(),
            PCA(n_components=2)
        ])
    ])
])
pipeline, X_t = pipeline.fit_transform(X)

那么你需要这样做:

# Get the components: 
pca = pipeline["Pipeline"]["Pipeline"][-1]
components = pca.components_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接