TExcelTAD
Home › Data Science › DS Variance

DS Variance

The variance is the average squared distance of the values from their mean. You met it in the previous lesson as the step just before the square root: the standard deviation is the square root of the variance, and the variance is the standard deviation squared.

text
variance = Σ (xᵢ − mean)² / (n − 1)        (sample variance)
sd       = √variance

Computing variance

python · try it yourself
import numpy as np
import pandas as pd

temp = np.array([24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7])

manual = ((temp - temp.mean()) ** 2).sum() / (len(temp) - 1)
print("manual sample variance:", manual.round(3))
print("np.var(ddof=1):        ", np.var(temp, ddof=1).round(3))
print("pandas .var():         ", round(pd.Series(temp).var(), 3))
print("sd = sqrt(variance):   ", np.sqrt(manual).round(3))
manual sample variance: 62.93
np.var(ddof=1):         62.93
pandas .var():          62.93
sd = sqrt(variance):    7.933

As with std, pandas' var() uses ddof=1 by default and NumPy's np.var uses ddof=0.

Why bother with variance if we have the SD?

The unit of variance is the data's unit squared — "degrees²" or "rides²" — which is hard to picture. So for describing data, the SD is friendlier. But variance has mathematical properties that make it the workhorse behind the scenes:

  1. Variances of independent parts add up. If daily rides = weather effect + random noise, then var(rides) ≈ var(weather effect) + var(noise). Standard deviations do not add.
  2. Regression is built on it. Least squares minimises a sum of squared deviations, and R² (Regression R-Squared lesson) is literally "the share of the variance explained by the model".

Variances add up

Let's check property 1 with simulated data: two independent sources of variation, and their sum.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
weather_effect = rng.normal(0, 90, 100_000)   # sd 90 -> variance 8100
noise = rng.normal(0, 30, 100_000)            # sd 30 -> variance 900
total = weather_effect + noise

print("var(weather):", round(weather_effect.var()))
print("var(noise):  ", round(noise.var()))
print("var(total):  ", round(total.var()))
print("sum of vars: ", round(weather_effect.var() + noise.var()))
print()
print("sd(total):", round(total.std(), 1), " vs  sd(weather) + sd(noise):",
      round(weather_effect.std() + noise.std(), 1))
var(weather): 8044
var(noise):   902
var(total):   8959
sum of vars:  8946

sd(total): 94.7  vs  sd(weather) + sd(noise): 119.7

The variances add up (8 044 + 902 = 8 946, very close to the 8 959 measured for the total), while the SDs do not (94.7, not 90 + 30 ≈ 120). The match is close but not exact because a random sample never hits its theoretical values perfectly — and because the two simulated parts are almost, not perfectly, uncorrelated.

Decomposing the variance of rides

This idea answers a real question: how much of the day-to-day variation in rentals comes from temperature? Fit the best line for temperature (as in the Slope & Intercept lesson), then compare the variance of the predictions with the variance of what's left over:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

slope, intercept = np.polyfit(bikes["temp_c"], bikes["rides"], 1)
predicted = intercept + slope * bikes["temp_c"]
leftover = bikes["rides"] - predicted

v_total = bikes["rides"].var()
v_pred = predicted.var()
v_left = leftover.var()
print(f"total variance:      {v_total:9.1f}")
print(f"explained by temp:   {v_pred:9.1f}")
print(f"left over:           {v_left:9.1f}")
print(f"share explained:     {v_pred / v_total:.3f}")
total variance:        11787.7
explained by temp:      8556.5
left over:              3231.1
share explained:     0.726

The two parts add up exactly to the total, and temperature alone accounts for roughly 73 % of the variance in daily rides. Keep that number in mind — it reappears as R² = 0.726 when we fit the same model with statsmodels.

Summary

Variance Standard deviation
Unit data unit² data unit
Easy to interpret no yes
Adds up over independent parts yes no
pandas .var() .std()

Test yourself

The standard deviation of daily temperature is 7 °C. What is the variance?

  1. 7 °C
  2. 14 °C
  3. 49 °C²
  4. √7 °C

Two independent sources of variation have variances 400 and 900. What is the variance of their sum?

  1. 50
  2. 1300
  3. √1300
  4. 500

What does the "share explained" of 0.726 in the last example mean?

  1. 72.6 % of days are warm
  2. Temperature accounts for about 73 % of the variance in daily rides
  3. The slope is 0.726
  4. The model is wrong 27.4 % of the time