Fit a min-max scaler on train and apply it to test

Why it matters Distance based models such as KNN and k-means and many neural nets expect features on a common scale, and fitting the scaler on test data is a classic interview red flag.

Min-max scaling squeezes every feature into a fixed range, but the min and max must come from the training rows only.

Write minmax_scale(X_train, X_test, lo=0.0, hi=1.0). Both inputs are 2D (n, d). Learn the per-column min and max from X_train, then return X_test mapped by lo + (x - min) / (max - min) * (hi - lo) as a float array of shape X_test.shape. A column that is constant in train uses a range of 1 instead of 0. Do not clip: test values outside the train range may land outside [lo, hi].

Signaturedef minmax_scale(X_train, X_test, lo=0.0, hi=1.0)

Example

X_train [[1, 10], [3, 10], [5, 10]], X_test [[2, 10], [7, 11]] gives [[0.25, 0.0], [1.5, 1.0]].

Understand the idea

Min-max scaling stretches or shrinks each column so the smallest training value becomes lo and the largest becomes hi, like converting marks out of 37 into marks out of 1.

Worked example: a column has training values 1, 3, 5. The min is 1 and the max is 5, so the range is 4. A test value 2 becomes (2 - 1) / 4 = 0.25. A test value 7 becomes (7 - 1) / 4 = 1.5, which is above 1 because the model has never seen such a big value. That is fine and honest.

Rule: x_scaled = lo + (x - min_train) / (max_train - min_train) * (hi - lo), with a range of 1 for constant columns.

The key habit is fit on train, transform on test. If you compute min and max on the test set you quietly use information from the future. Scalers like this sit at the start of most tabular pipelines, before KNN, SVMs and neural networks.

Shapes and data flow

X_train (n, d) -> min, max (d,) -> X_test (m, d) -> scaled (m, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleminmax_scale([[1, 10], [3, 10], [5, 10]], [[2, 10], [7, 11]])
  • Sample 2: range -1 to 1minmax_scale([[0, 2], [4, 6]], [[1, 3], [2, 6], [-4, 0]], -1.0, 1.0)
  • Test 3: randomminmax_scale(_a, _b)
  • Test 4: single test rowminmax_scale([[5, -1], [15, 1]], [[10, 0]])