Chapter 89 · Solutions
Covariance — Worked Solutions ✅
Five challenges, each verified in code.
⚙️ Setup¶
In [1]:
import numpy as np, pandas as pd
from scipy import stats
BASE="https://raw.githubusercontent.com/johnfisher-ai/Statistics-Data-Science-AI-Visual-Book/main/data/"
rng=np.random.default_rng(890)
CHALLENGE 1
Covariance from the formula
For x=[1,2,3,4,5], y=[2,4,5,4,5], compute the covariance as the mean of deviation products and check with numpy.
In [2]:
x=np.array([1,2,3,4,5]); y=np.array([2,4,5,4,5])
cov=((x-x.mean())*(y-y.mean())).mean()
print(f"formula (ddof=0) = {cov:.3f}, numpy = {np.cov(x,y,ddof=0)[0,1]:.3f}")
formula (ddof=0) = 1.200, numpy = 1.200
CHALLENGE 2
Sign of covariance
Generate a negatively related pair and confirm the covariance is negative.
In [3]:
a=rng.normal(0,1,200); b=-0.7*a+rng.normal(0,0.7,200)
print(f"cov = {np.cov(a,b)[0,1]:.3f} (negative as expected)")
cov = -0.534 (negative as expected)
CHALLENGE 3
Units change covariance, not correlation
Show cov(x, 100*y) = 100*cov(x, y) but the correlation is unchanged.
In [4]:
x=rng.normal(0,1,300); y=0.6*x+rng.normal(0,0.8,300)
print(f"cov(x,y)={np.cov(x,y)[0,1]:.3f}, cov(x,100y)={np.cov(x,100*y)[0,1]:.3f}")
print(f"corr(x,y)={np.corrcoef(x,y)[0,1]:.3f}, corr(x,100y)={np.corrcoef(x,100*y)[0,1]:.3f}")
cov(x,y)=0.714, cov(x,100y)=71.392 corr(x,y)=0.672, corr(x,100y)=0.672
CHALLENGE 4
Standardize to correlation
Compute the correlation as cov/(sx*sy) and confirm it matches np.corrcoef.
In [5]:
print(f"by hand = {np.cov(x,y)[0,1]/(x.std(ddof=1)*y.std(ddof=1)):.4f}, corrcoef = {np.corrcoef(x,y)[0,1]:.4f}")
by hand = 0.6717, corrcoef = 0.6717
CHALLENGE 5
Real data: covariance vs correlation matrix
Load covariance--ad_sales.xlsx; print the covariance and correlation matrices of the four numeric columns.
In [6]:
try: d = pd.read_excel("../../data/covariance--ad_sales.xlsx", sheet_name="Campaigns")
except FileNotFoundError: d = pd.read_excel(BASE+"covariance--ad_sales.xlsx", sheet_name="Campaigns")
num=d[["ad_spend","impressions","web_visits","sales"]]
print("cov(ad_spend,sales)=", f"{num.ad_spend.cov(num.sales):,.0f}")
print("corr matrix:\n", num.corr().round(2))
cov(ad_spend,sales)= 29,191,117
corr matrix:
ad_spend impressions web_visits sales
ad_spend 1.00 0.99 0.97 0.95
impressions 0.99 1.00 0.95 0.93
web_visits 0.97 0.95 1.00 0.91
sales 0.95 0.93 0.91 1.00
Statistics, Data Science and AI: A Visual Handbook · © 2026 John Fisher