在随机森林中传递 Class_weight 参数时出错

Getting error while passing Class_weight parameter in Random Forest

我正在做二进制 classifier。由于我的数据不平衡,我使用 class 重量。我在传递值时遇到错误如何解决这个问题。

错误:ValueError:class_weight must be dict, 'balanced', or None, got: [{0: 0.4, 1: 0.6}]”

代码

rf=RandomForestClassifier(n_estimators=1000,oob_score=True,min_samples_leaf=500,class_weight=[{0:.4, 1:.6}])
    fit_rf=rf.fit(X_train_res,y_train_res)

错误

\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\class_weight.py in compute_class_weight(class_weight, classes, y)
     60         if not isinstance(class_weight, dict):
     61             raise ValueError("class_weight must be dict, 'balanced', or None,"
---> 62                              " got: %r" % class_weight)
     63         for c in class_weight:
     64             i = np.searchsorted(classes, c)

ValueError: class_weight must be dict, 'balanced', or None, got: [{0: 0.4, 1: 0.6}]

如何解决这个问题。

根据 documentation

class_weight : dict, list of dicts, “balanced”,

因此,class_weight 参数接受字典、字典列表或字符串 "balanced"。您收到的错误消息表明它需要一本字典,并且由于您只有一本字典,因此不需要列表。

所以,让我们试试:

rf=RandomForestClassifier(n_estimators=1000,
                          oob_score=True,
                          min_samples_leaf=500,
                          class_weight={0:.4, 1:.6})

fit_rf=rf.fit(X_train_res,y_train_res)