Compute Covariance Matrix
Compute Covariance Matrix
Compute the covariance matrix from a dataset without using np.cov. The covariance matrix shows how features vary together and is fundamental to many ML algorithms.
Step 1: Center the Data
μ=mean(X,axis=0)Xcentered=X−μStep 2: Compute Covariance Matrix
Σ=N−11XcenteredTXcenteredWhere: X has shape (N, D), μ has shape (D,), Σ has shape (D, D)
Function Arguments
X: list[list[float]] | np.ndarray- Dataset with shape (N, D)
Examples
Input: X=[[1, 2], [2, 3], [3, 4]]
Output: [[1.0, 1.0], [1.0, 1.0]]
Input: X=[[1, 0], [0, 1]]
Output: [[0.5, -0.5], [-0.5, 0.5]]
Input: X=[[1, 2, 3]]
Output: None (only 1 sample)
Hint 1
Use np.asarray() to convert input and check shape with .shape and .ndim. Use np.mean() to compute feature means.
Hint 2
Center data by subtracting mean for matrix multiplication.
Hint 3
Divide by (N-1) for sample covariance and handle edge cases by returning None.
Requirements
- Return
np.ndarrayof shape (D, D) with covariance values - Return
Nonefor invalid input (N < 2 or not 2D) - Must be vectorized (no loops over data points)
- Cannot use
np.covfunction - Use sample covariance (divide by N-1, not N)
Constraints
- Dataset size: N ≤ 10,000, D ≤ 1,000
- Numerical precision: relative tolerance ≤ 1e-8
- Libraries: NumPy only
Try Similar Problems
Log in to take notes on this problem
Accepts: array
Compute Covariance Matrix
Compute Covariance Matrix
Compute the covariance matrix from a dataset without using np.cov. The covariance matrix shows how features vary together and is fundamental to many ML algorithms.
Step 1: Center the Data
μ=mean(X,axis=0)Xcentered=X−μStep 2: Compute Covariance Matrix
Σ=N−11XcenteredTXcenteredWhere: X has shape (N, D), μ has shape (D,), Σ has shape (D, D)
Function Arguments
X: list[list[float]] | np.ndarray- Dataset with shape (N, D)
Examples
Input: X=[[1, 2], [2, 3], [3, 4]]
Output: [[1.0, 1.0], [1.0, 1.0]]
Input: X=[[1, 0], [0, 1]]
Output: [[0.5, -0.5], [-0.5, 0.5]]
Input: X=[[1, 2, 3]]
Output: None (only 1 sample)
Hint 1
Use np.asarray() to convert input and check shape with .shape and .ndim. Use np.mean() to compute feature means.
Hint 2
Center data by subtracting mean for matrix multiplication.
Hint 3
Divide by (N-1) for sample covariance and handle edge cases by returning None.
Requirements
- Return
np.ndarrayof shape (D, D) with covariance values - Return
Nonefor invalid input (N < 2 or not 2D) - Must be vectorized (no loops over data points)
- Cannot use
np.covfunction - Use sample covariance (divide by N-1, not N)
Constraints
- Dataset size: N ≤ 10,000, D ≤ 1,000
- Numerical precision: relative tolerance ≤ 1e-8
- Libraries: NumPy only
Try Similar Problems
Log in to take notes on this problem
Accepts: array