Compute the Pearson correlation matrix from a dataset without using np.corrcoef. Correlation measures linear relationships between features, normalized by their standard deviations.
Pearson Correlation Formula:
ρij=σiσjCov(Xi,Xj)Matrix Form:
R=σσTΣWhere: Σ = covariance matrix, σ = vector of standard deviations, R = correlation matrix
X: list[list[float]] | np.ndarray - Dataset with shape (N, D)Input: X=[[1, 2], [2, 4], [3, 6]]
Output: [[1.0, 1.0], [1.0, 1.0]] (perfect correlation)
Input: X=[[1, 6], [2, 4], [3, 2]]
Output: [[1.0, -1.0], [-1.0, 1.0]] (perfect negative correlation)
Input: X=[[1, 5], [2, 5], [3, 5]]
Output: [[1.0, NaN], [NaN, 1.0]] (zero variance in feature 2)
Start by computing the covariance matrix. Center data with X - np.mean() then use matrix multiplication.
Compute standard deviations with np.std(). Use np.outer() to create the denominator matrix.
Handle zero variance features by checking std_devs == 0. Set correlations involving these features to NaN, but keep diagonal as 1.0.
np.ndarray of shape (D, D) with correlation valuesNone for invalid input (N < 2 or not 2D)np.corrcoef functionSign in to take notes on this problem
Accepts: array
Compute the Pearson correlation matrix from a dataset without using np.corrcoef. Correlation measures linear relationships between features, normalized by their standard deviations.
Pearson Correlation Formula:
ρij=σiσjCov(Xi,Xj)Matrix Form:
R=σσTΣWhere: Σ = covariance matrix, σ = vector of standard deviations, R = correlation matrix
X: list[list[float]] | np.ndarray - Dataset with shape (N, D)Input: X=[[1, 2], [2, 4], [3, 6]]
Output: [[1.0, 1.0], [1.0, 1.0]] (perfect correlation)
Input: X=[[1, 6], [2, 4], [3, 2]]
Output: [[1.0, -1.0], [-1.0, 1.0]] (perfect negative correlation)
Input: X=[[1, 5], [2, 5], [3, 5]]
Output: [[1.0, NaN], [NaN, 1.0]] (zero variance in feature 2)
Start by computing the covariance matrix. Center data with X - np.mean() then use matrix multiplication.
Compute standard deviations with np.std(). Use np.outer() to create the denominator matrix.
Handle zero variance features by checking std_devs == 0. Set correlations involving these features to NaN, but keep diagonal as 1.0.
np.ndarray of shape (D, D) with correlation valuesNone for invalid input (N < 2 or not 2D)np.corrcoef functionSign in to take notes on this problem
Accepts: array