使用具有特定簇的 sklearn 进行 K 折叠,而不是按特定大小进行拆分

K folding using sklearn with specific clusters instead of spliting with specific size

我想在 python.My 数据中使用 sklearn 进行 K 折交叉验证,数据有 8 个用户,我只对一个 user.Is 的数据进行 K 折交叉验证用户之间的验证?例如,将 7 个用户用作训练集,将 1 个用户用作测试集,并针对这 8 个不同的场合执行此操作?

是的,这是可能的。为此,您可以对组使用交叉验证。如果你想确保一个人的数据点在 训练集或测试集中,这称为 grouping阻塞。在 scikit-learn 中,可以通过将具有组成员值的数组添加到 cross_val_scores 来实现这样的事情。然后你可以使用 scikit-learn 的 GroupKFold class 和组数作为交叉验证程序。请参见下面的示例。 (简单的逻辑回归模型只是为了说明 GroupKFold 的用法class)

from sklearn.model_selection import GroupKFold
# create synthetic dataset
X, y = make_blobs(n_samples=12, random_state=0)

# the first three samples belong to the same group, etc.
groups = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]

scores = cross_val_score(logreg, X, y, groups, cv=GroupKFold(n_splits=4))

print("cross_val_score(logreg, X, y, groups, cv=GroupKFold(n_splits=4)")
print("Cross-validation scores :\n{}".format(scores))