Find test rows that also appear in the training set

Why it matters Duplicate leakage is one of the most common reasons a Kaggle or internal model scores far better offline than in production.

Duplicated rows across train and test inflate test scores because the model has already memorised the answer.

Write leaked_test_rows(X_train, X_test, decimals=6). Both are 2D numeric arrays with the same number of columns. Round both to the given number of decimals and return the sorted list of test row indices whose rounded row exactly equals some rounded train row.

Signaturedef leaked_test_rows(X_train, X_test, decimals=6)

Example

X_train [[1, 2], [3, 4]], X_test [[3, 4], [5, 6], [1.0000000001, 2]] gives [0, 2].

Understand the idea

If the same row sits in both train and test, the test score is partly a memory test, not a generalisation test. It is like a teacher putting last week's homework questions on the exam: marks go up, learning does not.

Worked example: train has [1, 2] and [3, 4]. Test row 0 is [3, 4], an exact copy. Test row 2 is [1.0000000001, 2], which is the same row after a CSV round trip added float noise. After rounding to 6 decimals it becomes [1, 2], also a copy. Test row 1, [5, 6], is new. Answer: [0, 2].

Rule: leaked = { i : round(test_i) is in set(round(train rows)) }.

Hashing rounded rows makes the check linear time even for millions of rows. Real pipelines run this before every evaluation, and for text data they do the same thing after normalising case and whitespace.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: exampleleaked_test_rows([[1, 2], [3, 4]], [[3, 4], [5, 6], [1.0000000001, 2]])
  • Sample 2: no leakleaked_test_rows([[0, 0, 1]], [[0, 0, 2], [1, 0, 0]])
  • Test 3: coarse decimalsleaked_test_rows([[1.234, 5.0], [2.0, 2.0]], [[1.2341, 5.0], [2.04, 2.0], [2.0, 2.0]], 2)
  • Test 4: all leakedleaked_test_rows([[7, 7], [8, 8]], [[8, 8], [7, 7], [8, 8]])