Neural Mastery
← Practice
Sample Covariance Matrixmedium

Sample Covariance Matrix

medium Math for ML 15-20 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Compute the unbiased empirical sample covariance matrix from multidimensional observations.

Task

Implement sample_covariance_matrix(data): given an n x d matrix of observations (n rows, d columns), calculate the d x d sample covariance matrix using Bessel's correction Cov(j1, j2) = sum_i ((x_i,j1 - mu_j1)*(x_i,j2 - mu_j2)) / (n - 1). If n < 2, return all zeros. Round each entry to 4 decimals.

Function Signature

sample_covariance_matrix(data: list[list[float]]) -> list[list[float]]

Examples

Example 1: 2D Two Points
Input: data = [[1, 2], [3, 6]]
Output: [[2, 4], [4, 8]]
Explanation: Covariance with sample size 2.
Example 2: Uncorrelated Features
Input: data = [[1, 0], [0, 1], [-1, 0], [0, -1]]
Output: [[0.6667, 0], [0, 0.6667]]
Explanation: Symmetric zero covariance off-diagonals.

Constraints

  • data has shape n x d with 2 <= n <= 100, 1 <= d <= 20.
Python3Saved ✓
def sample_covariance_matrix(data: list[list[float]]) -> list[list[float]]:
"""Compute d x d sample covariance matrix from n x d data matrix with denominator (n - 1).
Return d x d matrix rounded to 4 decimals."""
# Your implementation here
pass

Case 1: 2D Two Points
Input: data = [[1, 2], [3, 6]]
Expected: [[2, 4], [4, 8]]
Case 2: Uncorrelated Features
Input: data = [[1, 0], [0, 1], [-1, 0], [0, -1]]
Expected: [[0.6667, 0], [0, 0.6667]]