TExcelTAD
Home › Machine Learning › ML Standard Deviation

ML Standard Deviation

Two data sets can share the same mean and still look completely different. Compare the daily temperatures of two towns:

text
Coastal town:  18, 19, 20, 21, 22
Desert town:    5, 12, 20, 28, 35

Both average 20 °C, but you would pack very different clothes. What separates them is spread: how far the values tend to be from the mean. The two standard measures of spread are variance and standard deviation.

Variance

Variance answers: on average, how far (squared) is each value from the mean? The recipe:

  1. Compute the mean.
  2. Subtract the mean from every value (the deviations).
  3. Square each deviation, so negatives don't cancel positives.
  4. Average the squares.
python · try it yourself
import numpy as np

coastal = np.array([18, 19, 20, 21, 22])

mean = coastal.mean()
deviations = coastal - mean
squares = deviations ** 2
print("mean:      ", mean)
print("deviations:", deviations)
print("squares:   ", squares)
print("variance by hand:", squares.mean())
print("np.var:          ", np.var(coastal))
mean:       20.0
deviations: [-2. -1.  0.  1.  2.]
squares:    [4. 1. 0. 1. 4.]
variance by hand: 2.0
np.var:           2.0

Standard deviation

The trouble with variance is its unit: squared degrees. Taking the square root brings us back to the original unit. That square root is the standard deviation, usually written σ (sigma):

python · try it yourself
import numpy as np

coastal = np.array([18, 19, 20, 21, 22])
desert = np.array([5, 12, 20, 28, 35])

for name, temps in [("coastal", coastal), ("desert", desert)]:
    print(f"{name:8} mean={temps.mean():.1f}  var={np.var(temps):6.1f}  std={np.std(temps):5.2f}")
coastal  mean=20.0  var=   2.0  std= 1.41
desert   mean=20.0  var= 115.6  std=10.75

The desert town's standard deviation is about seven times larger. A low σ means values cluster tightly around the mean; a high σ means they are spread out.

Population vs sample

There is a small but important detail. If your numbers are the entire population you care about, divide by n. If they are a sample taken from a larger population, statisticians divide by n - 1 instead (Bessel's correction), which gives a slightly larger, less biased estimate.

NumPy and pandas disagree on the default:

Tool Default divisor Parameter
np.std(x), np.var(x) n (population) ddof=1 for sample
pandas.Series.std(), .var() n - 1 (sample) ddof=0 for population
statistics.pstdev / statistics.stdev n / n - 1 —
python · try it yourself
import numpy as np
import pandas as pd

desert = [5, 12, 20, 28, 35]

print("numpy  (ddof=0):", round(np.std(desert), 4))
print("numpy  (ddof=1):", round(np.std(desert, ddof=1), 4))
print("pandas (default):", round(pd.Series(desert).std(), 4))
numpy  (ddof=0): 10.7517
numpy  (ddof=1): 12.0208
pandas (default): 12.0208

With large data sets the difference is tiny. With five values it is noticeable, so always know which one you are using.

Using σ to spot unusual values

A handy rule: values more than about two standard deviations away from the mean are unusual. Here are the reaction times (ms) of 12 players in a game; one looks suspicious:

python · try it yourself
import numpy as np

reaction_ms = np.array([251, 263, 240, 258, 249, 270, 245, 262, 255, 248, 410, 259])

mean = reaction_ms.mean()
std = reaction_ms.std()
z_scores = (reaction_ms - mean) / std
print(f"mean = {mean:.1f} ms, std = {std:.1f} ms")
for value, z in zip(reaction_ms, z_scores):
    flag = "  <-- unusual" if abs(z) > 2 else ""
    print(f"{value:4d} ms  z = {z:+.2f}{flag}")
mean = 267.5 ms, std = 43.7 ms
 251 ms  z = -0.38
 263 ms  z = -0.10
 240 ms  z = -0.63
 258 ms  z = -0.22
 249 ms  z = -0.42
 270 ms  z = +0.06
 245 ms  z = -0.51
 262 ms  z = -0.13
 255 ms  z = -0.29
 248 ms  z = -0.45
 410 ms  z = +3.26  <-- unusual
 259 ms  z = -0.19

The number (value - mean) / std is called a z-score: how many standard deviations a value sits from the mean. You will meet it again in the Scale lesson, where z-scores are used to put features on a common scale.

Note: In machine learning, features with a very small standard deviation carry little information (they hardly change), while features with a huge spread can dominate distance-based models. Looking at σ for each column is a quick health check.

Test yourself

Why is the standard deviation often preferred over the variance?

  1. It is always smaller
  2. It is expressed in the same unit as the data
  3. It ignores outliers
  4. It does not need the mean

What does np.std([2, 2, 2, 2]) return?

  1. 0.0
  2. 1.0
  3. 2.0
  4. nan

Which call computes the sample standard deviation (dividing by n - 1) with NumPy?

  1. np.std(x)
  2. np.std(x, ddof=1)
  3. np.std(x, sample=True)
  4. np.var(x) - 1