0

Following the open-ended principle i want to create my LinearRegression by inheritance for sklearn one. I try to create MyRegression with the same functionality as LinearRegression but add one function

Could you help, why it's not working?

    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)

I've got an error, but as I understand all parametrs and methods of original LinearRegression had to be ingereted from parent during init() process

---------------------------------------------------------------------------
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'

1 Answers1

0

I used PyCharm to override the method, this is the result ... and it is working just fine.

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)

Another option which works is:

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

see this answer about override constructor in python

Avihay Tsayeg
  • 444
  • 4
  • 10