【发布时间】:2017-10-28 04:48:35
【问题描述】:
我正在尝试将 GridSearch 中的多个特征列与 Pipeline 一起使用。因此,我传递了两列,我想为其执行 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]
我读到了类似的错误here 和here,我尝试了这两个问题的建议,但无济于事。
我尝试以不同的方式选择我的数据:
features = ['text', 'path_contents']
Xs = training_data[features]
我尝试使用.values 来代替建议的here,如下所示:
grid_search.fit(Xs.values, y.values)
但这给了我以下错误:
AttributeError: 'numpy.ndarray' 对象没有属性 'lower'
那么发生了什么?我不确定如何继续。
【问题讨论】:
-
TfidfVectorizer.fit()需要一个元素为字符串的可迭代对象,但Xs包含两列,所以Xs的每个元素都是一个数组对象,当TfidfVectorizer调用lower()Xs中的项目方法,它引发 AttributeError: 'numpy.ndarray' 对象没有属性 'lower'。所以问题是为什么你将两列传递给TfidfVectorizer。 -
正如我在对您的 previous question 的回答中所建议的那样,在管道内的 TfidfVectorizer 中使用多个列并不是那么简单。
标签: python numpy machine-learning scikit-learn grid-search