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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With