Scikit learn 超参数优化会产生更糟糕的结果
我对随机森林分类器进行了如下训练:Scikit learn 超参数优化会产生更糟糕的结果,scikit-learn,random-forest,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
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\u pred=clf,它会给我带来更糟糕的结果
我认为这是因为scoring='accurity'
的缘故。我应该使用哪个分数来获得与我的初始随机林相同或更好的结果?在gridsearch中定义scoring='accurity'
不应对这种差异负责,因为这将是随机林分类器的默认值
这里出现意外差异的原因是,您在第一个随机林rf
中指定了class\u weight=“balanced”
,但在第二个分类器clf
中没有指定。因此,在计算准确度分数时,您的类的权重不同,这最终会导致不同的性能指标
要更正此问题,只需通过以下方式定义clf
:
clf = RandomForestClassifier(random_state = 0, n_jobs=-1, class_weight="balanced")
clf = RandomForestClassifier(random_state = 0, n_jobs=-1, class_weight="balanced")