Python OneVsRestClassifier在管道中的自定义评分功能
我正在尝试为OneVsRestClassifier创建我自己的评分函数,我面临一些问题Python OneVsRestClassifier在管道中的自定义评分功能,python,machine-learning,scikit-learn,multiclass-classification,gridsearchcv,Python,Machine Learning,Scikit Learn,Multiclass Classification,Gridsearchcv,我正在尝试为OneVsRestClassifier创建我自己的评分函数,我面临一些问题 pipeline = Pipeline([ ('tfidf', TfidfVectorizer()), ('clf', OneVsRestClassifier(MultinomialNB(fit_prior=True, class_prior=None))) ]) parameters = {
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('clf', OneVsRestClassifier(MultinomialNB(fit_prior=True, class_prior=None)))
])
parameters = {
'tfidf__max_df': (0.25, 0.5, 0.75),
'tfidf__ngram_range': [(1, 1), (1, 2), (1, 3)],
'clf__estimator__alpha': (1e-2, 1e-3)
}
grid_search_cv = GridSearchCV(pipeline, parameters, cv=2, n_jobs=3, verbose=10, scoring=overall_f1_score_cv)
grid_search_cv.fit(train_X, train_y)
这里,train_X和train_y是数据帧,train_X只有一列(包含文本数据),train_y有27个二进制列(27个不同的类)
我的评分函数定义如下。我注意到预测的输出是np数组
def overall_f1_score(y_actual, y_predict):
num_genres = y_actual.shape[1]
tp, fp, fn = 0, 0, 0
for idx in range(num_genres):
tp+=((y_actual[:,idx]==1) & (y_predict[:,idx]==1)).sum()
fp+=((y_actual[:,idx]==0) & (y_predict[:,idx]==1)).sum()
fn+=((y_actual[:,idx]==1) & (y_predict[:,idx]==0)).sum()
precision = tp/(tp+fp)
recall = tp/(tp+fn)
f1_score = 2*precision*recall/(precision+recall)
return f1_score
overall_f1_score_cv = make_scorer(overall_f1_score, greater_is_better=True)
使用上述评分功能,我的GridSearchCV拟合似乎卡住了。没有我额外的计分理由,它工作得很好。任何人都可以帮助我使用正确的格式来为这个场景使用定制的评分功能吗 没有真实的数据来重现这一点,很难说。但是,在scikit中进行多类分类时,切勿对
y
使用二维二进制数组。它用作标签指示器矩阵并启用多标签分类。在OneVsRestClassifier
中,启动二进制关联方法,该方法可能会选择两个或多个类(标签)作为输出,您可能不希望这样做。对于多类,始终使用单个维度y
(将所有可能的类放入该单个数组中)。例如:[1,2,1,3,2,4,5,1,3,4]
或['cat','dog','horse','dog','horse','dog','cat']
等感谢您的回复,Vivek。对……这是一个多标签分类。因此,我有一个2d二进制数组…多个列(输出)的多个观测值都有1。如果没有实际数据来重现,很难说。但是,在scikit中进行多类分类时,切勿对y
使用二维二进制数组。它用作标签指示器矩阵并启用多标签分类。在OneVsRestClassifier
中,启动二进制关联方法,该方法可能会选择两个或多个类(标签)作为输出,您可能不希望这样做。对于多类,始终使用单个维度y
(将所有可能的类放入该单个数组中)。例如:[1,2,1,3,2,4,5,1,3,4]
或['cat','dog','horse','dog','horse','dog','cat']
等感谢您的回复,Vivek。对……这是一个多标签分类。因此,我有一个2d二进制数组…多个列(输出)有1个用于多个观察值。