Reputation: 272
I am trying to create a sklearn pipeline which will first extract the average word length in a text, and then standardize it using StandardScaler
.
custom transformer
class AverageWordLengthExtractor(BaseEstimator, TransformerMixin):
def __init__(self):
pass
def average_word_length(self, text):
return np.mean([len(word) for word in text.split( )])
def fit(self, x, y=None):
return self
def transform(self, x , y=None):
return pd.DataFrame(pd.Series(x).apply(self.average_word_length))
My goal is to achieve this. X is a pandas series with text values. This works.
extractor=AverageWordLengthExtractor()
print(extractor.transform(X[:10]))
sc=StandardScaler()
print(sc.fit_transform(extractor.transform(X[:10])))
The pipeline I created for this is.
pipeline = Pipeline([('text_length', AverageWordLengthExtractor(), 'scale', StandardScaler())])
But the pipeline.fit_transform()
producing below error.
Traceback (most recent call last):
File "custom_transformer.py", line 48, in <module>
main()
File "custom_transformer.py", line 43, in main
'scale', StandardScaler())])
File "/opt/conda/lib/python3.6/site-packages/sklearn/pipeline.py", line 114, in __init__
self._validate_steps()
File "/opt/conda/lib/python3.6/site-packages/sklearn/pipeline.py", line 146, in _validate_steps
names, estimators = zip(*self.steps)
ValueError: too many values to unpack (expected 2)
Upvotes: 3
Views: 6201
Reputation: 3632
Your brackets are in the wrong place / you are missing brackets when creating the Pipeline, should be a list of tuples:
pipeline = Pipeline([
('text_length', AverageWordLengthExtractor()),
('scale', StandardScaler())
])
Upvotes: 6
Reputation: 2007
I think you need add fit_transform
method to your class AverageWordLengthExtractor
.
Upvotes: 1