sklearn 中的网格搜索技术,python

Gridsearch technique in sklearn, python

我正在研究一种受监督的机器学习算法,它似乎有一种奇怪的行为。 那么,让我开始吧:

我有一个函数可以传递不同的分类器、它们的参数、训练数据和它们的标签:

def HT(targets,train_new, algorithm, parameters):
#creating my scorer
scorer=make_scorer(f1_score)
#creating the grid search object with the parameters of the function
grid_search = GridSearchCV(algorithm, 
param_grid=parameters,scoring=scorer,   cv=5)
# fit the grid_search object to the data
grid_search.fit(train_new, targets.ravel())
# print the name of the classifier, the best score and best parameters
print algorithm.__class__.__name__
print('Best score: {}'.format(grid_search.best_score_))
print('Best parameters: {}'.format(grid_search.best_params_))
# assign the best estimator to the pipeline variable
pipeline=grid_search.best_estimator_
# predict the results for the training set
results=pipeline.predict(train_new).astype(int)
print results    
return pipeline

我向这个函数传递了如下参数:

clf_param.append( {'C' : np.array([0.001,0.01,0.1,1,10]), 
'kernel':(['linear','rbf']),
'decision_function_shape' : (['ovr'])})

好的,事情开始变得奇怪了。此函数返回 f1_score 但它与我使用以下公式手动计算的分数不同: F1 = 2 *(精度 * 召回率)/(精度 + 召回率)

有相当大的差异(0.68 与 0.89 相比)

我在函数中做错了什么? grid_search (grid_search.best_score_) 计算的分数应该与整个训练集的分数相同 (grid_search.best_estimator_.predict(train_new)) ? 谢谢

您手动计算的分数考虑了所有 classes 的全局真阳性和阴性。但在 scikit 中,f1_score,默认方法是计算二进制平均值(即仅针对正 class)。

因此,为了获得相同的分数,请使用下面指定的 f1_score:

scorer=make_scorer(f1_score, average='micro')

或者简单地说,在 gridSearchCV 中,使用:

scoring = 'f1_micro'

有关如何计算平均分数的更多信息,请参见: - http://scikit-learn.org/stable/modules/model_evaluation.html#common-cases-predefined-values

您可能还想看看下面的答案,它详细描述了 scikit 中分数的计算:-

编辑: 宏观变微观。如文档中所写:

'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.