Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Covariance and Correlation
Covariance asks whether two variables move together:
When both are above their means at the same time, the product is positive. When one is high while the other is low, it is negative. Add them up and you have the tendency.
The trouble with covariance is units. Height in centimetres against weight in kilograms gives a covariance in cm·kg, and switching to metres changes the number by a factor of 100 without changing the relationship at all. Correlation fixes that by dividing out both spreads:
Now 1 is a perfect straight line upward, −1 perfect downward, 0 no linear relationship — and that qualifier is load-bearing. y=x2 over a symmetric range has r=0 despite y being completely determined by x. Correlation only sees straight lines.
x = [1, 2, 3] y = [2, 4, 6] r = 1.0 (y is exactly 2x) x = [1, 2, 3] y = [6, 4, 2] r = -1.0
Your task:
Implement correlation(x, y) from the definition, returning r as a float. The n−1 cancels between numerator and denominator, but compute it honestly rather than relying on that.
Example Tests
A perfect straight line upward
Input: {"x":[1,2,3],"y":[2,4,6]}
Expected: 1
A perfect straight line downward
Input: {"x":[1,2,3],"y":[6,4,2]}
Expected: -1
A symmetric parabola is perfectly determined and yet uncorrelated
Input: {"x":[-2,-1,0,1,2],"y":[4,1,0,1,4]}
Expected: 0
import numpy as np
def correlation(x, y):
"""
Pearson correlation coefficient.
Args:
x: array of shape (n,)
y: array of shape (n,)
Returns:
float in [-1, 1]
"""
# YOUR CODE HERE
pass