0
$\begingroup$

I defined a class like below:

from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler

class CustomScaler(BaseEstimator, TransformerMixin):
    
    def __init__(self, columns, copy=True, with_mean=True, with_std=True):
        self.scaler = StandardScaler(copy, with_mean, with_std)
        self.columns = columns
        self.mean_ = None
        self.var_ = None
        
    def fit(self, X, y = None):
        self.scaler.fit(X[self.columns], y)
        self.mean_ = np.mean(X[self.columns])
        self.var_ = np.var(X[self.columns])
        return self
    
    def transform(self, X, y=None, copy=None):
        init_col_order = X.columns
        X_scaled = pd.DataFrame(self.scaler.transform(X[self.columns]), columns=self.columns)
        X_not_scaled = X.loc[:, ~X.columns.isin(self.columns)]
        return pd.concat([X_not_scaled, X_scaled], axis = 1)[init_col_order]

When I try to create an instance from it:

columns_to_scale = ['col_A', 'col_B']
scaler = CustomScaler(columns_to_scale)

I got this error:

init() takes 1 positional argument but 4 were given

What's the problem? And how to solve it?

Environment:

  • Python: 3.9.1
  • Scikit-learn: 1.0.2
$\endgroup$

1 Answer 1

0
$\begingroup$

As the error mentions, you are passing multiple positional arguments whereas the __init__ method of StandardScaler only takes in one. The arguments you are trying to pass to the scaler should instead be passed as keywords arguments:

self.scaler = StandardScaler(copy=copy, with_mean=with_mean, with_std=with_std)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.