Standard deviation
- Machine Learning course
- Beginner
- Lesson 27/112
- 5 min
Standard deviation shows how much data deviates from the mean.
Standard deviation
The standard deviation measures how far the values move from the mean on average. If it is small the data is tight; if large, spread out.
a = np.array([10, 10, 10, 10])
b = np.array([0, 5, 15, 20])
print(a.std(), b.std()) # 0.0 7.905...Both arrays have the same mean (10) but very different spreads; the mean alone isn't enough.
ddof: sample and population
By default NumPy computes the population standard deviation (divides by n). When estimating the population from a sample, ddof=1 divides by n-1; that is the pandas default:
x = np.array([2, 4, 4, 4, 5, 5, 7, 9])
print(x.std()) # 2.0
print(x.std(ddof=1)) # 2.138...With large datasets the difference becomes negligible; but when NumPy and pandas results differ, this is usually why.
Practice Measure the spread
Print the population standard deviation (the default) of array x. Then print how many standard deviations each value is from the mean ((x - mean) / std).
Starter code
import numpy as np
x = np.array([2, 4, 4, 4, 5, 5, 7, 9])
# buraya yazSample solution
import numpy as np
x = np.array([2, 4, 4, 4, 5, 5, 7, 9])
s = x.std()
print(s)
print((x - x.mean()) / s)Expected output
2.0 [-1.5 -0.5 -0.5 -0.5 0. 0. 1. 2. ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the standard deviation of an array whose values are all the same?
- 1
- Equal to the mean
- Undefined
- 0 Correct answer
Explanation: No value deviates from the mean, so the spread is zero.
2 Compute the sample standard deviation.
s = x.std(____)
s = x.std(ddof=1)
Explanation: ddof=1 makes the denominator n-1.
3 Match the values.
| Term | Meaning |
|---|---|
small std() |
Data is tight |
large std() |
Data is spread out |
ddof=0 |
Dividing by n |
ddof=1 |
Dividing by n-1 |