【问题标题】:Scikit : custom estimator : cannot cloneScikit:自定义估算器:无法克隆
【发布时间】:2020-10-07 04:45:48
【问题描述】:

我为自动清理特定数据集编写了自己的估算器。我想我正确地遵循了 scikit 规则:

from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
from pathlib import Path

class cleaning(BaseEstimator, TransformerMixin):

    def __init__(self, to_drop = [], ins_threshold=0.6, 
                 corr_threshold=0.7, attribute_filepath='attribute.xlsx'): # no *args or **kargs, provides methods get_params() and set_params()
        """
        Parameters:
        -----------
        to_drop (list) : columns to be dropped
        ins_thresholrd (float) : [0.0 - 1.0] insignificant threshold above which columns containing that proportion of NaN get dropped
        corr_threshold (float) : [0.0 - 1.0] correlation threshold above which correlated columns get dropped (first one is kept)
        attribute_filepath (str of pathlib.Path) : path to the Excel file containing attributes information

        """

        self.attribute_filepath = Path(attribute_filepath)
        self.ins_threshold = ins_threshold
        self.corr_threshold = corr_threshold

        self.to_drop = to_drop
        self.ins_col = None
        self.correlated_col = None

但我仍然收到错误

RuntimeError: Cannot clone object cleaning(attribute_filepath=PosixPath('MyFile.xlsx')), as the constructor either does not set or modifies parameter attribute_filepath

我不明白为什么self.attribute_filepath 在我的__init__ 中有明确定义?

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    虽然很晚,但我会在遇到类似问题时尝试给出答案。对我来说,你在这里设置了 self.attribute_filepath 到与默认参数不同的东西,这有点违反 scikit-learn API 约定。 确实,说到__init__的方法,引用docs

    应该没有逻辑,甚至没有输入验证,参数也不应该改变。相应的逻辑应该放在使用参数的地方,通常是合适的。以下是错误的:

    def __init__(self, param1=1, param2=2, param3=3):
        # WRONG: parameters should not be modified
        if param1 > 1:
            param2 += 1
        self.param1 = param1
        # WRONG: the object's attributes should have exactly the name of
        # the argument in the constructor
        self.param3 = param2
    

    将您的自定义转换器传递给GridSearchCV() 时会发生什么-我猜您将您的转换器传递给Pipeline 而这反过来又传递给GridSearchCV() 或者您正在做类似的事情-因此调用fit()在获得的实例上,将如下:

    1. 在您到达this point 之前,您的设置可能不会出现问题。然后:
    2. 您的转换器将被克隆(并调用 __init__ 方法);
    3. setter 将被调用;
    4. 外部克隆将失败 herethe constructor [...] modifies parameter attribute_filepath

    再次引用文档,

    由于 model_selection.GridSearchCV 使用 set_params 将参数设置应用于估计器,因此调用 set_params 与使用 init 方法设置参数具有相同的效果。

    当然,答案的某些部分依赖于一些有根据的猜测。

    这个post很好地解释了这一点。最后,我也会建议这两个类似问题的答案:herehere

    【讨论】:

      猜你喜欢
      • 2021-03-04
      • 2015-08-22
      • 2020-09-25
      • 2016-02-08
      • 2011-10-13
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多