866. Fix the scaler that leaks test data
Why it matters Fitting preprocessing on the full dataset is the most common form of data leakage. Offline scores look better than what the model will see in production.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
scale_split(X, n_train) should split the rows of X into train (the first n_train rows) and test (the rest), then standardise both with the mean and population std (ddof=0) of the train rows only. A train column with std 0 uses std 1 instead.
Inputs: X is a list or ndarray of shape (n, d). n_train is an int with 1 <= n_train < n.
Return a tuple (train_scaled, test_scaled) of ndarrays of floats with shapes (n_train, d) and (n - n_train, d). No rounding.
def scale_split(X, n_train)Example 1
Input: scale_split([[1.0], [3.0], [100.0]], 2)
Output: ([[-1.0], [1.0]], [[98.0]])
Example 2
Input: X = [[0.0, 5.0], [2.0, 5.0], [4.0, 5.0], [10.0, 9.0]], n_train = 3
Output: ([[-1.224745, 0.0], [0.0, 0.0], [1.224745, 0.0]], [[4.898979, 4.0]])
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Which rows does the starter use to compute mu?
Hint 2
Split first, then fit.
Hint 3
Apply the train mu and sd to the test rows.
Common mistakes
- Fitting a second scaler on the test rows.
- Using ddof=1.
- Leaving std 0 columns as division by zero.
Understand the idea
Statistics must come from data the model is allowed to see at training time. Here the test row 100.0 drags the mean and std, so the train features are scaled with information from the future. Fit mu and sd on the train slice, then apply the same transform to both slices.
Shapes and data flow
X: (n, d). mu, sd: (d,).