TExcelTAD
Home › Data Science › DS Train/Test Split & Evaluation

DS Train/Test Split & Evaluation

A model is only useful if it works on new data — tomorrow's weather, next month's riders. Judging a model by how well it fits the data it was trained on is like grading a student on exam questions they saw in advance. The fix is simple: hold some data back and evaluate on it.

Overfitting

A flexible enough model can memorise its training data, noise included. It then looks brilliant on that data and fails on anything new. This is overfitting. Let's provoke it with polynomials of increasing degree on the first 20 days:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

train, test = bikes.iloc[:20], bikes.iloc[20:]

def rmse(actual, predicted):
    return np.sqrt(np.mean((actual - predicted) ** 2))

for degree in [1, 3, 6, 9]:
    coefs = np.polyfit(train["temp_c"], train["rides"], degree)
    train_err = rmse(train["rides"], np.polyval(coefs, train["temp_c"]))
    test_err = rmse(test["rides"], np.polyval(coefs, test["temp_c"]))
    print(f"degree {degree}: train RMSE {train_err:7.1f}   test RMSE {test_err:9.1f}")
degree 1: train RMSE    42.6   test RMSE      62.6
degree 3: train RMSE    41.8   test RMSE      63.5
degree 6: train RMSE    39.9   test RMSE      66.4
degree 9: train RMSE    34.2   test RMSE     158.4

The training error keeps falling as the curve gets more flexible, while the test error rises — slowly at first, then dramatically at degree 9, where the wiggly curve chases the noise in 20 points and makes wild predictions elsewhere. The plain straight line generalises best.

Error metrics

Metric Formula Reads as
MAE — mean absolute error mean of |actual − predicted| "on average we're off by … rides"
RMSE — root mean squared error √ mean of (actual − predicted)² like MAE, but punishes big misses more
MAPE — mean absolute percentage error mean of |error| / actual "off by …%" (bad when actual values are near 0)
R² on test data 1 − SSE / SST on the test set share of variance explained on new data

Always compare against a baseline, such as "predict the training mean every day". A model that can't beat the baseline is useless, however good its R² looks.

Splitting randomly

For data without a time order, a random split is standard. scikit-learn's train_test_split shuffles with a fixed random_state so the split is reproducible:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

train, test = train_test_split(bikes, test_size=0.25, random_state=0)
print("train rows:", len(train), " test rows:", len(test))

def evaluate(name, predicted):
    err = test["rides"] - predicted
    mae = err.abs().mean()
    rmse = np.sqrt((err ** 2).mean())
    r2 = 1 - (err ** 2).sum() / ((test["rides"] - test["rides"].mean()) ** 2).sum()
    print(f"{name:28} MAE={mae:6.1f}  RMSE={rmse:6.1f}  R2={r2:6.3f}")

evaluate("baseline (training mean)", np.full(len(test), train["rides"].mean()))
for f in ["rides ~ temp_c", "rides ~ temp_c + rain_mm + weekend"]:
    m = smf.ols(f, data=train).fit()
    evaluate(f, m.predict(test))
train rows: 45  test rows: 15
baseline (training mean)     MAE=  93.6  RMSE= 111.6  R2=-0.001
rides ~ temp_c               MAE=  53.0  RMSE=  65.9  R2= 0.651
rides ~ temp_c + rain_mm + weekend MAE=  26.5  RMSE=  30.8  R2= 0.924

The baseline's test R² is slightly negative (it doesn't even explain the test set's own mean). Temperature alone cuts the typical error substantially, and the full model brings it down to about 26 rides per day.

Splitting by time

When you'll use a model to predict the future, test it on the future: train on earlier days, test on later ones. A random split would let the model "peek" at days that come after some test days, which flatters it if anything drifts over time.

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

cutoff = pd.Timestamp("2024-05-16")
train = bikes[bikes["date"] < cutoff]
test = bikes[bikes["date"] >= cutoff]
print(f"train: {train['date'].min().date()} to {train['date'].max().date()} ({len(train)} days)")
print(f"test:  {test['date'].min().date()} to {test['date'].max().date()} ({len(test)} days)")

m = smf.ols("rides ~ temp_c + rain_mm + weekend", data=train).fit()
result = test[["date", "rides"]].copy()
result["predicted"] = m.predict(test).round()
result["error"] = result["rides"] - result["predicted"]
print(result.head(6).to_string(index=False))
print("test MAE:", round(result["error"].abs().mean(), 1))
train: 2024-04-01 to 2024-05-15 (45 days)
test:  2024-05-16 to 2024-05-30 (15 days)
      date  rides  predicted  error
2024-05-16    459      440.0   19.0
2024-05-17    371      313.0   58.0
2024-05-18    220      252.0  -32.0
2024-05-19    420      429.0   -9.0
2024-05-20    265      237.0   28.0
2024-05-21    273      255.0   18.0
test MAE: 20.2

Cross-validation

With only 60 rows, a single 15-row test set is a noisy judge — another split could give a quite different score. k-fold cross-validation splits the data into k parts, trains on k − 1 and tests on the remaining one, rotating through all parts, then averages the scores:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

kf = KFold(n_splits=5, shuffle=True, random_state=1)
for f in ["rides ~ temp_c", "rides ~ temp_c + rain_mm + weekend",
          "rides ~ temp_c + rain_mm + weekend + humidity"]:
    maes = []
    for train_idx, test_idx in kf.split(bikes):
        train, test = bikes.iloc[train_idx], bikes.iloc[test_idx]
        m = smf.ols(f, data=train).fit()
        maes.append((test["rides"] - m.predict(test)).abs().mean())
    print(f"{f:44} MAE per fold {np.round(maes, 1)}  mean {np.mean(maes):.1f}")
rides ~ temp_c                               MAE per fold [51.  35.8 53.4 45.6 42.9]  mean 45.7
rides ~ temp_c + rain_mm + weekend           MAE per fold [26.2 31.3 27.7 18.3 25.8]  mean 25.9
rides ~ temp_c + rain_mm + weekend + humidity MAE per fold [28.4 31.4 28.6 18.5 25.9]  mean 26.5

The three-variable model wins clearly. Adding humidity doesn't help on unseen data — it slightly worsens the average error — confirming what its p-value suggested.

Tip: Never tune anything (features, outlier rules, model choice) on the test set. If you look at test results and go back to change the model, the test set has become training data. Use cross-validation on the training part for choices, and keep the final test for the very end.

Test yourself

A model has a much lower error on training data than on test data. What's the likely problem?

  1. Underfitting
  2. Overfitting
  3. A wrong baseline
  4. Too much test data

You forecast next month's rides. How should you split the data?

  1. Randomly
  2. By time: train on earlier days, test on later days
  3. Test on the training data
  4. Use only weekends

Why use a baseline such as "predict the mean"?

  1. It's the best model
  2. It shows whether the real model adds any value
  3. It's required by scikit-learn
  4. It increases R²