Skip to content

Instantly share code, notes, and snippets.

@jojonki
Last active December 22, 2022 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jojonki/88bfd8130eec0552841b5db9550bda5a to your computer and use it in GitHub Desktop.
Save jojonki/88bfd8130eec0552841b5db9550bda5a to your computer and use it in GitHub Desktop.
A simple example of covariance matrix
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