Sklearn GridSearchCV,class_weight 不明原因不起作用:(

hmm*_*bob 2 python scikit-learn grid-search

试图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
Run Code Online (Sandbox Code Playgroud)

这是我的代码

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_
Run Code Online (Sandbox Code Playgroud)

有没有人发现我犯的错误?

yan*_*jie 6

我假设您想对不同class_weight的“薪水”类进行网格搜索。

的值class_weight应该是一个列表:

'class_weight':[{'salary':1}, {'salary':2}, {'salary':4}, {'salary':6}, {'salary':10}]
Run Code Online (Sandbox Code Playgroud)

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

'class_weight':[{'salary': w} for w in [1, 2, 4, 6, 10]]
Run Code Online (Sandbox Code Playgroud)

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

但更严重的问题是class_weight有关联的权重,但在你的情况下,“工资”是一个名称的功能。您不能为要素分配权重。一开始我误解了你的意图,但现在我对你想要的东西感到困惑。

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

'class_weight':[{0: w} for w in [1, 2, 4, 6, 10]]
Run Code Online (Sandbox Code Playgroud)

如果某个类的权重很大,则分类器更有可能预测数据属于该类。一种典型的使用情况class_weight是数据不平衡时。

这是一个示例,尽管分类器是 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]]}
Run Code Online (Sandbox Code Playgroud)