Sklearn GridSearchCV,class_weight 不明原因不工作:(

Sklearn GridSearchCV, class_weight not working for unknown reason :(

正在努力class_weight。我知道其余代码有效,只是 class_weight 给我错误:

    parameters_to_tune = ['min_samples_split':[2,4,6,10,15,25], 'min_samples_leaf':[1,2,4,10],'max_depth':[None,4,10,15],
                                             ^
SyntaxError: invalid syntax

这是我的代码

clf1 = tree.DecisionTreeClassifier()
 parameters_to_tune = ['min_samples_split':[2,4,6,10,15,25], 'min_samples_leaf':[1,2,4,10],'max_depth':[None,4,10,15],
 'splitter' : ('best','random'),'max_features':[None,2,4,6,8,10,12,14],'class_weight':{1:10}]
clf=grid_search.GridSearchCV(clf1,parameters_to_tune)
clf.fit(features,labels)
print clf.best_params_

有人发现我犯的错误吗?

我假设您想在不同的 class_weight 上对 'salary' class.

进行网格搜索

class_weight 的值应该是一个列表:

'class_weight':[{'salary':1}, {'salary':2}, {'salary':4}, {'salary':6}, {'salary':10}]

你可以用列表理解来简化它:

'class_weight':[{'salary': w} for w in [1, 2, 4, 6, 10]]

第一个问题是dict parameters_to_tune 中的参数值应该是一个列表,而你传递的是一个dict。它可以通过传递字典列表作为 class_weight 的值来修复,每个字典包含一组 class_weight for DecisionTreeClassifier.

但更严重的问题是class_weight是与classes关联的权重,但在你的情况下,'salary'是特征 的名称。您不能为特征分配权重。起初我误解了你的意图,但现在我对你想要的东西感到困惑。

class_weight的形式是{class_label: weight},如果你真的想在你的情况下设置class_weightclass_label应该是0.0、1.0等值,语法如下:

'class_weight':[{0: w} for w in [1, 2, 4, 6, 10]]

如果 class 的权重很大,classifier 更有可能预测数据在 class 中。使用 class_weight 的一种典型情况是数据不平衡时。

这里是一个example,尽管classifier是SVM。

更新:

完整的 parameters_to_tune 应该是这样的:

parameters_to_tune = {'min_samples_split': [2, 4, 6, 10, 15, 25],
                      'min_samples_leaf': [1, 2, 4, 10],
                      'max_depth': [None, 4, 10, 15],
                      'splitter' : ('best', 'random'),
                      'max_features':[None, 2, 4, 6, 8, 10, 12, 14],
                      'class_weight':[{0: w} for w in [1, 2, 4, 6, 10]]}
下面

Link是关于不同class_weight值的用法。只需 Ctrl+F "class_weight" 到相关部分。它使用 GridSearchCV 为不同的优化目标找到最佳 class_weight。

Optimizing a classifier using different evaluation metrics