Skip to content
Raisalon

Machine Learning

How to split a dataset by customer ID in scikit-learn

Use GroupShuffleSplit to keep each customer in one partition. Check for overlapping IDs and see how a row split can inflate an evaluation score.

Author
4 min read

To test how a model performs on new customers, split your dataset by customer ID. If Alice has five orders, all five belong on the same side of the split. In scikit-learn, GroupShuffleSplit can assign customers to partitions and return the row positions you need to train and evaluate your model.

Decide what counts as a new example

Suppose a subscription service uses the first order from a customer to predict whether they will need help with onboarding. Your historical orders table contains several rows per account. Two orders can have different order numbers but share a billing plan, delivery address and support history. A random row split can give the model examples from the same account on both sides.

Dropping the customer ID from the feature matrix doesn’t fix the evaluation design. The remaining features can still identify repeat customers indirectly. Keep the ID alongside your features long enough to decide where each row goes. The prediction target determines the group: use an account ID if two users on the same account share the outcome you are trying to predict.

Build one holdout and check the IDs

This example needs pandas and scikit-learn. The order numbers form a nonconsecutive index so you can see why positional selection matters. There are eight orders from five customers. One customer placed three orders and two customers placed only one.

import pandas as pd
from sklearn.model_selection import GroupShuffleSplit

orders = pd.DataFrame(
    {
        "customer_id": ["A", "A", "A", "B", "C", "C", "D", "E"],
        "items": [1, 3, 1, 2, 5, 2, 1, 4],
        "needed_help": [1, 1, 0, 0, 1, 0, 0, 1],
    },
    index=[101, 103, 104, 109, 113, 118, 121, 125],
)
groups = orders["customer_id"]
assert groups.notna().all()

splitter = GroupShuffleSplit(n_splits=1, test_size=0.4, random_state=7)
train_pos, test_pos = next(splitter.split(orders, groups=groups))
train, test = orders.iloc[train_pos], orders.iloc[test_pos]

overlap = set(train["customer_id"]) & set(test["customer_id"])
assert not overlap, f"Customers in both partitions: {overlap}"
assert test["customer_id"].nunique() == 2
for name, part in [("train", train), ("test", test)]:
    print(name, len(part), sorted(part["customer_id"].unique()))

The fraction 0.4 applies to the five distinct customers. Two go to the test set. The fraction of orders in the test set depends on which customers were drawn. The returned integers are positions into the original frame, so select with iloc before sorting or filtering. A fixed random seed makes comparisons reproducible for this input. scikit-learn GroupShuffleSplit reference

See how a row split can reward memorization

Consider a separate, deliberately small example. Customer A has label 1 on both orders and customer B has label 0 on both. Train a lookup rule that remembers the label for each customer and predicts 0 for an unknown customer. This exaggerated baseline makes the effect visible without fitting a large model.

Training orders Test orders Correct predictions
First order from A and first order from B Second order from A and second order from B 2 of 2
Both orders from B Both orders from A 0 of 2

Both scores follow directly from the lookup rule. The first experiment tests recognition of two known customers. The second reveals exactly what the rule does when a new customer arrives. The arithmetic illustrates a failure mode. With real labels and more customers, the size and even the direction of a score change depend on the draw.

Audit what the grouped split actually contains

Count customers, orders and positive outcomes in each partition. If one customer generates half the orders, a row-weighted average heavily reflects that customer’s experience. An average of per-customer scores answers a different question, giving each customer equal weight. State which unit your reported score represents.

Also check whether a rare outcome is missing from either side. With five customers, a single held-out account can change the result substantially. For model selection on a larger training set, pass training customer IDs to a grouped cross-validation splitter. Fit imputers, scalers and other learned preprocessing inside each training fold. Leave the final customer holdout untouched until you have chosen the model. scikit-learn guide to grouped cross-validation

Handle customers with very different order histories

Take four held-out customers who placed 1, 1, 1 and 17 orders. Suppose a model gets the first three customers’ orders right and gets 8 of the last customer’s 17 orders right. Its order-level accuracy is 11 out of 20, or 55%. If you calculate accuracy for each customer and average those four numbers, you get about 86.8%. Both calculations use exactly the same predictions. The first describes a randomly selected order and the second describes a randomly selected customer’s average experience.

A similar weighting issue affects a validation threshold. A threshold chosen to minimize mistakes per order will give a frequent customer more influence than an occasional buyer. Determine which cost the business incurs before averaging scores. If you report a customer average, retain the per-customer order counts so reviewers can see which individual scores rest on a single prediction.

If an order has no reliable customer ID, keep track of it explicitly. Assigning a fresh ID to every missing row assumes all those orders came from different customers. Assigning one shared ID assumes they all came from the same group. Either assumption can dominate a small holdout. Report how many orders need an identity decision before interpreting the test.

Next steps

Write down the deployment question before saving the split. For future orders from existing customers, a chronological cutoff may match deployment better. For new customers arriving next quarter, check both first-seen dates and group overlap. Save the customer assignments with the experiment so subsequent models face the same test. If the resulting holdout has very few positives, inspect the worked example of high accuracy and zero recall before interpreting its headline score.

Share

Written by