Skip to content
Tactiverge

Correlation is not causation

Measure how strongly two quantities move together, then see in a simulation how a hidden third factor can create a strong correlation with no causal link, and how controlled experiments reveal the truth.

Lesson 6 of 6 · 30 min · Self-paced · Free

A tempting conclusion

You log 300 test runs of a robot arm. You notice that on runs where the joint motor was hotter, the arm's position error was larger. The obvious conclusion: heat is causing the error, so add a cooling fan. That fan costs money, mass and power. Before buying it, you need to know whether heat really causes the error, or whether the two just happen to rise together. This lesson shows how to tell the difference.

Measuring correlation

The Pearson correlation coefficient, r, measures how closely two quantities follow a straight-line relationship. It runs from −1 to +1:

  • r = +1: the points lie exactly on a rising line.
  • r = −1: the points lie exactly on a falling line.
  • r = 0: no straight-line relationship (though there might still be a curved one).

It is built from the same pieces as the least-squares slope in the line-fitting lesson:

              Σ (x − x̄)(y − ȳ)
r = ---------------------------------
     √( Σ(x − x̄)² · Σ(y − ȳ)² )

For a straight-line fit, r² is the same as the R² you met in that lesson. Python 3.10 and later provide statistics.correlation(xs, ys).

A simulation where we know the truth

In real data you never know for certain what causes what. In a simulation, you write the rules, so you can check whether analysis methods find the truth. Here is a model of the robot arm (simulated, made-up data). The payload the arm carries makes the motor work harder, which heats it, and also bends the arm slightly, which increases position error. Temperature itself has no effect on error in this model.

import random
import statistics

random.seed(4)
# Simulated, made-up data: 300 test runs of a robot arm.
# The payload drives BOTH motor temperature and position error.
# Temperature has NO effect on error in this model.
runs = []
for _ in range(300):
    payload = random.uniform(0.0, 5.0)                        # kg
    temp = 25 + 3.0 * payload + random.gauss(0, 1.5)          # °C
    error = 0.5 + 0.4 * payload + random.gauss(0, 0.3)        # mm
    runs.append((payload, temp, error))

temps = [t for _, t, _ in runs]
errors = [e for _, _, e in runs]
print(f"all runs:        r = {statistics.correlation(temps, errors):.2f}")

# Look only at runs with nearly the same payload
band = [(t, e) for p, t, e in runs if 2.0 <= p < 2.5]
r_band = statistics.correlation([t for t, _ in band], [e for _, e in band])
print(f"payload 2.0-2.5: r = {r_band:.2f}  ({len(band)} runs)")

fit = statistics.linear_regression(temps, errors)
print(f"slope: {fit.slope:.2f} mm per °C")

Output:

all runs:        r = 0.84
payload 2.0-2.5: r = 0.09  (27 runs)
slope: 0.12 mm per °C

Across all runs, temperature and error are strongly correlated, r = 0.84. A fitted line says error rises by about 0.12 mm per °C, which would suggest that cooling the motor by 10 °C cuts the error by over a millimetre. Yet we built the model, and we know temperature does nothing to error.

The payload is a confounder: a third factor that influences both quantities and makes them move together. When we look only at runs with nearly the same payload (2.0 to 2.5 kg), the correlation almost vanishes, r = 0.09. Holding the confounder roughly fixed reveals that, at a given payload, hotter runs are not worse.

Be careful with that last number too. It comes from only 27 runs, and small samples give noisy correlations: with other random seeds, the same band typically gives values anywhere from about −0.3 to +0.4. "Close to zero, with a lot of uncertainty" is the honest summary.

Ways a correlation can arise without the cause you expect

  1. Confounding: a third factor drives both, as with payload above. Classic non-engineering example: ice-cream sales and swimming accidents both rise in hot weather.
  2. Reverse causation: the effect runs the other way. A struggling joint might draw more current because it is fighting a position error, so the error heats the motor rather than the reverse.
  3. Chance: with few data points, or many pairs of quantities tested, some strong correlations appear by luck alone.
  4. Selection: if you only logged runs that triggered an alarm, you may have created a pattern that does not exist in all runs.

The controlled experiment

Stratifying by payload helped, but only because we thought of payload. There might be confounders nobody has thought of. The most powerful tool for establishing cause is the controlled experiment: you change the suspected cause, and you make sure nothing else changes along with it.

The key trick is randomisation. Decide by a coin flip whether each run gets extra heating. Then heating cannot be linked to payload, or to time of day, or to anything else, except by chance. Any difference in error between heated and unheated runs must be caused by the heat (or by luck, which we can estimate).

import random
import statistics

random.seed(2)
# Simulated controlled experiment (made-up model, same as before).
# A coin flip decides whether each run gets an extra 10 °C of heating,
# so heating is independent of payload.
heated, unheated = [], []
for _ in range(300):
    payload = random.uniform(0.0, 5.0)
    heat_on = random.random() < 0.5
    temp = 25 + 3.0 * payload + (10 if heat_on else 0) + random.gauss(0, 1.5)
    error = 0.5 + 0.4 * payload + random.gauss(0, 0.3)
    (heated if heat_on else unheated).append(error)

print(f"heated:   n = {len(heated)}, mean error = {statistics.mean(heated):.2f} mm")
print(f"unheated: n = {len(unheated)}, mean error = {statistics.mean(unheated):.2f} mm")

diff = statistics.mean(heated) - statistics.mean(unheated)
se = (statistics.variance(heated) / len(heated)
      + statistics.variance(unheated) / len(unheated)) ** 0.5
print(f"difference = {diff:.2f} mm, SE of difference = {se:.2f} mm")

Output:

heated:   n = 154, mean error = 1.48 mm
unheated: n = 146, mean error = 1.51 mm
difference = -0.02 mm, SE of difference = 0.07 mm

(The rounded means differ by 0.03 mm; the unrounded difference is about 0.02 mm.) The correlation suggested 10 °C of heat should add over a millimetre of error. The experiment finds a difference of −0.02 mm, much smaller than its standard error of 0.07 mm: no detectable effect. The fan would have been wasted money. What would actually help is a stiffer arm, or compensating for payload in the controller.

In real engineering you cannot always run the ideal experiment, but you can often get close: change one thing at a time, randomise the order of trials, and keep a log of everything else that might matter.

Recap

  • The correlation coefficient r measures how closely two quantities follow a straight line, from −1 to +1.
  • A strong correlation does not show that one quantity causes the other. Look for confounders, reverse causation, chance and selection.
  • Holding a suspected confounder fixed can expose a misleading correlation, but only for confounders you have thought of.
  • A randomised controlled experiment, where you change the suspected cause and nothing else, is the strongest way to establish cause.

Project

Build a confounder of your own

Write a Python simulation, with a fixed random seed, of a situation where a hidden factor creates a misleading correlation. Ideas: hours of daylight driving both outdoor temperature and solar-panel output; class size driving both noise level and the number of questions asked.

  1. Generate at least 200 made-up observations in which the hidden factor influences two measured quantities, but neither measured quantity affects the other.
  2. Print the correlation between the two measured quantities.
  3. Print the correlation within a narrow band of the hidden factor.
  4. Add a randomised "experiment" in which you change one measured quantity by a coin flip, and show the other does not change.
  5. Write a short paragraph, clearly labelled as describing simulated data, explaining what an analyst who never measured the hidden factor might wrongly conclude.

Deliverables

  • A Python script with a fixed seed and comments describing the model
  • Printed correlations for all data and for a narrow band
  • Printed results of the randomised experiment and a short explanatory paragraph

Knowledge check

Check your understanding

  1. 1. In the simulation, why were temperature and error strongly correlated even though temperature had no effect?
  2. 2. Which value of r indicates the strongest straight-line relationship?
  3. 3. Why does deciding by coin flip which runs get extra heating make the experiment trustworthy?
  4. 4. A joint draws more current whenever its position error is large. An engineer concludes high current causes the error. What alternative should they consider first?
  5. 5. Within the 2.0–2.5 kg payload band, r was 0.09 from 27 runs. What is the most honest summary?

Go further