【发布时间】:2017-12-03 22:23:15
【问题描述】:
我想扩展 scikit-learn 的 ClassificationCriterion 类,该类在内部模块 sklearn.tree._criterion 中定义为 Cython 类。我想在 Python 中执行此操作,因为通常我无法访问 sklearn 的 pyx/pxd 文件(所以我不能 cimport 他们)。但是,当我尝试扩展 ClassificationCriterion 时,我收到错误 TypeError: __cinit__() takes exactly 2 positional arguments (0 given)。下面的 MWE 重现了错误,并显示错误发生在__new__ 之后但在__init__ 之前。
有没有办法像这样扩展 Cython 类?
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._criterion import ClassificationCriterion
class MaxChildPrecision(ClassificationCriterion):
def __new__(self, *args, **kwargs):
print('new')
super().__new__(MaxChildPrecision, *args, **kwargs)
def __init__(self, *args, **kwargs):
print('init')
super(MaxChildPrecision).__init__(*args, **kwargs)
clf = DecisionTreeClassifier(criterion=MaxChildPrecision())
【问题讨论】:
-
方法需要将 self 作为第一个位置参数。但是他们不应该在 super 调用中传递它,这就是为什么有必要在
*args之外捕获它。 -
@DanielRoseman 谢谢,我更新了代码,但仍然出现同样的错误。
-
@user2357112 也感谢您。我更新了代码,但这还没有解决问题。还有其他想法吗?
-
您需要定义
__new__并传递超类__new__它期望的参数。与传递超类__init__所需的参数相同 (although those arguments might not be the ones you expect it to expect)。
标签: python scikit-learn runtime-error subclass cython