Skip to content

Instantly share code, notes, and snippets.

@DFoly
Last active February 23, 2019 17:33
Show Gist options
  • Select an option

  • Save DFoly/efb03b0a61bacaf16f67ef502c9b3507 to your computer and use it in GitHub Desktop.

Select an option

Save DFoly/efb03b0a61bacaf16f67ef502c9b3507 to your computer and use it in GitHub Desktop.
def calculate_mean_covariance(X, prediction, C):
d = X.shape[1]
labels = np.unique(prediction)
initial_means = np.zeros((C, d))
initial_cov = np.zeros((C, d, d))
initial_pi = np.zeros(C)
counter=0
for label in sorted(labels):
ids = np.where(prediction == label) # returns indices
initial_pi[counter] = len(ids[0]) / X.shape[0]
initial_means[counter,:] = np.mean(X[ids], axis = 0)
de_meaned = X[ids] - initial_means[counter,:]
Nk = X[ids].shape[0]
initial_cov[counter,:, :] = np.dot(initial_pi[counter] * de_meaned.T, de_meaned) / Nk
counter+=1
assert np.sum(initial_pi) == 1
return (initial_means, initial_cov, initial_pi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment