scikit-learn 1.3 通过内置的 groupkfold、leaveonegroupout 和 leavepgroupsout 等分组交叉验证器,支持在训练集与测试集划分时严格隔离特定分组。只需将包含分组信息的数组作为 groups 参数传入这些验证器的 split() 方法或 cross_validate 函数中,即可确保同一分组的数据不会同时出现在训练集和测试集中。

GroupKFold 如何按组划分数据
GroupKFold 会将数据划分为 n_splits 个折,保证每个折中的分组互不重叠。例如,当有 6 个样本分为 3 个组(每组 2 个样本)时,设置 n_splits=3 会生成 3 个折,每个折包含一个完整的组作为测试集,其余两个组作为训练集。

from sklearn.model_selection import GroupKFold
import numpy as np
# 示例数据:6个样本,3个组
X = np.array([[1], [2], [3], [4], [5], [6]])
y = np.array([0, 1, 0, 1, 0, 1])
groups = np.array([0, 0, 1, 1, 2, 2]) # 前两个样本属于组0,中间两个属于组1,最后两个属于组2
gkf = GroupKFold(n_splits=3)
for train_index, test_index in gkf.split(X, y, groups):
print(f"Train indices: {train_index}, Test indices: {test_index}")
print(f"Train groups: {groups[train_index]}, Test groups: {groups[test_index]}")运行上述代码将输出:
立即学习“Python免费学习笔记(深入)”;
Train indices: [2 3 4 5], Test indices: [0 1] Train groups: [1 1 2 2], Test groups: [0 0] Train indices: [0 1 4 5], Test indices: [2 3] Train groups: [0 0 2 2], Test groups: [1 1] Train indices: [0 1 2 3], Test indices: [4 5] Train groups: [0 0 1 1], Test groups: [2 2]
可以看到,每个折的测试集都包含一个完整的组,且训练集中的组与测试集中的组没有交集。
LeaveOneGroupOut 如何处理留一法分组
LeaveOneGroupOut 每次留出所有属于同一个组的数据作为测试集,其余所有组的数据作为训练集。如果数据中有 N 个不同的组,则会生成 N 个折。这种方法适用于每个组代表一个独立的实验或患者等情况,确保模型在完全未见过的组上进行评估。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

from sklearn.model_selection import LeaveOneGroupOut
logo = LeaveOneGroupOut()
for train_index, test_index in logo.split(X, y, groups):
print(f"Train indices: {train_index}, Test indices: {test_index}")
print(f"Train groups: {groups[train_index]}, Test groups: {groups[test_index]}")运行上述代码将输出:
立即学习“Python免费学习笔记(深入)”;
Train indices: [2 3 4 5], Test indices: [0 1] Train groups: [1 1 2 2], Test groups: [0 0] Train indices: [0 1 4 5], Test indices: [2 3] Train groups: [0 0 2 2], Test groups: [1 1] Train indices: [0 1 2 3], Test indices: [4 5] Train groups: [0 0 1 1], Test groups: [2 2]
在这个例子中,由于只有 3 个组,LeaveOneGroupOut 的行为与 GroupKFold(n_splits=3) 相同。但如果组数更多,LeaveOneGroupOut 会为每个组生成一个单独的折。
使用 cross_validate 进行分组交叉验证评估
在实际应用中,通常需要将分组交叉验证与模型评估结合使用。sklearn.model_selection.cross_validate 函数支持 groups 参数,可以直接传入分组信息,自动执行分组交叉验证并返回各折的性能指标。
from sklearn.svm import SVC
from sklearn.model_selection import cross_validate
# 定义一个简单的分类器
clf = SVC(kernel='linear')
# 执行分组交叉验证
cv_results = cross_validate(clf, X, y, cv=GroupKFold(n_splits=3), groups=groups,
scoring='accuracy', return_train_score=True)
print("Train scores:", cv_results['train_score'])
print("Test scores:", cv_results['test_score'])这段代码会使用 GroupKFold 进行 3 折分组交叉验证,评估 SVC 模型的性能。返回的结果包括每折的训练得分和测试得分,方便分析模型的泛化能力。

















