ome*_*rbp 3 python pipeline feature-selection scikit-learn
我(iid)数据集中的每个样本如下所示:
x = [a_1,a_2 ... a_N,b_1,b_2 ... b_M]
我也有每个样本的标签(这是监督学习)
的一个特点是非常稀疏的(即袋的字表示),而b特征是致密的(整数,还有那些的〜45)
我正在使用scikit-learn,我想将GridSearchCV与管道一起使用.
问题:是否可以在功能类型a上使用一个CountVectorizer,在功能类型b上使用另一个CountVectorizer ?
我想要的可以被认为是:
pipeline = Pipeline([
('vect1', CountVectorizer()), #will work only on features [0,(N-1)]
('vect2', CountVectorizer()), #will work only on features [N,(N+M-1)]
('clf', SGDClassifier()), #will use all features to classify
])
parameters = {
'vect1__max_df': (0.5, 0.75, 1.0), # type a features only
'vect1__ngram_range': ((1, 1), (1, 2)), # type a features only
'vect2__max_df': (0.5, 0.75, 1.0), # type b features only
'vect2__ngram_range': ((1, 1), (1, 2)), # type b features only
'clf__alpha': (0.00001, 0.000001),
'clf__penalty': ('l2', 'elasticnet'),
'clf__n_iter': (10, 50, 80),
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)
grid_search.fit(X, y)
Run Code Online (Sandbox Code Playgroud)
那可能吗?
@Andreas Mueller提出了一个好主意.但是,我想保留原始的非选择功能...因此,我无法预先告知管道中每个阶段的列索引(在管道开始之前).
例如,如果我设置CountVectorizer(max_df=0.75),它可能会减少一些术语,原始列索引将更改.
谢谢
不幸的是,目前这还不是很好.您需要使用FeatureUnion连接到各种功能,并且每个功能中的变换器都需要选择功能并对其进行转换.一种方法是创建一个变换器的管道,选择列(您需要自己编写)和CountVectorizer.有一个例子在这里做类似的事情.该示例实际上将要素分离为字典中的不同值,但您不需要这样做.另请参阅选择包含所需变换器代码的列的相关问题.
使用当前代码看起来像这样:
make_pipeline(
make_union(
make_pipeline(FeatureSelector(some_columns), CountVectorizer()),
make_pipeline(FeatureSelector(other_columns), CountVectorizer())),
SGDClassifier())
Run Code Online (Sandbox Code Playgroud)