Sub topic 5
How Much Data Goes Where
This chapter assumes you can already call train_test_split, know what a validation set is for, and have run a scikit-learn model. Here you decide the sizes of the parts. The split sizes control two different errors. The size of the test set sets how noisy your final score is. The size of the training set sets how good the model can be.
Two budgets, one dataset
Every row you put in the test set is a row the model cannot learn from. Every row you keep for training is a row that cannot sharpen your estimate. You are balancing two effects:
- Estimate noise. A score measured on
nrows is a sample. Its uncertainty shrinks roughly with the square root ofn. - Model quality. Most models improve as they see more training rows, with diminishing returns.
Neither effect can be removed. You can only decide which one matters more for your dataset.
How noisy is a test score?
For accuracy, each test row is a pass/fail trial. If the true accuracy is p and you test on n independent rows, the standard error is sqrt(p * (1 - p) / n). A 95% interval is about 1.96 standard errors either side of the measured value.
The table assumes a model that is truly 90% accurate:
| Test rows | Standard error | 95% interval (about) |
|---|---|---|
| 100 | 0.030 | ±5.9 points |
| 500 | 0.013 | ±2.6 points |
| 1,000 | 0.009 | ±1.9 points |
| 5,000 | 0.004 | ±0.8 points |
Going from 100 to 1,000 test rows cuts the interval by a factor of about three, not ten. To halve the interval, you need four times the rows.
You can invert the formula to ask how many test rows a given precision needs:
import math
def test_rows_needed(expected_accuracy, margin, z=1.96):
"""Rows needed so a 95% interval is about +/- margin."""
p = expected_accuracy
return math.ceil(z**2 * p * (1 - p) / margin**2)
print(test_rows_needed(0.90, 0.01)) # 3458
print(test_rows_needed(0.90, 0.03)) # 385Measuring a 90% accurate model to within one point needs about 3,458 test rows. Within three points needs about 385.
Measuring the effect yourself
You can see the noise by repeating the split with many seeds. Each run changes both the training and test rows, so the spread reflects both. The test-set effect usually dominates on small test sets.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
for test_size in [0.1, 0.2, 0.3, 0.5]:
accs = []
for seed in range(100):
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=test_size, stratify=y, random_state=seed
)
model.fit(X_tr, y_tr)
accs.append(model.score(X_te, y_te))
print(f"test_size={test_size:.1f} mean={np.mean(accs):.3f} std={np.std(accs):.3f}")Run it and compare the std column across test sizes. The exact numbers depend on your scikit-learn version. The pattern to expect is that a 10% test set (57 rows) gives a visibly wider spread than a 30% or 50% one. The mean may drop slightly at 50% because the model trains on less data.
The lesson is about what a single split means. If you report "97.4% test accuracy" from 114 rows, a different seed could easily give 95% or 99%. That gap is not evidence that one model is better.
How much does more training data help?
A learning curve shows how the score changes as training size grows. It tells you whether collecting or keeping more training rows is worth it.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, learning_curve, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
sizes, train_scores, val_scores = learning_curve(
model, X_train, y_train, train_sizes=np.linspace(0.1, 1.0, 6), cv=cv
)
for n, tr, va in zip(sizes, train_scores.mean(axis=1), val_scores.mean(axis=1)):
print(f"n_train={n:4d} train={tr:.3f} cv={va:.3f}")The curve is computed on the training portion only, so the test set stays untouched. Read it like this:
- If the cross-validated score is still rising at the largest size, more training data would help. Keep the test set small.
- If it has flattened, extra training rows add little. You can afford a larger test set for a tighter estimate.
- A large gap between training and CV scores that narrows as
n_traingrows is a sign of overfitting that more data can reduce.
Common ratios and when to use them
No ratio is correct in general. These defaults work as starting points:
| Dataset size | Typical split | Reasoning |
|---|---|---|
| Under about 1,000 rows | Small test set plus cross-validation on the rest | A fixed validation set would be too noisy to rank models |
| 1,000 to 100,000 rows | 60/20/20 or 70/15/15 | Enough rows for each part to be informative |
| Millions of rows | 98/1/1 or similar | One percent is already tens of thousands of rows |
For large datasets, the test and validation sets are sized by the precision you need, not by a percentage. A fixed absolute number such as 10,000 rows may be all you need, whatever the total.
Effective sample size: the count that matters
Row count overstates your information in several cases. These are the usual traps.
Rare classes
If 1% of rows are positive, a 1,000-row test set has about 10 positives. Recall measured on 10 cases is very noisy: one more or fewer correct changes it by 10 points. Size the test set by the number of minority-class rows you need, not by total rows. Stratified splitting, covered in an earlier chapter, keeps the proportion the same but cannot create more rare cases.
Grouped rows
If 5,000 rows come from 50 patients, you have closer to 50 independent samples than 5,000 when you ask how the model handles new patients. Interval widths follow the number of groups. A 20% test split of those rows means about 10 patients, and the score depends heavily on which 10.
Duplicates
Near-duplicate rows inflate n without adding information. Deduplicate before computing sizes, and before splitting so copies do not land on both sides.
Noise limits what you can conclude
Two models scoring 0.951 and 0.947 on a 500-row validation set are not distinguishable. The interval alone is about ±2 points. Before trusting a small difference:
- Compare against the standard error from the table or from repeated splits.
- Evaluate both models on the same rows. Paired differences are less noisy than two separate scores.
- Prefer cross-validation, which averages over several splits, when the validation set is small.
Treat gaps smaller than the noise as ties and choose the simpler or cheaper model.
Common errors
- Using 80/20 by habit. On 200 rows, 40 test rows give an interval near ±9 points. On 10 million rows, 2 million test rows waste data that could train the model.
- Tuning the split until the score looks good. Trying seeds and keeping the best one turns the test set into a selection tool. Pick the split once, record the seed, and keep it.
- Counting rows instead of independent units. Use groups, patients, users or sessions as the unit when rows are related.
- Shrinking training data for a bigger test set without checking the learning curve. If the curve is still climbing, you lose real accuracy.
- Forgetting to refit at the end. After model selection is finished, you may retrain the chosen configuration on training plus validation data and evaluate once on the test set. The model then benefits from the rows you used only for selection.
Exercise
You have 2,000 labeled transactions, of which 2% are fraud. You plan a 20% test split. Roughly how many fraud cases will the test set contain, and what does that mean for the split you choose?
Show answer
A 20% test split has 400 rows, and 2% of those is about 8 fraud cases. Recall measured on 8 cases is very noisy, since one case changes it by 12.5 points. Either use a larger test fraction, or hold out a smaller test set and rely on stratified cross-validation on the remaining data for model comparison. Size the test set by the number of fraud cases needed for the precision you want, not by the total row count.
Exercise
Using the formula for the standard error of accuracy, about how many test rows do you need to measure a model with expected accuracy 0.80 to within ±2 points at 95% confidence?
Show answer
n = 1.96² × 0.8 × 0.2 / 0.02² = 3.8416 × 0.16 / 0.0004 = 1,536.64, so about 1,537 rows. You can check this with test_rows_needed(0.80, 0.02) from the chapter.