Train, validation and test splits
Watch one class split three ways, and see which error predicts new data.
Explain it simply
Each dot is one student, and each row of the file on the left is the same student. The two quiz scores are the features: what a model gets to see. Pass or fail is the label: the answer it must learn. A filled dot passed, and a hollow dot failed.
A scatter of 50 students by quiz 1 and quiz 2 scores. 24 pass and 26 fail. A dashed line marks the true pass line.
Sample i has a feature vector x and a label y.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
def mulberry32(seed): # the seeded generator the diagram uses
a = seed & 0xFFFFFFFF
def rand():
nonlocal a
a = (a + 0x6D2B79F5) & 0xFFFFFFFF
t = ((a ^ (a >> 15)) * (1 | a)) & 0xFFFFFFFF
t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
return (t ^ (t >> 14)) / 4294967296
return rand
def pass_pct(q1, q2): # the true source P: pass chance in %, scores in tenths
return max(5, min(95, 50 + 3 * (q1 + q2 - 100)))
rand = mulberry32(206)
students = []
for _ in range(50): # 50 samples, drawn IID
q1, q2 = math.floor(rand() * 101), math.floor(rand() * 101)
y = 1 if rand() * 100 < pass_pct(q1, q2) else 0 # label: 1 = pass, 0 = fail
students.append((q1, q2, y))
file = sorted(students, key=lambda s: s[0]) # the file is sorted by quiz 1
print([(q1 / 10, q2 / 10, y) for q1, q2, y in file[:3]]) # [(0.2, 5.2, 0), (0.2, 6.9, 0), (0.3, 5.9, 1)]
SHUFFLE, SEED = True, 1 # shuffle the rows first
order = list(range(50))
if SHUFFLE: # Fisher-Yates
rand = mulberry32(SEED)
for i in range(49, 0, -1):
j = math.floor(rand() * (i + 1))
order[i], order[j] = order[j], order[i]
rows = [file[i] for i in order]
train, val, test = rows[:30], rows[30:40], rows[40:]
print([sum(y for _, _, y in s) for s in (train, val, test)]) # [15, 6, 3] pass
def predict(q1, q2, k): # k-nearest neighbors on the training set
near = sorted(range(30), key=lambda j: (train[j][0] - q1) ** 2 + (train[j][1] - q2) ** 2)
return 1 if 2 * sum(train[j][2] for j in near[:k]) > k else 0
def wrong(samples, k):
return sum(predict(q1, q2, k) != y for q1, q2, y in samples)
print(wrong(train, 1), wrong(val, 1)) # 0 4 (of 30 and of 10)
KS = [1, 3, 5, 7, 9, 11, 15, 21, 29]
val_err = {k: wrong(val, k) for k in KS}
print(val_err) # {1: 4, 3: 2, 5: 1, 7: 3, 9: 2, 11: 3, 15: 2, 21: 1, 29: 2}
k_best = min(KS, key=lambda k: val_err[k])
print(k_best, wrong(test, k_best)) # 5 1 (the test set, once)
def new_error(k): # exact error on new students from P
miss = sum(100 - pass_pct(a, b) if predict(a, b, k) else pass_pct(a, b)
for a in range(101) for b in range(101))
return miss / (100 * 101 * 101)
print(f"{100 * new_error(k_best):.1f}%") # 12.3%
Plain Python, no libraries. It draws the same 50 students as the diagram and prints the same errors.
Common mix-ups
MYTHA low training error means the model works on new data.
FIXWith k = 1, the training error is 0%, but the validation error is 40%. Only held-out samples show the error on new data.
MYTHPicking k by test error keeps the test score fair.
FIXThe test error picks k = 1 and shows 0%. New students give 17.5%. A score that chooses cannot also judge.
Takeaways
- Fit on the training set; pick k on the validation set.
- Open the test set once, at the end.
- Shuffle first, so every set looks like new data.