Fit imputation, scaling and one-hot encoding on train and apply them to test
A real feature pipeline does several things at once: fill missing numbers, standardise them, and one-hot encode a category. Every statistic must come from the training set, and categories never seen in training must not crash the model.
Write preprocess(train_num, train_cat, test_num, test_cat).
- train_num: float array (n, p), may contain np.nan. test_num: (m, p), may contain np.nan.
- train_cat, test_cat: lists of strings or None, one categorical column.
Fit on train only:
1. median of each numeric column ignoring nan (0.0 if the column is all nan).
2. after filling train nans with those medians, the mean and population std (ddof 0) of each column; a std of 0 becomes 1.
3. categories = sorted distinct non-None strings in train_cat.
Transform test: fill nans with the train medians, standardise with the train mean and std, then append one-hot columns in category order. A None or unseen category gives all zeros.
Return a float array of shape (m, p + number of categories).
def preprocess(train_num, train_cat, test_num, test_cat)Example
train_num = [[1], [nan], [3]], train_cat = ["a", "b", "a"], test_num = [[nan]], test_cat = ["c"]: median 2, filled train [1, 2, 3], mean 2, std 0.8165, so the output is [[0.0, 0.0, 0.0]].
Understand the idea
A feature pipeline must learn every statistic from the training set only and reuse it on new data, just as it will in production where each request arrives alone. Here that means three fitted things: per-column medians for filling missing numbers, mean and standard deviation for scaling (computed after filling), and the sorted list of training categories for one-hot columns. Unknown or missing categories become all zeros instead of crashing. Worked example: train_num [[2], [nan], [4], [6]], train_cat [b, a, None, b]. Median of [2, 4, 6] is 4; filled train [2, 4, 4, 6]; mean 4; population std sqrt((4 + 0 + 0 + 4) / 4) = 1.414. Categories [a, b]. Test row [nan] with 'a' becomes 4, scaled 0, plus one-hot [1, 0], so [0, 1, 0]. Test row [8] with 'z' becomes (8 - 4) / 1.414 = 2.828 plus [0, 0]. Rule: fit medians, then mean and std (std 0 becomes 1), then categories, all on train; transform test with them; output width p + number of categories. scikit-learn pipelines exist to enforce this.