Sub topic 1
Tabular data and how to validate a model
Prerequisites
This chapter assumes you can:
- Read and write basic Python and pandas code.
- Explain features, labels and overfitting.
- Describe a decision tree and a train/validation split.
- Interpret common metrics such as RMSE, log loss and AUC.
Later chapters train LightGBM and CatBoost models. Every number those models report depends on the validation setup you choose here.
What tabular data is
Tabular data is a table. Each row is one example, such as a customer, a house or a transaction. Each column is a feature, and one column is the label you want to predict. Columns can be numeric (age, price), categorical (city, plan), boolean, or missing in some rows.
Boosted trees are a strong default for this kind of data for three reasons:
- Trees split on one column at a time, so the scale of a column does not matter. You do not need to normalize features.
- Trees capture interactions between columns, such as "plan is pro and age is above 55", without you building them by hand.
- Trees tolerate mixed column types and, in both libraries, missing values.
The cost is that a boosted model can fit noise very closely. A good validation setup is how you detect that.
Three datasets, three jobs
Split your labeled data into three parts. Each has one job.
| Dataset | Job | Used how often |
|---|---|---|
| Training set | Fit the trees | Every boosting round |
| Validation set | Choose the number of trees, tune hyperparameters, compare models | Many times |
| Test set | Report the final expected performance | Once |
Every decision you make by looking at the validation score leaks a little information from the validation set into your model. Early stopping is one such decision. It picks the iteration where validation error is lowest. After many such choices, the validation score is slightly optimistic. The test set gives an estimate that no decision has touched.
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=2000, n_features=10, weights=[0.9, 0.1], random_state=0
)
X = pd.DataFrame(X, columns=[f"f{i}" for i in range(10)])
y = pd.Series(y)
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
X_train, X_valid, y_train, y_valid = train_test_split(
X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=0
)
print(len(X_train), len(X_valid), len(X_test))
print(round(y_train.mean(), 3), round(y_valid.mean(), 3), round(y_test.mean(), 3))The first split holds out 20% as the test set. The second splits the remaining 80% into 60% training and 20% validation of the original data. The stratify argument keeps the share of positive labels about equal in every part. With a 10% positive rate, an unstratified split could give a validation set with noticeably fewer positives, which makes AUC and log loss noisy.
Choosing a splitting scheme
A random split is correct only if your rows are independent and the future looks like the past in the way your training data does. Real data often breaks that assumption. The split must imitate how the model will be used.
The four schemes:
- Random. Shuffle and cut. Use it only when rows are independent.
- Stratified. Preserve the class proportions. Use it for classification, especially with rare classes.
- Grouped. Rows from the same customer, device or patient stay together. Otherwise the model can recognize an entity it saw in training, and validation scores look better than real performance.
- Time-based. Train on earlier rows and validate on later ones. Use it for forecasting, fraud, churn and anything where deployment predicts the future.
Cross-validation
A single validation set of a few hundred rows gives a noisy score. K-fold cross-validation splits the development data into k folds. It trains k models, each validated on a different fold, and averages the scores. The spread across folds shows how much to trust a difference between two configurations.
Scikit-learn provides a splitter for each scheme above. This block is self-contained and checks that the grouped and time-based splits behave as intended.
import numpy as np
from sklearn.model_selection import GroupKFold, StratifiedKFold, TimeSeriesSplit
rng = np.random.default_rng(0)
n = 1000
X = rng.normal(size=(n, 5))
y = (rng.random(n) < 0.1).astype(int)
groups = rng.integers(0, 100, n) # for example, a customer id per row
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for train_idx, valid_idx in skf.split(X, y):
print("stratified positive rate:", round(y[valid_idx].mean(), 3))
gkf = GroupKFold(n_splits=5)
for train_idx, valid_idx in gkf.split(X, y, groups):
assert set(groups[train_idx]).isdisjoint(groups[valid_idx])
tscv = TimeSeriesSplit(n_splits=4)
for train_idx, valid_idx in tscv.split(X):
assert train_idx.max() < valid_idx.min()
print("train rows:", len(train_idx), "valid rows:", len(valid_idx))TimeSeriesSplit assumes the rows are already sorted by time. Sort first, or the "past" and "future" are meaningless. The training window grows with each fold, and every validation block lies after its training block.
Leakage
Data leakage means the model sees information at training time that it will not have at prediction time. Leakage produces excellent validation scores and poor production results. Common sources:
- Target-derived features. A column computed from the label, or recorded after the outcome. A "refund issued" column in a churn model is an example.
- Preprocessing before the split. Computing means, encodings or target statistics on the full dataset, then splitting. Fit any such step on the training part only. This matters again for categorical encoding in later chapters.
- Duplicates across splits. The same row, or near-copies, in both training and validation.
- Entity overlap. The grouped-split problem above.
- Future information. A rolling average that includes days after the row's date.
A useful check is suspicion of results. If a first model reaches AUC 0.99 on a hard problem, look for leakage before celebrating. Feature importance, covered later, often exposes a single leaking column.
Metrics must match the decision
Pick the validation metric before you start tuning, and make it match the real goal:
- RMSE punishes large errors heavily, so it suits regression where big misses are costly. Use MAE if outliers should matter less.
- Log loss scores the predicted probabilities. Use it when you need calibrated probabilities.
- AUC measures how well the model ranks positives above negatives, ignoring any threshold. It is the usual choice for imbalanced ranking problems. It does not tell you whether the probabilities are accurate.
Accuracy misleads on imbalanced data. With 10% positives, a model that always predicts "negative" is 90% accurate and useless.
Practical rules
- Fix the random seed and the split before comparing models, so differences come from the models and not the split.
- Never use the test set for early stopping or tuning.
- After choosing hyperparameters and the number of trees, you may retrain on training plus validation data with the chosen settings. Then evaluate once on the test set.
- Report the fold-to-fold standard deviation next to the mean score.
Exercise
A churn dataset has several monthly rows per customer, covering January to December. You plan to predict next month's churn for current customers. Which splitting scheme should you use, and why would a plain random split give misleading scores?
Show answer
Use a time-based split, with grouping if the same customers appear in both parts. Train on earlier months and validate on later ones, because deployment predicts the future. A random split puts rows from the same customer, and from months after the validation row, in the training data. The model then learns customer-specific patterns and future information, so the validation score is better than the score you would see in production.
Exercise
You tune hyperparameters and use early stopping against a validation set, then report the best validation AUC as your final result. What is wrong, and what should you do instead?
Show answer
The validation set influenced many choices, including the stopping iteration, so its best score is optimistically biased. Hold out a separate test set before any tuning. Evaluate on it once, after all choices are fixed, and report that score.