gpt4 book ai didi

machine-learning - `sklearn.model_selection.RandomizedSearchCV` 是如何工作的?

转载 作者:行者123 更新时间:2023-11-30 09:13:58 25 4
gpt4 key购买 nike

我正在制作一个具有不平衡类(比例为 1:10)的二元分类器。我尝试了 KNN、RF 和 XGB 分类器。我从 XGB 分类器中获得了最佳的精确召回权衡和 F1 分数(可能是因为数据集的大小非常小 - (1900,19))

因此,在检查了 XGB 的错误图之后,我决定使用 sklearn 中的 RandomizedSearchCV() 来调整我的 XGB 分类器的参数。基于 stackexchange 上的另一个答案,这是我的代码:

from xgboost import XGBClassifier
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
score_arr = []
clf_xgb = XGBClassifier(objective = 'binary:logistic')
param_dist = {'n_estimators': [50, 120, 180, 240, 400],
'learning_rate': [0.01, 0.03, 0.05],
'subsample': [0.5, 0.7],
'max_depth': [3, 4, 5],
'min_child_weight': [1, 2, 3],
'scale_pos_weight' : [9]
}
clf = RandomizedSearchCV(clf_xgb, param_distributions = param_dist, n_iter = 25, scoring = 'precision', error_score = 0, verbose = 3, n_jobs = -1)
print(clf)
numFolds = 6
folds = StratifiedKFold(n_splits = numFolds, shuffle = True)

estimators = []
results = np.zeros(len(X))
score = 0.0
for train_index, test_index in folds.split(X_train, y_train):
print(train_index)
print(test_index)
_X_train, _X_test = X.iloc[train_index,:], X.iloc[test_index,:]
_y_train, _y_test = y.iloc[train_index].values.ravel(), y.iloc[test_index].values.ravel()
clf.fit(_X_train, _y_train, eval_metric="error", verbose=True)

estimators.append(clf.best_estimator_)
results[test_index] = clf.predict(_X_test)
score_arr.append(f1_score(_y_test, results[test_index]))
score += f1_score(_y_test, results[test_index])
score /= numFolds

因此,RandomizedSearchCV 实际上选择了分类器,然后在 kfold 中它在验证集上得到拟合并预测结果。 请注意我已经在kfolds split中给出了X_trainy_train,因此我有一个单独的test数据集用于测试最终的算法。

现在,问题是,如果您实际上查看每次 kfold 迭代中的 f1-score,它就像这样 score_arr = [0.5416666666666667, 0.4, 0.41379310344827586, 0.5, 0.44, 0.43478260869565216 ] .

但是当我在 test 数据集上测试 clf.best_estimator_ 作为我的模型时,它给出的 f1-score0.80 以及 {' precision': 0.8688524590163934, 'recall': 0.7571428571428571} 精度和召回率。

为什么我的分数在验证时很低,现在测试集上发生了什么?我的模型正确还是我错过了什么?

附注- 采用clf.best_estimator_的参数,我使用xgb.cv将它们分别拟合到我的训练数据上,然后还有f1-score code> 接近 0.55。我认为这可能是由于 RandomizedSearchCVxgb.cv 的训练方法之间的差异造成的。请告诉我是否需要绘图或更多信息。

更新:我附上了生成模型的训练和测试aucpr以及分类准确性的误差图。该图是通过仅运行一次 model.fit() 生成的(证明 score_arr 的值合理)。 enter image description here

最佳答案

超参数的随机搜索。

虽然使用参数设置网格是目前最广泛使用的参数优化方法,但其他搜索方法具有更有利的属性。 RandomizedSearchCV 实现对参数的随机搜索,其中每个设置都是从​​可能的参数值的分布中采样的。与详尽的搜索相比,这有两个主要好处:

A budget can be chosen independently of the number of parameters and possible values.

Adding parameters that do not influence the performance does not decrease efficiency.

如果所有参数都以列表形式呈现,则执行无放回采样。如果至少有一个参数作为分布给出,则使用放回抽样。强烈建议对连续参数使用连续分布。

更多信息(引用):SKLEARN documentation for RandomizedSearchCV

关于machine-learning - `sklearn.model_selection.RandomizedSearchCV` 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com