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)
X: list[list[float]] | np.ndarray - Dataset with shape (N, D)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)
Use np.asarray() to convert input and check shape with .shape and .ndim. Use np.mean() to compute feature means.
Center data by subtracting mean for matrix multiplication.
Divide by (N-1) for sample covariance and handle edge cases by returning None.
np.ndarray of shape (D, D) with covariance valuesNone for invalid input (N < 2 or not 2D)np.cov functionSign in to take notes on this problem
Accepts: array
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)
X: list[list[float]] | np.ndarray - Dataset with shape (N, D)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)
Use np.asarray() to convert input and check shape with .shape and .ndim. Use np.mean() to compute feature means.
Center data by subtracting mean for matrix multiplication.
Divide by (N-1) for sample covariance and handle edge cases by returning None.
np.ndarray of shape (D, D) with covariance valuesNone for invalid input (N < 2 or not 2D)np.cov functionSign in to take notes on this problem
Accepts: array