gpt4 book ai didi

python - sklearn 包装估计器会导致 get_params 丢失 self 错误

转载 作者:行者123 更新时间:2023-11-30 23:02:32 25 4
gpt4 key购买 nike

我试图继承 BaseEstimatorMetaEstimatorMixin 来为 base_estimator 创建包装,但我遇到了问题。我试图遵循存储库中的 base_ensemble 代码,但没有帮助。在运行下面调用 check_estimator(Wrapper) 的测试时,我收到 TypeError: get_params() Missing 1 requiredpositional argument: 'self' 。根据文档,如果我继承自 BaseEstimator,则不必实现 get_params。看起来有些东西是一个类而不是一个实例,但我无法确定它。

from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin, MetaEstimatorMixin, clone
from functools import lru_cache
import numpy as np
from sklearn.linear_model import LogisticRegression

'''
this is a module containing classes which wraps a classifier or a regressor sklearn estimator
'''


class Wrapper(BaseEstimator, MetaEstimatorMixin):
def __init__(self, base_estimator=LogisticRegression, estimator_params=None):
super().__init__()
self.base_estimator = base_estimator
self.estimator_params = estimator_params

def fit(self, x, y):
self.model = self._make_estimator().fit(x,y)

def _make_estimator(self):
"""Make and configure a copy of the `base_estimator_` attribute.
Warning: This method should be used to properly instantiate new
sub-estimators. taken from sklearn github
"""
estimator = self.base_estimator()
estimator.set_params(**dict((p, getattr(self, p))
for p in self.estimator_params))

return estimator

def predict(self, x):
self.model.predict(x)


import unittest
from sklearn.utils.estimator_checks import check_estimator
class Test(unittest.TestCase):
def test_check_estimator(self):
check_estimator(Wrapper)

最佳答案

base_estimator 字段必须使用对象初始化,而不是类。

....
def __init__(self, base_estimator=LogisticRegression(), ...
....

发生错误是因为某些测试中使用了clone(safe=False)。

safe: boolean, optional
If safe is false, clone will fall back to a deepcopy on objects
that are not estimators.

关于python - sklearn 包装估计器会导致 get_params 丢失 self 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34442455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com