Algorithms From Scratch

How to Scale Machine Learning Data From Scratch With Python

Suresh Madhra·Mar 03, 2026·8 min read

Why scaling matters

Many algorithms treat every input as if it lived on the same ruler. Gradient descent takes a step proportional to the input value; k-nearest neighbours measures distance; neural networks initialise weights assuming inputs are small. Feed them a column measured in thousands next to a column measured in tenths and the big column dominates the model for reasons that have nothing to do with predictive power.

Two rescalings cover almost everything: normalization to the 0–1 range, and standardization to zero mean and unit variance.

1. Normalization (min–max)

Use it when you know sensible bounds, when the distribution is not Gaussian, or when the algorithm expects bounded inputs (sigmoid outputs, image pixels). The cost: it is sensitive to outliers, since a single extreme value squashes everything else.

normalize.py

2. Standardization (z-score)

Use it when the column is roughly Gaussian, when you need unbounded values, or when the algorithm assumes centred data (linear and logistic regression, PCA, SVMs). Outliers still move the mean, but far less violently than they move a min or a max.

standardize.py

3. The mistake everyone makes once

Compute the statistics on the training set only, then apply them to the test set. Scaling the whole dataset before splitting leaks information about the test distribution into training and inflates your score — sometimes dramatically, always misleadingly.

no_leakage.py

Which one should you use?

  • Neural networks and gradient descent: standardize, or normalize if inputs are naturally bounded.
  • k-NN, k-means, SVM with RBF: always scale — distance metrics are meaningless otherwise.
  • Decision trees, random forests, gradient boosting: scaling changes nothing; splits are order-based.
  • Regularized linear models: standardize, otherwise the penalty punishes large-scale features unfairly.