Last active
December 22, 2022 00:42
-
-
Save jojonki/88bfd8130eec0552841b5db9550bda5a to your computer and use it in GitHub Desktop.
A simple example of covariance matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
data = np.array([[40, 35, 80], | |
[80, 50, 90], | |
[20, 55, 40], | |
[94, 80, 88], | |
[90, 30, 100]]) | |
print('Input data (N, featuers):', data, data.shape) | |
N = data.shape[0] | |
n_dim = data.shape[1] | |
cov = np.zeros((n_dim, n_dim)) | |
# E(X) | |
avg = [] | |
for i in range(n_dim): | |
avg.append(sum([d[i] for d in data]) / N) | |
print('avg', avg) | |
# covariance matrix | |
for i in range(n_dim): | |
for j in range(n_dim): | |
var = 0 | |
for d in data: | |
var += (d[i] - avg[i]) * (d[j] - avg[j]) | |
var /= (N - 1) | |
cov[i, j] = var | |
print('cov', cov) | |
print('numpy cov', np.cov(data, rowvar=False, bias=False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment