Python 3.x 如何使用估计器对文本进行分类?
我用以下方法培训了估计员:Python 3.x 如何使用估计器对文本进行分类?,python-3.x,scikit-learn,text-classification,countvectorizer,Python 3.x,Scikit Learn,Text Classification,Countvectorizer,我用以下方法培训了估计员: def train_estimator(feature_list, expected_values, k=5): pipeline = Pipeline([('vect', CountVectorizer(input='filename', stop_words='english')), ('clf', MultinomialNB())]) parameters = {'vect__ngram_ran
def train_estimator(feature_list, expected_values, k=5):
pipeline = Pipeline([('vect', CountVectorizer(input='filename', stop_words='english')),
('clf', MultinomialNB())])
parameters = {'vect__ngram_range':[(1, 1), (1, 2), (1, 3)],
'vect__min_df':[0.001, 0.01, 0.02, 0.05, 0.1],
'vect__max_df':[0.85, 0.90, 0.95, 0.99, 1.0],
'clf__alpha':[0.001, 0.01, 0.1, 0.2, 0.5, 1.0]}
gs_clf = GridSearchCV(pipeline, parameters, n_jobs=6, cv=k, verbose=1, refit=True, scoring='roc_auc')
gs_clf.fit(feature_list, expected_values)
return gs_clf.best_estimator_
现在我需要用这个估计器对一些文本进行分类,但不清楚如何正确地对文本进行矢量化
我需要对文本进行向量化,然后用向量调用estimator.predict()
。问题是,该向量必须与用于训练估计器的向量一致(单词foobar
必须与用于训练模型的向量具有相同的索引)。文档中不清楚如何以这种方式将文本
矢量化
如何编写这个predict()
函数
def predict(estimator, text):
# Vectorize text and call estimator.predict()
编辑
功能列表
和预期值
如下所示:
def fetch_training_set(doc_iterator):
files, labels = list(), list()
for row in doc_iterator:
filename = 'somepath/%s.txt' % random()
with open(filename, 'w', encoding='utf-8') as f:
f.write(row['text'])
files.append(filename)
labels.append(row['label'])
feature_list = np.array(files)
expected_values = np.array(labels)
return feature_list, expected_values
我认为添加额外的函数train\u estimator
和predict
会使事情变得复杂
gs_clf = GridSearchCV(pipeline, parameters, n_jobs=6, cv=k, verbose=1, refit=True, scoring='roc_auc')
gs_clf.fit(feature_list, expected_values)
gs_clf.predict(your_data)
我将完成这项工作(最后一行)。由于您重新安装了管道(refit=True
),因此,gs_clf
使用网格搜索找到的最佳参数重新安装。然后,gs\u clf.predict
将调用管道中每个成员的predict
函数作为管道。什么是feature\u list
?原始文本?@Vivek Kumarfeature\u list
是一个文件名列表。每个文件都包含文本。@Vivek Kumarfeature\u list
实际上是文件名的np.array()
。我用更多信息更新了问题。你的数据是什么?它是文本还是特征向量?通常是文本。但是由于CountVectorizer的输入是filename,所以我也应该尝试使用filename。