TExcelTAD
Home › Machine Learning › ML Train/Test

ML Train/Test

Up to now we measured how well a model fits the same data it was trained on. That is like letting students grade their own homework with the answer sheet next to them: of course the score looks good. What we really want to know is how the model will do on new data it has never seen.

The simplest honest method is the train/test split:

  • the training set (typically 70–80 % of the rows) is used to fit the model,
  • the testing set (the remaining 20–30 %) is kept hidden and used only at the end to measure accuracy.

Our data set

We simulate 100 days of a small online shop: the number of minutes customers spent on the site and how much they spent. Spending rises with time on the site but levels off — a gentle curve plus noise:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(12)
minutes = rng.uniform(1, 30, size=100)
spent = 60 * np.log(minutes) + rng.normal(0, 12, size=100)

plt.scatter(minutes, spent, s=15)
plt.xlabel("Minutes on site")
plt.ylabel("Amount spent")
plt.show()
print(f"{len(minutes)} customers simulated")
100 customers simulated

Splitting by hand

Since the data is in random order already, we could simply take the first 80 rows for training and the last 20 for testing:

python · try it yourself
import numpy as np

rng = np.random.default_rng(12)
minutes = rng.uniform(1, 30, size=100)
spent = 60 * np.log(minutes) + rng.normal(0, 12, size=100)

train_x, test_x = minutes[:80], minutes[80:]
train_y, test_y = spent[:80], spent[80:]
print("train:", train_x.shape, " test:", test_x.shape)
train: (80,)  test: (20,)

In practice, use scikit-learn's train_test_split. It shuffles the rows first (important when the data is sorted, e.g. by date or by class) and splits X and y consistently:

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(12)
minutes = rng.uniform(1, 30, size=100)
spent = 60 * np.log(minutes) + rng.normal(0, 12, size=100)

X_train, X_test, y_train, y_test = train_test_split(
    minutes.reshape(-1, 1), spent, test_size=0.2, random_state=42
)
print("X_train:", X_train.shape, " X_test:", X_test.shape)
print("first training row:", X_train[0].round(2), "->", y_train[0].round(2))
X_train: (80, 1)  X_test: (20, 1)
first training row: [14.8] -> 147.98

random_state=42 fixes the shuffle so the split is the same every time — a must for reproducible results. The order of the four return values (X_train, X_test, y_train, y_test) is worth memorising.

Comparing models on unseen data

Now the payoff. We fit polynomials of increasing degree on the training set only and compute R² on both sets:

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score

rng = np.random.default_rng(12)
minutes = rng.uniform(1, 30, size=100)
spent = 60 * np.log(minutes) + rng.normal(0, 12, size=100)

x_tr, x_te, y_tr, y_te = train_test_split(minutes, spent, test_size=0.2, random_state=42)

print("degree  train R^2  test R^2")
for degree in [1, 2, 3, 6, 12]:
    model = np.poly1d(np.polyfit(x_tr, y_tr, degree))
    print(f"{degree:6}  {r2_score(y_tr, model(x_tr)):9.3f}  {r2_score(y_te, model(x_te)):8.3f}")
degree  train R^2  test R^2
     1      0.879     0.775
     2      0.930     0.880
     3      0.935     0.910
     6      0.940     0.928
    12      0.942     0.880

Look at the pattern:

  • Training R² never goes down as the degree grows: a more flexible curve can always fit the training points at least as well.
  • Test R² improves at first (a curve fits better than a line), then stops improving or gets worse once the curve starts to chase noise.

Here degree 6 has the best test score, with degree 3 close behind; degree 12 is clearly worse on the test set despite its higher training score. The training score alone would always tell you "more complex is better", which is wrong. When two options score about the same, prefer the simpler one: we'll use degree 3 below.

Making a prediction

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score

rng = np.random.default_rng(12)
minutes = rng.uniform(1, 30, size=100)
spent = 60 * np.log(minutes) + rng.normal(0, 12, size=100)
x_tr, x_te, y_tr, y_te = train_test_split(minutes, spent, test_size=0.2, random_state=42)

model = np.poly1d(np.polyfit(x_tr, y_tr, 3))
print(f"test R^2: {r2_score(y_te, model(x_te)):.3f}")
print(f"a customer who browses 10 minutes is expected to spend {model(10):.2f}")
test R^2: 0.910
a customer who browses 10 minutes is expected to spend 137.16

Warning: Never let the test set influence training decisions more than once. If you keep tweaking the model until the test score looks great, the test set quietly becomes training data and stops being an honest estimate. The Cross Validation lesson shows a better way to compare many options.

Go further: When rows belong to the same customer or arrive in time order, a random split leaks the answer: Random, Stratified, Group and Time-Based Splits shows the splits to use instead.

Test yourself

What is the test set used for?

  1. Fitting the model's coefficients
  2. Estimating performance on unseen data
  3. Scaling features
  4. Choosing the random seed

What does train_test_split(X, y, test_size=0.25, random_state=0) return, in order?

  1. X_train, y_train, X_test, y_test
  2. X_train, X_test, y_train, y_test
  3. train, test
  4. X_test, X_train, y_test, y_train

A model scores R² = 0.99 on training data and 0.40 on test data. What is most likely happening?

  1. Underfitting
  2. Overfitting
  3. The test set is too large
  4. Perfect generalisation