Python,机器学习 - 对自定义验证集执行网格搜索

Python, machine learning - Perform a grid search on custom validation set

我正在处理一个不平衡的 class 化问题,我的负 class 比我的正 class 多 1000 倍。我的策略是在平衡(50/50 比例)训练集(我有足够的模拟样本)上训练深度神经网络,然后使用不平衡(1/1000 比例)验证集来 select 最好的模型并优化超参数。

由于参数数量很大,我想使用scikit-learn RandomizedSearchCV,即随机网格搜索。

据我了解,sk-learn GridSearch 将训练集上的指标应用于 select 最佳超参数集。然而,就我而言,这意味着 GridSearch 将 select 模型针对 平衡 训练集表现最佳,而不是针对更现实的不平衡数据。

我的问题是:有没有一种方法可以使用在特定的、用户定义的验证集上估计的性能进行网格搜索?

按照评论中的建议,你需要的是PredefinedSplit. It is described in the

关于工作,你可以看文档中给出的例子:

from sklearn.model_selection import PredefinedSplit
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 1, 1])

#This is what you need
test_fold = [0, 1, -1, 1]

ps = PredefinedSplit(test_fold)
ps.get_n_splits()
#OUTPUT
2

for train_index, test_index in ps.split():
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = X[train_index], X[test_index]
   y_train, y_test = y[train_index], y[test_index]

#OUTPUT
TRAIN: [1 2 3] TEST: [0]
TRAIN: [0 2] TEST: [1 3]

正如您在此处看到的,您需要为 test_fold 分配一个索引列表,这些索引将用于拆分数据。 -1 将用于样本的索引,这些样本不包括在验证集中。

所以在上面的代码中,test_fold = [0, 1, -1, 1] 表示在第一个验证集中(样本中的索引,其值在 test_fold 中为 0),索引 0。第二个是 test_fold 的值为 1,因此索引 1 和 3。

但是当你说你有 X_trainX_test 时,如果你只想从 X_test 获得验证集,那么你需要执行以下操作:

my_test_fold = []

# put -1 here, so they will be in training set
for i in range(len(X_train)):
    my_test_fold.append(-1)

# for all greater indices, assign 0, so they will be put in test set
for i in range(len(X_test)):
    my_test_fold.append(0)

#Combine the X_train and X_test into one array:
import numpy as np

clf = RandomizedSearchCV( ...    cv = PredefinedSplit(test_fold=my_test_fold))
clf.fit(np.concatenate((X_train, X_test), axis=0), np.concatenate((y_train, y_test), axis=0))