修正scikit学习估计器中的参数



我需要固定scikit学习估计器的参数值。我仍然需要能够更改估计器的所有其他参数,并在scikit学习工具(如Pipelines和GridSearchCV(中使用估计器。

我试图定义一个继承自scikit学习估计器的新类。例如,在这里,我试图创建一个新的类来修复RandomForestClassifier的n_estimators=5

class FiveTreesClassifier(RandomForestClassifier):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.n_estimators = 5

fivetrees = FiveTreesClassifier()
randomforest = RandomForestClassifier(n_estimators=5)
# This passes.
assert fivetrees.n_estimators == randomforest.n_estimators
# This fails: the params of fivetrees is an empty dict.
assert fivetrees.get_params() == randomforest.get_params()

get_params()不可靠的事实意味着我不能在Pipelines和GridSearchCV中使用新的估计器(如这里所解释的(。

我使用的是scikit learn 0.24.2,但我认为它实际上与新版本相同。

我更喜欢在固定超参数值的同时定义一个新类的答案。我也会接受使用其他技巧的答案。我也很感谢你对我为什么应该/不应该这样做的彻底解释!

您可以使用functools.partial

NewEstimator = partial(RandomForestClassifier, n_estimators=5)
new_estimator = NewEstimator()

最新更新