Train test split in Python means holding back part of your data so you can score a model on rows it never saw. It looks like one line of code, but the split itself changes your score. This guide measures how much, using 7,043 real telecom customers and 100 different random splits for each setting.
The data is the IBM Telco Customer Churn sample: one row per customer, with a yes or no churn label. It is a published sample dataset, not a live company. Code was run with pandas 3.0.5 and scikit-learn 1.9.1. The question throughout is: how far can I trust a single test score?

Step 1: Set up one model and one dataset
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
url = "https://raw.githubusercontent.com/IBM/telco-customer-churn-on-icp4d/master/data/Telco-Customer-Churn.csv"
df = pd.read_csv(url)
df["TotalCharges"] = pd.to_numeric(df.TotalCharges, errors="coerce").fillna(0)
y = (df.Churn == "Yes").astype(int)
X = df.drop(columns=["customerID", "Churn"])
num = ["tenure", "MonthlyCharges", "TotalCharges", "SeniorCitizen"]
cat = [c for c in X.columns if c not in num]
def model():
return make_pipeline(
ColumnTransformer([("n", StandardScaler(), num),
("c", OneHotEncoder(handle_unknown="ignore"), cat)]),
LogisticRegression(max_iter=2000))
print(len(df), round(y.mean(), 3))7043 0.26526.5% of customers churned, so the classes are unbalanced. The preprocessing sits inside a pipeline, so scaling and encoding are learned from training rows only, as in our guide to building a machine learning model with scikit-learn.
Step 2: Run the split 100 times, not once
def run(Xs, ys, seeds, test_size, stratify=True):
scores = []
for s in seeds:
a, b, c, d = train_test_split(Xs, ys, test_size=test_size,
stratify=ys if stratify else None, random_state=s)
scores.append(roc_auc_score(d, model().fit(a, c).predict_proba(b)[:, 1]))
return np.array(scores)
print("seed 0 only:", round(run(X, y, [0], 0.25)[0], 3))
for ts in [0.5, 0.25, 0.1]:
r = run(X, y, range(100), ts)
print("test %d%%: mean %.3f sd %.3f range %.3f-%.3f" % (ts * 100, r.mean(), r.std(), r.min(), r.max()))seed 0 only: 0.844
test 50%: mean 0.845 sd 0.005 range 0.833-0.856
test 25%: mean 0.845 sd 0.008 range 0.828-0.863
test 10%: mean 0.846 sd 0.015 range 0.810-0.891Seed 0 gives an AUC of 0.844. Across 100 seeds the 25% test set gives a mean of 0.845 but a range of 0.828 to 0.863, a spread of about 0.035 between the luckiest and unluckiest split. A 10% test set is noisier (standard deviation 0.015, range 0.810 to 0.891), and a 50% test set is steadier (0.005). The mean barely moves, so the test size changes how much you can trust one number, not what the model is worth. A smaller test set also leaves more rows for training, which matters when data is scarce. Report a single split as a rough value, and say how big the test set was.
Step 3: Small datasets make the split matter much more
idx = np.random.RandomState(0).choice(len(X), 300, replace=False)
r = run(X.iloc[idx], y.iloc[idx], range(100), 0.25)
print("300 rows: mean %.3f sd %.3f range %.3f-%.3f" % (r.mean(), r.std(), r.min(), r.max()))300 rows: mean 0.774 sd 0.051 range 0.641-0.884On a random 300-row sample the same model scores 0.774 on average, but individual splits range from 0.641 to 0.884 (standard deviation 0.051, only 75 test rows). A student who tries a few seeds and keeps the best one is reporting luck. For small data, prefer cross-validation, covered in random forests explained, and report the spread.
Step 4: Stratify when classes are unbalanced
def test_churn_rate(stratify):
rates = []
for s in range(100):
_, _, _, d = train_test_split(X, y, test_size=0.05,
stratify=y if stratify else None, random_state=s)
rates.append(d.mean())
return min(rates), max(rates)
print("random split: %.3f to %.3f" % test_churn_rate(False))
print("stratified split: %.3f to %.3f" % test_churn_rate(True))random split: 0.193 to 0.320
stratified split: 0.266 to 0.266With a 5% test set (353 customers), a plain random split gave test sets with anywhere from 19.3% to 32.0% churners across seeds, while the true rate is 26.5%. The stratified split held it at 26.6% every time. Pass stratify=y for classification, so every split keeps the label balance. See the train_test_split documentation for all options.
Step 5: See what leakage does to a score
a, b, c, d = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
forest = make_pipeline(
ColumnTransformer([("n", "passthrough", num),
("c", OneHotEncoder(handle_unknown="ignore"), cat)]),
RandomForestClassifier(300, random_state=0, n_jobs=2)).fit(a, c)
leaky_X = pd.concat([b, a.iloc[:len(b)]]) # half the rows were seen in training
leaky_y = pd.concat([d, c.iloc[:len(b)]])
print("clean test AUC %.3f" % roc_auc_score(d, forest.predict_proba(b)[:, 1]))
print("half rows seen %.3f" % roc_auc_score(leaky_y, forest.predict_proba(leaky_X)[:, 1]))
print("training rows AUC %.3f" % roc_auc_score(c, forest.predict_proba(a)[:, 1]))clean test AUC 0.825
half rows seen 0.939
training rows AUC 1.000Here we deliberately break the test: half the rows in the “test” set were also in training. A random forest then scores 0.939 instead of 0.825, a jump of 0.11 that comes entirely from memorising. Its AUC on the training rows is 1.000. The logistic regression we used earlier barely changed (0.845 against 0.844 in a separate check), because a simple model cannot memorise rows. So leakage hurts most with flexible models, and a high score alone never proves the split was clean. The file also holds 40 rows whose features exactly match another row, which is a small version of the same risk. Check for duplicates before splitting, as we describe in cleaning and preprocessing data in Python.
Step 6: Cross-validation and a validation set
cv = cross_val_score(model(), X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="roc_auc")
print("5-fold: mean %.3f sd %.3f" % (cv.mean(), cv.std()), np.round(cv, 3).tolist())
a3, tmp, c3, ytmp = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
v, t, yv, yt = train_test_split(tmp, ytmp, test_size=0.5, stratify=ytmp, random_state=0)
print("train / validation / test:", len(a3), len(v), len(t))5-fold: mean 0.845 sd 0.014 [0.856, 0.819, 0.853, 0.844, 0.856]
train / validation / test: 4930 1056 1057Five-fold cross-validation gave 0.845 with folds from 0.819 to 0.856. That is a more honest picture than one split. When you also tune settings, use three parts: train to fit, validation to choose, test to report once. A 70/15/15 split gives 4,930, 1,056 and 1,057 rows. Never tune against the final test set, or it stops being a test.
Rules of thumb from these runs
Use stratify for classification. Fix random_state so results can be repeated, but do not pick the seed that looks best. Keep at least a few hundred test rows if you can. With under about 1,000 rows, use cross-validation and report the spread. Split before any step that learns from the data, and remove duplicate rows first. For time-ordered data, split by date instead of at random; we did not test that here. The same ideas appear in customer churn prediction in Python, which uses this data end to end.
FAQ
What is a good train test split ratio in Python?
80/20 or 75/25 are common defaults. In our test the ratio changed the noise, not the average: the 25% test set had a standard deviation of 0.008 across seeds, the 10% set 0.015 and the 50% set 0.005.
What does random_state do in train_test_split?
It fixes the shuffle so you get the same split every time. It makes results repeatable, but a different value would give a different score, as the 100-seed range above shows.
When should I use stratify in train_test_split?
Whenever you classify with unbalanced labels. It keeps the class share the same in both parts. In our 5% test it held churn at 26.6% every time, while a plain split ranged from 19.3% to 32.0%.
What is data leakage in a train test split?
Leakage means information from the test rows reached the model during training, for example through duplicate rows or preprocessing fitted on all the data. It inflates scores, most of all for flexible models: our forest scored 0.939 instead of 0.825.
