BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix11 of 16 in topic

866. Fix the scaler that leaks test data

MediumDebug and fix Pro

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.

Functiondef 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,).
Topics
Debug and fix
Similar questions
  • Fix the causal mask off-by-oneMedium
  • Fix Adam missing bias correctionMedium
  • Fix attention scores without the transposeMedium
  • Fix the KV cache that grows the wrong axisMedium
All Debug and fix problems
Report
866 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
import numpy as np
​
def scale_split(X, n_train):
X = np.asarray(X, dtype=float)
mu = X.mean(axis=0)
sd = X.std(axis=0)
sd[sd == 0] = 1.0
Z = (X - mu) / sd
return Z[:n_train], Z[n_train:]
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS