Correlation
From -1 to 1.
Correlation is covariance with the units removed. Divide by both standard deviations, and you always get a number between minus one and one. It's one of the most used numbers in all of data science.

- Covariance without units
- Always between −1 and 1
- Used everywhere
np.corrcoef
NP dot corr coef gives the correlation, often called r. Run it. Zero point nine nine. That's a very strong positive link between study hours and scores. Converting hours to minutes doesn't change it at all.
import numpy as np
from study import hours, scores
r = np.corrcoef(hours, scores)[0, 1]
print("r =", round(r, 3))
print("minutes:", round(np.corrcoef(hours * 60, scores)[0, 1], 3))r = 0.992 minutes: 0.992
Also uses study.py
import numpy as np
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8])
scores = np.array([42, 50, 53, 61, 64, 72, 74, 85])What different r values look like
Here are three scatter plots. A strong positive correlation, no correlation, and a moderate negative one. Run it. The closer r is to one or minus one, the more tightly the points hug a straight line.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(0)
x = rng.normal(0, 1, 300)
ys = [x + rng.normal(0, 0.4, 300), rng.normal(0, 1, 300), -x + rng.normal(0, 1, 300)]
fig, ax = plt.subplots(1, 3, figsize=(10, 3.8))
for a, y in zip(ax, ys):
a.scatter(x, y, s=8)
a.set_title(f"r = {np.corrcoef(x, y)[0, 1]:.2f}")
plt.tight_layout(); plt.savefig("r.png")Summary
Correlation runs from minus one to one, and doesn't depend on units. It measures straight line relationships. Next, the biggest warning in statistics.
Key takeaways- np.corrcoef
- −1 to 1
- Measures straight lines