Split folds by user so no user lands in both train and validation
If one user's sessions sit in both train and validation, the model gets graded on people it has already seen. Group K-fold keeps each group in exactly one fold.
Write group_kfold(groups, k). groups is a list of group labels, one per row. Assign whole groups to folds greedily: process groups by size descending (ties by first appearance), and give each group to the fold with the fewest rows so far (ties to the lowest fold index). Return a list of k sorted int arrays with the validation row indices of each fold.
def group_kfold(groups, k)Example
group_kfold(["a", "a", "b", "c"], 2) gives [[0, 1], [2, 3]].
Understand the idea
If one user's rows appear in both training and validation, the model is graded partly on people it has already seen, and the score looks better than it really is. Group K-fold keeps every group, such as a user, inside exactly one fold. A greedy balancer places the biggest groups first into the currently smallest fold, which keeps fold sizes even. Worked example: groups ['u1', 'u2', 'u2', 'u3', 'u3', 'u3', 'u4'], k = 2. Sizes: u3 = 3, u2 = 2, u1 = 1, u4 = 1 (u1 before u4 by first appearance). u3 goes to fold 0 (both empty, lowest index), rows 3, 4, 5. u2 goes to fold 1, rows 1, 2. u1 goes to fold 1 (2 rows versus 3), row 0. u4: both folds have 3 rows, tie goes to fold 0, row 6. Result [[3, 4, 5, 6], [0, 1, 2]]. Rule: order groups by size descending, ties by first appearance; give each to the fold with the fewest rows, ties to the lowest index; return each fold's row indices sorted. Used for user-level splits in recommender and medical data.