超参数优化给出更差的结果

时间:2019-12-04 16:28:10

标签: scikit-learn random-forest

我对我的随机森林分类器进行了如下训练:

rf = RandomForestClassifier(n_jobs=-1, max_depth = None, max_features = "auto", 
                            min_samples_leaf = 1, min_samples_split = 2, 
                            n_estimators = 1000, oob_score=True, class_weight="balanced", 
                            random_state=0)
​
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
​
print("Confusion matrix")
print(metrics.confusion_matrix(y_test, y_pred))
print("F1-score")
print(metrics.f1_score(y_test, y_pred, average="weighted"))
print("Accuracy")
print(metrics.accuracy_score(y_test, y_pred))
print(metrics.classification_report(y_test, y_pred))

并得到以下结果:

Confusion matrix
[[558  42   2   0   1]
 [ 67 399  84   3   2]
 [ 30 135 325  48   7]
 [  5  69  81 361  54]
 [  8  17   7  48 457]]
F1-score
0.7459670332027826
Accuracy
0.7473309608540926
              precision    recall  f1-score   support

           1       0.84      0.93      0.88       603
           2       0.60      0.72      0.66       555
           3       0.65      0.60      0.62       545
           4       0.78      0.63      0.70       570
           5       0.88      0.85      0.86       537

然后我决定执行超参数优化以改善此结果。

clf = RandomForestClassifier(random_state = 0, n_jobs=-1)
param_grid = { 
    'n_estimators': [1000,2000],
    'max_features': [0.2, 0.5, 0.7, 'auto'],
    'max_depth' : [None, 10],
    'min_samples_leaf': [1, 2, 3, 5],
    'min_samples_split': [0.1, 0.2]
}

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)
clf = GridSearchCV(estimator=clf, 
                   param_grid=param_grid, 
                   cv=k_fold,
                   scoring='accuracy',
                   verbose=True)

clf.fit(X_train, y_train)

但是,如果我y_pred = clf.best_estimator_.predict(X_test)这样做会给我带来更糟糕的结果:

Confusion matrix
[[533  68   0   0   2]
 [145 312  70   0  28]
 [ 58 129 284  35  39]
 [ 21  68  73 287 121]
 [ 32  12   3  36 454]]
F1-score
0.6574507466273805
Accuracy
0.6654804270462633
              precision    recall  f1-score   support

           1       0.68      0.88      0.77       603
           2       0.53      0.56      0.55       555
           3       0.66      0.52      0.58       545
           4       0.80      0.50      0.62       570
           5       0.70      0.85      0.77       537

我认为这是由于scoring='accuracy'而引起的。我应该使用哪个分数来获得与最初的随机森林相同或更好的结果?

1 个答案:

答案 0 :(得分:1)

在gridsearch中定义scoring='accuracy'不应造成这种差异,因为无论如何,这将是随机森林分类器的默认设置。

此处之所以有意想不到的区别,是因为您在第一个随机森林class_weight="balanced"中指定了rf,但在第二个分类器clf中却没有指定。因此,在计算准确性得分时,您的班级的权重会有所不同,最终导致不同的绩效指标。

要解决此问题,只需通过以下方式定义clf

clf = RandomForestClassifier(random_state = 0, n_jobs=-1, class_weight="balanced")