Module 12 · Statistical Computing and Reproducibility Lesson 118 of 120

Leakage-Free Fitting, Scaling, and Preprocessing

Fitting a scaler without teaching it the test distribution.

2:37 clip6:19:41–6:22:18 in the full courseWatch on YouTube

Transcript

18 sentences · select one to jump there

Check your understanding

Should large test z-scores trigger silent refitting on the test set?

Choose one answer

Code lab

Run it yourself

The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.

118-leakage-free-fitting-scaling-and-preprocessing.ts
Start from GitHub
/**
 * Fintech Math Bootcamp · Lesson 118 of 120
 * Leakage-Free Fitting, Scaling, and Preprocessing
 * Module 12: Statistical Computing and Reproducibility
 *
 * Scenario: Fitting a scaler without teaching it the test distribution
 * Rule:     fit(train) → freeze parameters → transform(test)
 *
 * Try it:   Should large test z-scores trigger silent refitting on the test set?
 *
 * Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/statistical-computing-and-reproducibility/leakage-free-fitting-scaling-and-preprocessing/
 * Free course:    https://courses.thefintechbuilder.com
 * Synthetic teaching example, not financial advice or a production library.
 */

export function lesson118() {
  const train=[10,12,14,16],test=[100,102];
  const mean=train.reduce((s,x)=>s+x,0)/train.length;
  const sd=Math.sqrt(train.reduce((s,x)=>s+(x-mean)**2,0)/(train.length-1));
  const transformed=test.map(x=>(x-mean)/sd);
  const result={mean,sd,transformed};
  return result;
}

export const checkedResult = {"mean":13,"sd":2.581988897471611,"transformed":[33.69495511200453,34.46955178124601]};

// Run this file directly: npx tsx lessons/12-statistical-computing-and-reproducibility/118-leakage-free-fitting-scaling-and-preprocessing.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
  console.log(JSON.stringify(lesson118(), null, 2));
}

Your output

Press Run to execute the code in your browser.

Expected output

{
  "mean": 13,
  "sd": 2.581988897471611,
  "transformed": [
    33.69495511200453,
    34.46955178124601
  ]
}

Prefer your own machine? Every file is in the course repository · open it in Codespaces.

Lesson notes

The rule

fit(train) → freeze parameters → transform(test)