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.
Transcript
18 sentences · select one to jump thereCheck your understanding
Should large test z-scores trigger silent refitting on the test set?
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.
/**
* 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
]
}# 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.
#
# Run: python main.py
import json
import math
def lesson_118():
train, test = [10, 12, 14, 16], [100, 102]
mean = sum(train) / len(train) # fit on the training data only
squares = 0.0
for x in train:
squares += (x - mean) ** 2
sd = math.sqrt(squares / (len(train) - 1))
transformed = [(x - mean) / sd for x in test] # frozen parameters applied to test
return {"mean": mean, "sd": sd, "transformed": transformed}
if __name__ == "__main__":
print(json.dumps(lesson_118(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"mean": 13,
"sd": 2.581988897471611,
"transformed": [
33.69495511200453,
34.46955178124601
]
}/*
* 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.
*
* Run: javac Main.java && java Main
*/
import java.util.*;
public class Main {
static Map<String, Object> lesson118() {
double[] train = {10, 12, 14, 16};
double[] test = {100, 102};
double mean = 0; // fit on the training data only
for (double x : train) mean += x;
mean /= train.length;
double squares = 0;
for (double x : train) squares += Math.pow(x - mean, 2);
double sd = Math.sqrt(squares / (train.length - 1));
List<Object> transformed = new ArrayList<Object>(); // frozen parameters applied to test
for (double x : test) transformed.add((x - mean) / sd);
return obj("mean", mean, "sd", sd, "transformed", transformed);
}
public static void main(String[] args) {
System.out.println(toJson(lesson118(), ""));
}
// Minimal JSON writer: insertion-ordered Map, List, Number, Boolean, String and null.
static String toJson(Object value, String indent) {
if (value == null) return "null";
if (value instanceof String) return quote((String) value);
if (value instanceof Boolean) return value.toString();
if (value instanceof Double) return formatNumber((Double) value);
if (value instanceof Number) return value.toString();
String inner = indent + " ";
StringBuilder sb = new StringBuilder();
if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
if (map.isEmpty()) return "{}";
sb.append("{\n");
int i = 0;
for (Map.Entry<?, ?> e : map.entrySet()) {
sb.append(inner).append(quote(e.getKey().toString())).append(": ").append(toJson(e.getValue(), inner));
sb.append(++i < map.size() ? ",\n" : "\n");
}
return sb.append(indent).append("}").toString();
}
List<?> list = (List<?>) value;
if (list.isEmpty()) return "[]";
sb.append("[\n");
for (int i = 0; i < list.size(); i++) {
sb.append(inner).append(toJson(list.get(i), inner)).append(i + 1 < list.size() ? ",\n" : "\n");
}
return sb.append(indent).append("]").toString();
}
// Integral doubles print without ".0", as JavaScript does; others use Java's round-trip form.
static String formatNumber(double x) {
if (x == Math.rint(x) && Math.abs(x) < 1e15) return Long.toString((long) x);
return Double.toString(x);
}
static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') sb.append('\\').append(c);
else if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
return sb.append('"').toString();
}
// Builds an insertion-ordered object from alternating keys and values.
static Map<String, Object> obj(Object... keysAndValues) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (int i = 0; i < keysAndValues.length; i += 2) map.put((String) keysAndValues[i], keysAndValues[i + 1]);
return map;
}
static List<Object> list(double... values) {
List<Object> out = new ArrayList<Object>();
for (double v : values) out.add(v);
return out;
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"mean": 13,
"sd": 2.581988897471611,
"transformed": [
33.69495511200453,
34.46955178124601
]
}// 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.
//
// Run: go run main.go
package main
import (
"encoding/json"
"fmt"
"math"
)
type Result struct {
Mean float64 `json:"mean"`
SD float64 `json:"sd"`
Transformed []float64 `json:"transformed"`
}
func lesson118() Result {
train, test := []float64{10, 12, 14, 16}, []float64{100, 102}
mean := 0.0 // fit on the training data only
for _, x := range train {
mean += x
}
mean /= float64(len(train))
squares := 0.0
for _, x := range train {
squares += math.Pow(x-mean, 2)
}
sd := math.Sqrt(squares / float64(len(train)-1))
transformed := make([]float64, len(test)) // frozen parameters applied to test
for i, x := range test {
transformed[i] = (x - mean) / sd
}
return Result{Mean: mean, SD: sd, Transformed: transformed}
}
func main() {
out, err := json.MarshalIndent(lesson118(), "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"mean": 13,
"sd": 2.581988897471611,
"transformed": [
33.69495511200453,
34.46955178124601
]
}// 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.
//
// Run: g++ -std=c++17 -O1 -o lesson main.cpp && ./lesson
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <variant>
#include <vector>
// Minimal JSON value: objects keep insertion order; numbers print in shortest round-trip form.
struct Json {
enum class Kind { Null, Bool, Number, String, Array, Object };
Kind kind = Kind::Null;
bool flag = false;
double number = 0.0;
std::string text;
std::vector<std::string> keys; // object keys, parallel to items
std::vector<Json> items; // array items, or object values
};
Json jnull() { return Json{}; }
Json jbool(bool value) { Json j; j.kind = Json::Kind::Bool; j.flag = value; return j; }
Json jnum(double value) { Json j; j.kind = Json::Kind::Number; j.number = value; return j; }
Json jstr(const std::string& value) { Json j; j.kind = Json::Kind::String; j.text = value; return j; }
Json jarr(std::vector<Json> items) { Json j; j.kind = Json::Kind::Array; j.items = std::move(items); return j; }
Json jobj(std::vector<std::pair<std::string, Json>> fields) {
Json j;
j.kind = Json::Kind::Object;
for (auto& field : fields) {
j.keys.push_back(field.first);
j.items.push_back(std::move(field.second));
}
return j;
}
Json jnums(const std::vector<double>& values) {
std::vector<Json> items;
for (double v : values) items.push_back(jnum(v));
return jarr(std::move(items));
}
Json jnums(const std::vector<std::optional<double>>& values) {
std::vector<Json> items;
for (const auto& v : values) items.push_back(v ? jnum(*v) : jnull());
return jarr(std::move(items));
}
std::string formatNumber(double value) {
char buffer[64];
auto result = std::to_chars(buffer, buffer + sizeof buffer, value); // shortest round-trip form
return std::string(buffer, result.ptr);
}
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') {
out += '\\';
out += c;
} else if (static_cast<unsigned char>(c) < 0x20) {
char buffer[8];
std::snprintf(buffer, sizeof buffer, "\\u%04x", static_cast<unsigned>(c));
out += buffer;
} else {
out += c;
}
}
return out + "\"";
}
void writeJson(std::ostream& out, const Json& value, const std::string& indent = "") {
const std::string inner = indent + " ";
switch (value.kind) {
case Json::Kind::Null: out << "null"; return;
case Json::Kind::Bool: out << (value.flag ? "true" : "false"); return;
case Json::Kind::Number: out << formatNumber(value.number); return;
case Json::Kind::String: out << quote(value.text); return;
case Json::Kind::Array:
case Json::Kind::Object: {
const bool isObject = value.kind == Json::Kind::Object;
if (value.items.empty()) {
out << (isObject ? "{}" : "[]");
return;
}
out << (isObject ? "{\n" : "[\n");
for (std::size_t i = 0; i < value.items.size(); ++i) {
out << inner;
if (isObject) out << quote(value.keys[i]) << ": ";
writeJson(out, value.items[i], inner);
out << (i + 1 < value.items.size() ? ",\n" : "\n");
}
out << indent << (isObject ? "}" : "]");
}
}
}
Json lesson118() {
const std::vector<double> train{10, 12, 14, 16}, test{100, 102};
double mean = 0; // fit on the training data only
for (double x : train) mean += x;
mean /= static_cast<double>(train.size());
double squares = 0;
for (double x : train) squares += std::pow(x - mean, 2);
const double sd = std::sqrt(squares / static_cast<double>(train.size() - 1));
std::vector<double> transformed; // frozen parameters applied to test
for (double x : test) transformed.push_back((x - mean) / sd);
return jobj({{"mean", jnum(mean)}, {"sd", jnum(sd)}, {"transformed", jnums(transformed)}});
}
int main() {
writeJson(std::cout, lesson118());
std::cout << "\n";
return 0;
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"mean": 13,
"sd": 2.581988897471611,
"transformed": [
33.69495511200453,
34.46955178124601
]
}// 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.
//
// Run: rustc -O main.rs && ./main
#![allow(dead_code)]
/// Minimal JSON value; objects keep insertion order.
enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn nums(values: &[f64]) -> Json {
Json::Arr(values.iter().map(|&v| Json::Num(v)).collect())
}
fn optional_nums(values: &[Option<f64>]) -> Json {
Json::Arr(values.iter().map(|v| v.map_or(Json::Null, Json::Num)).collect())
}
fn quote(text: &str) -> String {
let mut out = String::from("\"");
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
// Display for f64 prints the shortest string that round-trips, as JavaScript does.
fn write_json(value: &Json, indent: &str, out: &mut String) {
let inner = format!("{} ", indent);
match value {
Json::Null => out.push_str("null"),
Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Json::Num(n) => out.push_str(&format!("{}", n)),
Json::Str(s) => out.push_str("e(s)),
Json::Arr(items) if items.is_empty() => out.push_str("[]"),
Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
Json::Arr(items) => {
out.push_str("[\n");
for (i, item) in items.iter().enumerate() {
out.push_str(&inner);
write_json(item, &inner, out);
out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push(']');
}
Json::Obj(fields) => {
out.push_str("{\n");
for (i, (key, item)) in fields.iter().enumerate() {
out.push_str(&inner);
out.push_str("e(key));
out.push_str(": ");
write_json(item, &inner, out);
out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" });
}
out.push_str(indent);
out.push('}');
}
}
}
fn lesson_118() -> Json {
let train: [f64; 4] = [10.0, 12.0, 14.0, 16.0];
let test: [f64; 2] = [100.0, 102.0];
let n = train.len() as f64;
let mean = train.iter().fold(0.0, |s, x| s + x) / n; // fit on the training data only
let sd = (train.iter().fold(0.0, |s, x| s + (x - mean).powi(2)) / (n - 1.0)).sqrt();
let transformed: Vec<f64> = test.iter().map(|x| (x - mean) / sd).collect(); // frozen parameters applied to test
obj(vec![
("mean", Json::Num(mean)),
("sd", Json::Num(sd)),
("transformed", nums(&transformed)),
])
}
fn main() {
let mut out = String::new();
write_json(&lesson_118(), "", &mut out);
println!("{}", out);
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"mean": 13,
"sd": 2.581988897471611,
"transformed": [
33.69495511200453,
34.46955178124601
]
}// 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.
//
// Run: dotnet run
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
Console.WriteLine(JsonSerializer.Serialize(Lesson118(), options));
static object Lesson118()
{
double[] train = { 10, 12, 14, 16 }, test = { 100, 102 };
double mean = train.Aggregate(0.0, (s, x) => s + x) / train.Length; // fit on the training data only
double sd = Math.Sqrt(train.Aggregate(0.0, (s, x) => s + Math.Pow(x - mean, 2)) / (train.Length - 1));
double[] transformed = test.Select(x => (x - mean) / sd).ToArray(); // frozen parameters applied to test
return new { mean, sd, transformed };
}
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
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)