继承 python

inheritance with the extention in python

遵循开放式原则,我想通过继承为 sklearn 创建我的 LinearRegression。 我尝试创建具有与 LinearRegression 相同功能的 MyRegression,但添加了一个函数

你能帮忙吗,为什么它不起作用?

    from sklearn.linear_model import LinearRegression

class MyRegression(LinearRegression):
    def __init__(self):
        super(LinearRegression, self).__init__()
        
    def modified_fit(self, x, y):
        return self.fit(x, y)


x = [
    (1,2),
    (2,3)
]
y = [1,2]

regression = MyRegression()
regression.modified_fit(x, y)

我遇到了一个错误,但据我所知,原始 LinearRegression 的所有参数和方法都必须在 init() 过程

期间从父项中获取
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-7d9a5c74a33f> in <module>
     16 
     17 regression = MyRegression()
---> 18 regression.modified_fit(x, y)

<ipython-input-29-7d9a5c74a33f> in modified_fit(self, x, y)
      6 
      7     def modified_fit(self, x, y):
----> 8         return self.fit(x, y)
      9 
     10 

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in fit(self, X, y, sample_weight)
    478         """
    479 
--> 480         n_jobs_ = self.n_jobs
    481         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
    482                          y_numeric=True, multi_output=True)

AttributeError: 'MyRegression' object has no attribute 'n_jobs'

我用 PyCharm 覆盖了这个方法,结果是这样的……而且工作正常。

from sklearn.linear_model import LinearRegression
class MyRegression(LinearRegression):
    def __init__(self, *, fit_intercept=True, normalize=False, copy_X=True, n_jobs=None):
        super().__init__(fit_intercept=fit_intercept, normalize=normalize, copy_X=copy_X, n_jobs=n_jobs)

    def modified_fit(self, x, y):
        return self.fit(x, y)


x = [(1, 2),(2, 3)]
y = [1, 2]

regression = MyRegression()
regression.modified_fit(x, y)

另一个可行的选项是:

from sklearn.linear_model import LinearRegression
class MyRegression(LinearRegression):
    def __init__(self):
        super().__init__()

在 python

中查看关于覆盖构造函数的 answer