All problems
Covariance Matrix from Data
Problem
Compute the sample covariance matrix of data, given as a list of samples (rows) with one feature per column, using the unbiased denominator n - 1:
C[i][j] = sum_k (x[k][i] - mean_i) * (x[k][j] - mean_j) / (n - 1)
Assume at least two samples.
Hint
Subtract column means first, then average outer products over n - 1.
Test cases
case 1
in: [[[1,2],[3,4],[5,6]]]
expected: [[4,4],[4,4]]
case 2
in: [[[1,2],[2,4],[3,6]]]
expected: [[1,2],[2,4]]
case 3
in: [[[1,0],[0,1]]]
expected: [[0.5,-0.5],[-0.5,0.5]]
case 4
in: [[[1,1],[2,2],[3,3]]]
expected: [[1,1],[1,1]]
Starter codePython
def covariance_matrix(data):
# Your code here
pass4 test cases · run your code against them in the editor