Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scikit-learn AttributeError in custom transformer

I'm trying to create a transformer that changes types of columns from "object" to "category", so I created custom class for that:

from sklearn.base import BaseEstimator, TransformerMixin

class ChangeToCategory(BaseEstimator, TransformerMixin):
    def __init__(self, to_categories = None):
        self.to_categories_ = to_categories
    def fit(self, X, y=None):
        return self
    def transform(self, X, y=None):
        X_ = X.copy()
        for cat in self.to_categories_:
            X_[cat] = X_[cat].astype("category")
        return X_ 

But I'm getting error when I try to create object of this class:

ChangeToCategory(to_categories=["Sex", "Embarked"])
AttributeError: 'ChangeToCategory' object has no attribute 'to_categories'

What am I doing wrong? Based on error, I assume that it somewhere try to call attribute "to_categories", but I use attribute "to_categories_" - with underscore, and without is variable from init, which I don't call anywhere.

like image 791
Igor Agafonov Avatar asked Aug 01 '26 00:08

Igor Agafonov


1 Answers

So, I found there I was wrong. From sklearn documentation you must initialize all estimator parameters as attributes of the class.

In addition, every keyword argument accepted by init should correspond to an attribute on the instance. Scikit-learn relies on this to find the relevant attributes to set on an estimator when doing model selection.

like image 70
Igor Agafonov Avatar answered Aug 02 '26 14:08

Igor Agafonov