CodeBlanks Logo Icon CodeBlanks

Correlation

Correlation shows the strength of the relationship between two variables.

Correlation

Pearson correlation measures the linear relationship of two variables between -1 and 1: 1 is perfectly positive, -1 perfectly negative, 0 no linear relationship.

boy = np.array([160, 170, 180, 190])
kilo = np.array([55, 65, 72, 85])
print(np.corrcoef(boy, kilo)[0, 1])   # 0.99...

np.corrcoef returns a matrix; the diagonal is always 1 and [0, 1] is the value between the two variables.

Limits of correlation

Correlation only captures linear relationships. For a symmetric relationship like y = x², the correlation can be 0 even though there is full dependence:

x = np.array([-2, -1, 0, 1, 2])
print(np.corrcoef(x, x ** 2)[0, 1])   # 0.0

Correlation also isn't causation: ice-cream sales and drownings rise together because both are caused by hot weather.

Practice Compute the correlation

Compute the correlation between calisma (hours) and not_ with np.corrcoef, round it to 3 digits and print it.

Starter code

model.py
import numpy as np

calisma = np.array([1, 2, 3, 4, 5])
not_ = np.array([50, 55, 65, 70, 80])

# buraya yaz

Sample solution

model.py
import numpy as np

calisma = np.array([1, 2, 3, 4, 5])
not_ = np.array([50, 55, 65, 70, 80])

r = np.corrcoef(calisma, not_)[0, 1]
print(round(r, 3))

Expected output

0.993

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What can be said if the correlation is -0.95?

  • There is a weak positive relationship
  • As one rises, the other falls strongly Correct answer
  • There is no relationship
  • One causes the other

Explanation: The sign gives the direction, the magnitude the strength; correlation doesn't prove causation.

2 Take the correlation between the two variables.

Question
r = np.corrcoef(a, b)[____]
Answer
r = np.corrcoef(a, b)[0, 1]

Explanation: The off-diagonal element is the correlation of the two variables.

3 Match the values with their meanings.

Term Meaning
1 Perfect positive linear
-1 Perfect negative linear
0 No linear relationship
0.3 Weak positive

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation