您可以使用以下链接中的示例中的“ItemSelector”为数据中的每一列使用不同的处理方法,然后使用 sklearn 的 FeatureUnion 将所有内容重新组合在一起。
我认为您的意思是您想像处理分类数据一样处理价格?我会说将数字转换为字符串,然后使用 CountVectorizer 并将二进制标志设置为 True。
这是一个非常有用的例子:
http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html#sphx-glr-auto-examples-hetero-feature-union-py
编辑:另外,计数矢量化器会去掉我认为的句点,所以最好在没有这样的标记器的情况下调用它。可能有一个更优雅的解决方案,行数更少,但这也有效。
def no_tokenizer(t):
return [t]
CountVectorizer(binary=False, tokenizer=no_tokenizer)
编辑:这是一个带有 ItemSelector 的管道示例。我为 pandas 数据框设置了我的设置,我通过传递关键字传递是否要取回文本、数字数据。
class ItemSelector(BaseEstimator, TransformerMixin):
def __init__(self, key, dt):
self.key = key
self.dt = dt
def fit(self, x, y=None):
# does nothing
return self
def transform(self, data_dict):
# this returns the column requested
print "Selecting",self.key
if self.dt == 'text':
return data_dict.loc[:,self.key]
elif self.dt == 'num2text':
return data_dict.loc[:,self.key].astype(unicode)
elif self.dt == 'date':
return (data_dict.loc[:,self.key].squeeze() - pd.Timestamp(1900,1,1)).dt.days.to_frame()
else:
return data_dict.loc[:,[self.key]].astype(float)
def preproc_pipeline():
return FeatureUnion(
transformer_list=[
('artist_name', Pipeline([
('selector', ItemSelector(key='artist_name', dt='text')),
('cv', CountVectorizer(binary=False),
])),
('composer', Pipeline([
('selector', ItemSelector(key='composer', dt='text')),
('cv', CountVectorizer(binary=False),
])),
('song_length', Pipeline([
('selector', ItemSelector(key='song_length', dt='num')),
])),
])