sklearn,python中的网格搜索技术

时间:2017-04-13 16:18:19

标签: python machine-learning scikit-learn cross-validation grid-search

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

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

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))的得分相同? 谢谢

1 个答案:

答案 0 :(得分:1)

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

因此,为了达到相同的分数,请使用下面指定的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&#39 ;:通过统计总数来全局计算指标   积极,假阴性和误报。