Machine Learning from Scratch ยท Testing Models
Train, Test, and Overfitting
A model that memorises its training data scores perfectly on it and badly on anything new. Hold some data back, and test on that.
train_test.py
# Hours studied and exam scores for six students.
hours = [1, 2, 3, 4, 5, 6]
scores = [3, 5, 6, 9, 10, 13]
split = ["train", "train", "train", "train", "test", "test"]
# Learn from the first four only. Keep the last two hidden: they test the model.
train_x, train_y = hours[:4], scores[:4]
test_x, test_y = hours[4:], scores[4:]
# Model 1, a straight line, fitted to the training data (least squares).
mx, my = sum(train_x) / 4, sum(train_y) / 4
w = sum([(x - mx) * (y - my) for x, y in zip(train_x, train_y)]) / sum([(x - mx) ** 2 for x in train_x])
b = my - w * mx
line_train = sum([abs(w * x + b - y) for x, y in zip(train_x, train_y)]) / 4
line_test = sum([abs(w * x + b - y) for x, y in zip(test_x, test_y)]) / 2
# Model 2 memorises every training answer, and answers anything else like the nearest hour it saw.
memory = dict(zip(train_x, train_y))
memo_train = sum([abs(memory[x] - y) for x, y in zip(train_x, train_y)]) / 4
memo_test = sum([abs(memory[max(train_x)] - y) for x, y in zip(test_x, test_y)]) / 2
print("line: train error", round(line_train, 2), "test error", round(line_test, 2))
print("memoriser: train error", memo_train, "test error", memo_test)
Step by step
- Six students: hours studied.
- Their exam scores. More study, higher score, roughly in a straight line.
- Labels saying which students the models may learn from (train) and which are kept hidden to test them (test).
- The first four students are the training set.
- The last two are the test set. The models never see these while learning.
- Model 1, a straight line. First the averages of the training hours and scores.
- The least-squares slope: the line that best fits the four training points. w = 1.9 points per hour.
- And the intercept: b = 1. The line now appears on the chart.
- Training error: on average the line is 0.35 points away from the training scores. Not zero, because the points are not exactly on a line.
- Test error: 0.55 on the two hidden students. A bit worse than training, but close. The line has learned the real pattern, so it works on new data too.
- Model 2, a memoriser: it stores every training answer exactly.
- Training error: 0. It just looks the answers up, so it is perfect on data it has seen.
- Test error: 2.5. Asked about 5 or 6 hours, it can only repeat the answer for the nearest hour it saw (4 hours, 9 points). It never learned that more study means more points.
- The line: 0.35 on training, 0.55 on test.
- The memoriser: 0 on training, 2.5 on test. Perfect on training but bad on new data is called overfitting. Always judge a model on data it did not learn from.