重塑 pandas.Df 以在 GridSearch 中使用

Reshape pandas.Df to use in GridSearch

我正在尝试将 GridSearch 中的多个特征列与管道一起使用。因此,我传递了两列,我想为其执行 TfidfVectorizer,但是当 运行 GridSearch.

时我遇到了麻烦
Xs = training_data.loc[:,['text','path_contents']]
y = training_data['class_recoded'].astype('int32')

for col in Xs:
    print Xs[col].shape

print Xs.shape
print y.shape

# (2464L,)
# (2464L,)
# (2464, 2)
# (2464L,)

from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import GridSearchCV

pipeline = Pipeline([('vectorizer', TfidfVectorizer(encoding="cp1252", stop_words="english")), 
                     ('nb', MultinomialNB())])

parameters = {
    'vectorizer__max_df': (0.48, 0.5, 0.52,),
    'vectorizer__max_features': (None, 8500, 9000, 9500),
    'vectorizer__ngram_range': ((1, 3), (1, 4), (1, 5)),
    'vectorizer__use_idf': (False, True)
}

if __name__ == "__main__":
    grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=2)
    grid_search.fit(Xs, y) # <- error thrown here

    print("Best score: {0}".format(grid_search.best_score_))  
    print("Best parameters set:")  
    best_parameters = grid_search.best_estimator_.get_params()  
    for param_name in sorted(list(parameters.keys())):  
        print("\t{0}: {1}".format(param_name, best_parameters[param_name]))

错误:ValueError:发现样本数量不一致的输入变量:[2, 1642]

我读到一个类似的错误 and ,我尝试了两个问题的建议但无济于事。

我尝试以不同的方式选择我的数据:

features = ['text', 'path_contents']
Xs = training_data[features]

我尝试使用 .values 而不是建议 here,像这样:

grid_search.fit(Xs.values, y.values) 

但这给了我以下错误:

AttributeError: 'numpy.ndarray' object has no attribute 'lower'

所以这是怎么回事?我不确定如何继续。

TfidfVectorizer 需要输入一个字符串列表。这解释了 "AttributeError: 'numpy.ndarray' object has no attribute 'lower'" 因为您输入的是二维数组,这意味着数组列表。

所以你有 2 个选择,要么预先将 2 列连接成 1 列(pandas),要么如果你想保留 2 列,你可以在管道中使用特征联合(http://scikit-learn.org/stable/modules/pipeline.html#feature-union )

关于第一个异常,我猜是pandas和sklearn通信引起的。但是,由于代码中存在上述错误,您无法确定。