使用自定义转换器子类对 sklearn 管道进行评分时出现 AttributeError,但在拟合时却没有

AttributeError when scoring sklearn pipeline with custom transformer subclass but not when fitting

我在理解如何创建 sklearn t运行sformer 的子class 时遇到问题。我想为长代码示例道歉,我试图使最小可重现性,但无法重新创建错误。希望您会看到大部分代码示例都是我记录的。

下面的代码片段中描述了 t运行sformer。

class PCAVarThreshSelector(PCA):
"""
Description
-----------
Selects the columns that can explain a certain percentage of the variance in a data set

Authors
-------
Eden Trainor

Notes
-----
1. PCA has a principole component limit of 4459 components, no matter how many more features you put into
it this is a hrad limit of how many components it will return to you.

"""

def __init__(self, 
             n_components=None, 
             copy=True, 
             whiten=False, 
             svd_solver='auto', 
             tol=0.0, 
             iterated_power='auto', 
             random_state=None, 
             explained_variance_thresh = 0.8):


    super(PCAVarThreshSelector, self).__init__(n_components, copy, whiten, svd_solver, tol, iterated_power, random_state)


    self.explained_variance_thresh = explained_variance_thresh

def find_nearest_index(self, array, value):
    """
    Description
    -----------
    Finds the index of the coefficient in an array nearest a certain value.


    Args
    ----
    array: np.ndarray, (number_of_componants,)
        Array containing coeffficients 

    value: int,
        Index of coefficient in array closset to this value is found.


    Returns
    -------
    index: int,
        Index of coefficient in array closest to value.
    """

    index = (np.abs(array - value)).argmin()

    return index

def fit(self, X, y = None):
    """
    Description
    -----------
    Fits the PCA and calculates the index threshold index of the cumulative explained variance ratio array.


    Args
    ----
    X: DataFrame, (examples, features)
        Pandas DataFrame containing training example features

    y: array/DataFrame, (examples,)
        (Optional) Training example labels

    Returns
    -------
    self: PCAVarThreshSelector instance
        Returns transfromer instance with fitted instance variables on training data.
    """

    #PCA fit the dataset
    super(PCAVarThreshSelector, self).fit(X)

    #Get the cumulative explained variance ratio array (ascending order of cumulative variance explained)
    cumulative_EVR = self.explained_variance_ratio_.cumsum()

    #Finds the index corresponding to the threshold amount of variance explained
    self.indx = self.find_nearest_index(array = cumulative_EVR, 
                                    value = self.explained_variance_thresh)


    return self

def transform(self, X):
    """
    Description
    -----------        
    Selects all the principle components up to the threshold variance.


    Args
    ----
    X: DataFrame, (examples, features)
        Pandas DataFrame containing training example features


    Returns
    -------
    self: np.ndarray, (examples, indx)
        Array containing the minimum number of principle componants required by explained_variance_thresh.
    """

    all_components =  super(PCAVarThreshSelector, self).transform(X) #To the sklean limit

    return all_components[:, :self.indx]

我用我的数据测试了这个 class 并且它按预期工作,在一个带有 RobustScaler infront 的简单管道中。在这个简单的管道中,class 将适合并且 t运行 会按预期形成。

然后我将简单的管道放入另一个带有估算器的管道中,希望 .fit() 和 .score() 管道:

model_pipe = Pipeline([('ppp', Pipeline([('rs', RobustScaler()),
                                    ('pcavts', PCAVarThreshSelector(whiten = True))])),
                  ('lin_reg', LinearRegression())])

管道安装无误。但是,当我尝试对其进行评分时,我得到一个 AttributeError:

AttributeError                            Traceback (most recent call last)
<ipython-input-92-cf336db13fe1> in <module>()
----> 1 model_pipe.score(X_test, y_test)

~\Anaconda3\lib\site-packages\sklearn\utils\metaestimators.py in <lambda>(*args, **kwargs)
    113 
    114         # lambda, but not partial, allows help() to work with update_wrapper
--> 115         out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs)
    116         # update the docstring of the returned function
    117         update_wrapper(out, self.fn)

~\Anaconda3\lib\site-packages\sklearn\pipeline.py in score(self, X, y, sample_weight)
    484         for name, transform in self.steps[:-1]:
    485             if transform is not None:
--> 486                 Xt = transform.transform(Xt)
    487         score_params = {}
    488         if sample_weight is not None:

~\Anaconda3\lib\site-packages\sklearn\pipeline.py in _transform(self, X)
    424         for name, transform in self.steps:
    425             if transform is not None:
--> 426                 Xt = transform.transform(Xt)
    427         return Xt
    428 

<ipython-input-88-9153ece48646> in transform(self, X)
    114         all_components =  super(PCAVarThreshSelector, self).transform(X) #To the sklean limit
    115 
--> 116         return all_components[:, :self.indx]
    117 

AttributeError: 'PCAVarThreshSelector' object has no attribute 'indx'

我最初认为这与我在 class 中调用 super() 的方式有关。根据 this 博客 post,我认为当管道被 .score()-ed 时,class 正在重新启动,因此 fit 方法中创建的属性不再得分时存在。 我尝试了其他几种调用父方法 class 的方法,包括:super().method、PCA.method(),以及博客 post 中建议的方法,但是都给出相同的错误。

我想也许博客的解决方案是针对Python 2的,而我的代码在Python 3.

然而,当尝试以最小可重现的方式重现此问题时,我不再遇到错误。

from sklearn.datasets import make_regression
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline

X, y = make_regression() #Just some dummy regression data for demonstrative purposes.

class BaseTransformer(TransformerMixin, BaseEstimator):

    def __init__(self):
        print("Base Init")

    def fit(self, X, y = None):
        return self

    def transform(self, X):
        return X

class DerivedTransformer(BaseTransformer):

    def __init__(self):
        super(DerivedTransformer, self).__init__()
        print("Dervied init")

    def fit(self, X, y = None):
        super(DerivedTransformer, self).fit(X, y)
        self.new_attribute = 0.0001
        return self

    def transform(self, X):
        output = super(DerivedTransformer, self).transform(X)
        output += self.new_attribute

        return output

base_pipeline = Pipeline([('base_transformer', BaseTransformer()),
              ('linear_regressor', LinearRegression())])

derived_pipeline = Pipeline([('derived_transformer', DerivedTransformer()),
              ('linear_regressor', LinearRegression())])

上面的代码运行符合预期,没有错误。我不知所措。谁能帮我解决这个错误?

那是因为您还没有覆盖(实施)fit_transform() 方法。

只需将以下部分添加到您的 PCAVarThreshSelector 即可解决问题:

def fit_transform(self, X, y=None):
    return self.fit(X, y).transform(X)

原因:流水线将尝试在所有步骤(不包括最后一个步骤)上首先调用fit_transform()方法。

这个 fit_transform() 方法只是一个 shorthand 用于调用 fit() 然后 transform() 并且定义如我上面定义的那样。

但在某些情况下,如 PCA,或 scikit-learn 中的 CountVectorizer 等,此方法的实现方式不同以使处理速度更快,因为:

  • 与在 fit() 中检查数据然后在 transform()
  • 中再次检查相比,将数据检查/验证(和转换)为适当的形式仅需完成一次
  • 其他一些重复性工作可以轻松简化

由于您从 PCA 继承,当您调用 model_pipe.fit() 时,它使用来自 PCA 的 fit_transform(),因此永远不会转到您定义的 fit() 方法(因此您的 class 对象从不包含任何 indx 属性。

但是当您调用 score() 时,只有 transform() 在管道的所有中间步骤上被调用并转到您实现的 transform()。因此错误。

如果您在 BaseTransformer 中以稍微不同的方式实现 fit_transform(),则您关于 BaseTransformer 和 DerivedTransformer 的示例可以重现。