Machine Learning from Scratch · Data as Numbers
Putting Features on the Same Scale
Grams and a 1-to-10 sweetness score live on very different scales. See how that makes one feature drown out the other, and how scaling to 0-1 fixes it.
scaling.py
# Four fruits: weight in grams, and sweetness from 1 to 10.
grams = [150, 152, 130, 110]
sweet = [8, 2, 8, 5]
# Which fruit is most like fruit 0? Compare its distance to fruit 1 and to fruit 2.
d1 = ((grams[0] - grams[1]) ** 2 + (sweet[0] - sweet[1]) ** 2) ** 0.5
d2 = ((grams[0] - grams[2]) ** 2 + (sweet[0] - sweet[2]) ** 2) ** 0.5
print("before scaling:", round(d1, 2), round(d2, 2))
# Squeeze each feature into 0 to 1: (value - smallest) / (largest - smallest).
lo, hi = min(grams), max(grams)
grams = [(g - lo) / (hi - lo) for g in grams]
lo, hi = min(sweet), max(sweet)
sweet = [(s - lo) / (hi - lo) for s in sweet]
d1 = ((grams[0] - grams[1]) ** 2 + (sweet[0] - sweet[1]) ** 2) ** 0.5
d2 = ((grams[0] - grams[2]) ** 2 + (sweet[0] - sweet[2]) ** 2) ** 0.5
print("after scaling:", round(d1, 2), round(d2, 2))
Step by step
- Four fruits' weights in grams: they range from 110 to 152.
- Their sweetness, from 1 to 10. Fruit 0 is 150 g and sweet 8; fruit 1 is almost the same weight but sour (2); fruit 2 is lighter but just as sweet (8).
- Distance from fruit 0 to fruit 1: √(2² + 6²) = √40 ≈ 6.32. They differ by 2 g but by 6 in sweetness.
- Distance from fruit 0 to fruit 2: √(20² + 0²) = 20. Same sweetness, 20 g lighter.
- So fruit 1 looks far closer (6.32 against 20), only because grams are big numbers. A sour fruit wins because it weighs nearly the same, while a fruit that tastes the same loses.
- Find the smallest and largest weight: 110 and 152.
- Each weight becomes (weight − 110) / (152 − 110): 150 g → 0.95, 152 g → 1, 130 g → 0.48, 110 g → 0. Every weight is now between 0 and 1.
- The same for sweetness: smallest 2, largest 8.
- Sweetness 8 → 1, 2 → 0, 5 → 0.5. Both features now use the same 0-to-1 scale.
- Fruit 0 to fruit 1 again, on the new scale: the weight difference is tiny (0.05) and the sweetness difference is the whole range (1), so the distance is about 1.
- Fruit 0 to fruit 2: weight differs by 0.48, sweetness not at all, so about 0.48.
- The answer flipped: before scaling fruit 1 looked closest, after scaling fruit 2 does. Nothing about the fruits changed, only the units. That is why features are scaled before anything that measures distance.