【问题标题】:Why is self not the class instance when using scikit-learn pipelines?为什么使用 scikit-learn 管道时 self 不是类实例?
【发布时间】:2020-07-18 21:47:32
【问题描述】:

从标题中可以看出,来自类实例的self 并不是类实例本身。

当我使用带有 scikit-learn 管道的自定义类时会发生这种情况,但当我单独使用相同的自定义类时不会发生这种情况。

import pandas as pd
import numpy as np

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import OneHotEncoder

class multi_feature_OHE(BaseEstimator, TransformerMixin):
    ''' Encode multiple redundant features as one, usign One-Hot-Encoder. '''
    def __init__(self):
        self.encoder = OneHotEncoder(handle_unknown='ignore')

    def fit(self, X):
        #self.encoder.fit(X)
        print(type(self))    # <--- We print the type of self here!
        return self

    def transform(self, X):
        ...

这里打印&lt;class 'numpy.ndarray'&gt;

pipeline = make_pipeline(...,
                         multi_feature_OHE)
pipeline.fit(data)

fit 方法中,self == XX == None

但这里打印的是&lt;class '__main__.multi_feature_OHE'&gt;

a = multi_feature_OHE()
a.fit(data)

【问题讨论】:

    标签: python python-3.x numpy scikit-learn


    【解决方案1】:

    您应该将类​​的实例 em>传递给管道,您通过类对象本身,没有实例。因此,请执行以下操作:

    pipeline = make_pipeline(...,
                             multi_feature_OHE())
    pipeline.fit(data)
    

    查看the docs

    的示例

    基本上,管道将采用任何对象并在其上致电@ 987654324。如果您只传递类对象,那么multi_feature_OHE.fit只是普通函数,所以第一个参数将从最后一个转换中获取数组。

    查看the docs

    的示例
    >>> from sklearn.naive_bayes import GaussianNB
    >>> from sklearn.preprocessing import StandardScaler
    >>> make_pipeline(StandardScaler(), GaussianNB(priors=None))
    Pipeline(steps=[('standardscaler', StandardScaler()),
                    ('gaussiannb', GaussianNB())])
    

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2015-08-14
      • 2018-07-21
      • 2021-03-17
      • 2018-07-26
      • 1970-01-01
      • 2021-01-12
      • 2018-09-24
      • 2023-03-11
      相关资源
      最近更新 更多