Covariance Matrix: How Features Move Together

Linear AlgebraEasy+10 XP+10

Covariance Matrix: How Features Move Together

Variance describes how one feature spreads out. Covariance describes how two move together — positive if they rise together, negative if one rises as the other falls. Collect it for every pair and you get the covariance matrix.

1cov(i, j) = Σ (x[i] - mean[i]) * (x[j] - mean[j]) / (n - 1)

Task: write covariance_matrix(data), where data is a list of samples and each sample is a list of features. Return the features × features matrix, rounded to 4 decimal places.

  • Use the sample covariance — divide by n - 1, not n.
  • The diagonal holds each feature's own variance.
  • The matrix is symmetric.

This is the object PCA actually decomposes. Its eigenvectors are the directions the data varies along, and its eigenvalues are how much — which is why "do PCA" and "find the eigenvectors of the covariance matrix" describe the same procedure.

Examples

data = [[1.0, 2.0], [3.0, 6.0], [5.0, 10.0]]
returns [[4.0, 8.0], [8.0, 16.0]]
data = [[1.0], [2.0], [3.0], [4.0]]
returns [[1.6667]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run