download

You scaled the data before the split. What went wrong?

Machine learning~12 minReviewed 29 Oct 2026Free · No sign-in

Question

Rows A and B are the training set. Rows P and Q are the test set.

rowx1x2role
A00train, label 0
B101train, label 1
P60test
Q0100test

The code scales all four rows to the 0 to 1 range, then splits them. A 1-nearest-neighbour model gives each test row the label of the closest training row. It predicts class 1 for P.

What is wrong? Fix it, and say which class P should get.

"CODE · PYTHON"
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import MinMaxScaler

X = np.array([[0, 0], [10, 1], [6, 0], [0, 100]])  # A, B, P, Q
y_train = np.array([0, 1])

X_scaled = MinMaxScaler().fit_transform(X)    # scale all rows
X_train, X_test = X_scaled[:2], X_scaled[2:]  # then split

model = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)
print(model.predict(X_test[:1]))  # P
Show hints (3)
  1. "WHAT FIT LEARNS"

    MinMaxScaler learns two numbers per column: the minimum and the maximum. Which rows did it learn them from here?

  2. "WATCH COLUMN X2"

    From A and B alone, x2 runs from 0 to 1. With Q, it runs from 0 to 100. What happens to the gap between P and B?

  3. "THE FIX"

    Fit the scaler on the training rows only. Then use that same fitted scaler on the test rows. A Pipeline does both steps for you.

Show checked explanation

The scaler learned its min and max from all rows, test rows included. That is data leakage: test data influenced the training. Here Q alone flips P from class 0 to class 1. Fit the scaler on the training rows only and reuse it on the test rows. A Pipeline does this for you.

"SOLUTION · PYTHON"
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler

X_train = np.array([[0, 0], [10, 1]])  # A, B
y_train = np.array([0, 1])
X_test = np.array([[6, 0], [0, 100]])  # P, Q

model = make_pipeline(MinMaxScaler(), KNeighborsClassifier(n_neighbors=1))
model.fit(X_train, y_train)  # the scaler sees A and B only
print("scaler ranges:", model[0].data_range_.tolist())
print("P gets:", model.predict(X_test[:1]))
"OUTPUT"
scaler ranges: [10.0, 1.0]
P gets: [0]

Code run on CPython 3.12 with scikit-learn 1.9 against the example above. Checked by an editor other than the author.

Walkthrough

MinMaxScaler maps each column to the 0 to 1 range with (value - min) / (max - min). fit learns the min and max. transform only applies them. So the min and max are learned values, just like a model's weights.

After scaling, A is (0, 0) and P is (0.6, 0) either way. Only B moves. The table shows P's squared distances to A and B. You can skip the square root: it doesn't change which row is nearest.

scaler fitted onB after scalingP to AP to BP gets
A and B only(1, 1)0.361.160
all four rows(1, 0.01)0.360.16011

With the right fit, x2 runs from 0 to 1, and B sits a full unit above P. A is closer. In the leaky fit, Q's x2 of 100 stretches that range to 0 to 100. B's x2 shrinks to 0.01, so B is suddenly closer.

A, B, their labels and P did not change. One test row changed the answer for another. That is the harm: the test score no longer shows how the model does on data it has never seen. The scaler never saw a label, and it still leaked.

A Pipeline keeps the right order for you. model.fit fits the scaler and then the model on the training rows. model.predict only calls the scaler's transform on new rows, so test rows can't change the min and max. With the right fit, Q becomes (0, 100). That is expected: MinMaxScaler doesn't clip new rows to 0 to 1 by default.

Common mistakes

  • Thinking the scaler can't leak because it never sees the labels. Its maximum for x2 came from test row Q, and that alone flipped P.
  • Calling fit_transform on the test set too. That fits a second scaler, so the same raw value turns into different numbers in train and test.
  • Scaling the whole dataset once, then running cross-validation on it. Every round leaks. Put the scaler inside a Pipeline so each round refits it.
  • Treating only scaling as risky. Filling missing values with a mean, picking features by how well they match the target, and PCA all learn from data. Fit them on training rows only.

Follow-up questions

  • "How do you do this with cross-validation?" Pass the whole pipeline to cross_val_score(model, X, y, cv=5). In each of the 5 rounds, it fits the scaler and the model on the training folds only. Then it transforms and scores the held-out fold with those numbers.
  • "Each customer has several rows, or the data is a time series. Is a pipeline enough?" No. A pipeline makes each step learn only from the training rows, but it doesn't choose those rows. If one customer's rows land in both train and test, the model has partly seen the answer. Split by customer with GroupKFold. For time series, use TimeSeriesSplit so you never train on the future.
  • "You tried 50 settings and kept the one with the best test score. Is that leakage too?" Yes. Each choice you make by looking at the test score fits the model a little more to the test set. Tune with cross-validation or a separate validation set. Use the test set once, at the end.

What a strong answer covers

Spots that the scaler's min and max are learned from data, so fitting them on test rows is leakage even without labels. Shows the effect on a small example. Fixes it with fit-on-train and a Pipeline, and extends the idea to cross-validation and grouped or time-based splits.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.