【问题标题】:Getting model attributes from pipeline从管道获取模型属性
【发布时间】:2015-05-03 13:41:03
【问题描述】:

我通常会收到这样的 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 = pipeline.components_ 失败:

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

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

【问题讨论】:

    标签: python scikit-learn pipeline


    【解决方案1】:

    你看文档了吗: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.names_steps.pca.<tab here gives autocomplete>

    【讨论】:

    • 好的,谢谢。在doc here 中不是这样(使用named_steps)。欣赏。
    • 我想通过添加这一点来劫持这个答案,如果你的管道上有一个regr = TransformedTargetRegressor,那么语法就不一样,而是你必须在你之前使用regressor_ 访问回归器访问命名步骤,即regr.regressor_.named_steps['pca'].components_。
    • 奇怪的是,它不在文档页面上,而是在该文档中的 user guide 中。
    • @agent18 它在哪里丢失了?也许打开一个问题(或者更好的 PR)给 sklearn 以更新文档:)
    【解决方案2】:

    使用 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_
    

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2015-09-01
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 2014-03-30
      • 1970-01-01
      相关资源
      最近更新 更多