Skip to content
DeepForgeby svx
All problems
HardML Fundamentalsml-042

Covariance Matrix

Problem

Compute the population covariance matrix of X (n rows, d columns): subtract the column means, then set entry (a, b) to (1/n) * sum_i centered[i][a] * centered[i][b].

Return a d x d matrix (divide by n, not n-1). Empty input returns [].

Hint

Cov(a, b) is the mean product of the centered columns a and b.

Test cases

case 1
in: [[[1,2],[3,4],[5,6]]]
expected: [[2.6666666666666665,2.6666666666666665],[2.6666666666666665,2.6666666666666665]]
case 2
in: [[[0,1],[1,0],[0,-1],[-1,0]]]
expected: [[0.5,0],[0,0.5]]
case 3
in: [[[2,0],[0,2]]]
expected: [[1,-1],[-1,1]]
case 4
in: [[[1],[2],[3]]]
expected: [[0.6666666666666666]]
Starter codePython
def covariance_matrix(X):
    # Your code here
    pass

4 test cases · run your code against them in the editor