首页 文章

超级__str__没有被调用

提问于
浏览
0

我正在继承 from sklearn.ensemble import RandomForestClassifier ,我正在尝试打印我的新估算器:

class my_rf(RandomForestClassifier):
    def __str__(self):
        return "foo_" + RandomForestClassifier.__str__(self)

foo_my_rf()

我也尝试过:

class my_rf(RandomForestClassifier):
    def __str__(self):
        return "foo_" + super(RandomForestClassifier, self).__str__()

结果相同 . 期望是非常像sklearn默认行为:

>>> a = RandomForestClassifier()
>>> print a
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
        max_depth=None, max_features='auto', max_leaf_nodes=None,
        min_samples_leaf=1, min_samples_split=2,
        min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
        oob_score=False, random_state=None, verbose=0,
        warm_start=False)
>>>

当我使用 print a.__str__() 时,这也是结果 .

我错过了什么?谢谢 .

How do I change the string representation of a Python class?相关

1 回答

  • 0

    RandomForestClassifier 中, __repr____str__ 都查找从中调用它们的实例的类的名称( self ) . 您应该直接引用超类的名称 .

    Update 这就是你如何得到你想要的输出,虽然我没有得到,为什么你想要这样的东西 . RandomForestClassifier__str____repr__ 返回类的实际名称是有原因的 . 这样你就可以 eval 来恢复对象 . 无论如何,

    In [1]: from sklearn.ensemble import RandomForestClassifier
    In [2]: class my_rf(RandomForestClassifier):
        def __str__(self):
            superclass_name = RandomForestClassifier.__name__
            return "foo_" + superclass_name + "(" + RandomForestClassifier.__str__(self).split("(", 1)[1]
    
    In [3]: forest = my_rf()
    In [4]: print forest
    foo_RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=None,
       max_features='auto', max_leaf_nodes=None, min_samples_leaf=1,
       min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=10,
       n_jobs=1, oob_score=False, random_state=None, verbose=0,
       warm_start=False)
    

    Update 2 覆盖 __init__ 时没有参数,因为在超类 __str____repr__ 中实现了扫描传递给 __init__ 的参数列表 . 您可以通过运行此代码清楚地看到它:

    In [5]: class my_rf(RandomForestClassifier):
        def __init__(self, *args, **kwargs):
            RandomForestClassifier.__init__(self, *args, **kwargs)
        def __str__(self):
            superclass_name = RandomForestClassifier.__name__
            return "foo_" + superclass_name + "(" + RandomForestClassifier.__str__(self).split("(", 1)[1]
    In [6]: forest = my_rf()
    In [7]: print forest
    ...
    RuntimeError: scikit-learn estimators should always specify their parameters in the signature of their __init__ (no varargs). <class '__main__.my_rf'> with constructor (<self>, *args, **kwargs) doesn't  follow this convention.
    

相关问题