在 sklear 风格的类中指定自定义参数

问题描述 投票:0回答:1

我正在尝试用 Python 实现我自己的、与 sklearn 兼容的分类器。为此,我继承了

BaseEstimator
ClassifierMixin
,但我还在构造函数中定义了自己的参数。

在调试时,我注意到在 IPython 控制台中交互调用

__repr__()
会产生一个
AttributeError
,声称我的分类器缺少我指定的属性。当我将文件作为程序运行时,不会出现此类错误。另外,该错误仅出现在我的 Mac 上的 Spyder 中,但不会出现在 Windows 上的 PyCharm 中。

这是我的最小可重现示例:

from sklearn.base import BaseEstimator, ClassifierMixin


class MyClassifier(BaseEstimator, ClassifierMixin):
  def __repr__(self, **kwargs):
    return "In MyClassifier.__repr__() ..."

  def __init__(self, my_arg=0):
    pass


mc = MyClassifier()
# The following line produces
#     AttributeError: 'MyClassifier' object has no attribute 'my_arg'
# but only when run interactively:
mc

我还注意到,如果我不继承自

BaseEstimator
,则不会出现该错误。另外,如果我将
my_arg
分配给同名的成员变量,则不会出现该错误:在
__init__()
中,用
self.my_arg = my_arg
替换
pass
self.my_differently_named_arg = my_arg
,另一方面,没有帮助。

那么,是否存在一些隐含的约定,即成员变量必须与形式参数具有相同的名称,或者它是 Spyder 中的一个怪癖,还是在 Mac 上的 Python 实现中、在 sklearn 中、在 PyCharm 中、在 Windows 上的 Python 实现中,还是我做错了什么?

我的配置是:Spyder 是 5.5.2、Python 3.9.7、IPython 8.18.1、sklearn 1.3.2,我的 Mac 是 Intel Core i7 和 Sonoma 14.4.1。

python inheritance scikit-learn spyder
1个回答
0
投票

文档中所述:

In addition, every keyword argument accepted by __init__ should correspond to an attribute on the instance. Scikit-learn relies on this to find the relevant attributes to set on an estimator when doing model selection.

P.S:查看文档或您在互联网上找到的任何其他资源,在开发自定义分类器后,您应该了解一些其他约定。例如:

__init__
中不应该有任何逻辑,甚至不能进行输入验证。

© www.soinside.com 2019 - 2024. All rights reserved.