从scikit-learn管道获取模型属性

时间:2015-03-03 01:52:38

标签: python scikit-learn

我通常会得到PCA这样的加载:

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

如果我使用PCA pipline运行scikit-learn ...

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

......是否有可能获得负荷?

简单地尝试loadings = pipeline.components_失败:

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

谢谢!

(也有兴趣从学习管道中提取coef_等属性。)

2 个答案:

答案 0 :(得分:44)

您是否看过文档:http://scikit-learn.org/dev/modules/pipeline.html 我觉得很清楚。

有两种方法可以使用索引或使用您提供的字符串名称来获取管道中的步骤:

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

这将为您提供PCA对象,您可以在其上获取组件。

答案 1 :(得分:5)

使用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_
相关问题