import numpy as np
A = np.array([[90, 60, 90], [90, 90, 90], [60, 60, 60], [60, 60, 90], [30, 30, 30]])
m = len(A)
One = np.ones((m, 1))
One_Matrix = One.dot(One.T) # m*m ones matrix
Average = One_Matrix.dot(A)/m # calculate the average of each column
Average
a = A - Average # center data
CoV = a.T.dot(a)/m # n*n matrix, Co-variance
CoV
# bias, False, is normalized by (m - 1); True, is normalized by m
cov = np.cov(A.T, bias=True)
cov
from sklearn.datasets import make_gaussian_quantiles
real_cov = np.array([[.8, .3], [.3, .4]])
rng = np.random.RandomState(0)
X = rng.multivariate_normal(mean=[0, 0], cov=real_cov, size=500)
X_test = np.array([[-3, 1], [0, 0]])
import matplotlib.pyplot as plt
plt.figure(figsize=(9, 3.5))
plt.plot(X[:, 0], X[:, 1], "yo")
plt.plot(X_test[:, 0], X_test[:, 1], "bs")
from matplotlib.patches import Ellipse
cov = np.cov(X.T, bias=True)
def plot_ellipse(X, cov):
lambda_, v = np.linalg.eig(cov)
lambda_ = np.sqrt(lambda_)
ax = plt.subplot(111, aspect='equal')
ell = Ellipse(xy=(np.mean(X[:, 0]), np.mean(X[:, 1])),
width=lambda_[0]*2*2, height=lambda_[1]*2*2, # 2 sigma
angle=np.rad2deg(np.arccos(v[0, 0])), lw=4, edgecolor='r', facecolor='none')
ax.add_artist(ell)
plt.plot(X[:, 0], X[:, 1], "yo")
plt.show()
plot_ellipse(X, cov)
cov
from sklearn.covariance import EmpiricalCovariance
model = EmpiricalCovariance().fit(X)
model.covariance_
import warnings
warnings.filterwarnings('ignore')
np.exp(model.score(X_test[0])), np.exp(model.score(X_test[1])) # calcualte probabilities
model.location_ # estimated feature means
plot_ellipse(X, model.covariance_)
from sklearn.covariance import ShrunkCovariance
model = ShrunkCovariance().fit(X)
model.covariance_
np.exp(model.score(X_test[0])), np.exp(model.score(X_test[1])) # calcualte probabilities
model.location_
plot_ellipse(X, model.covariance_)
from sklearn.covariance import LedoitWolf
model = LedoitWolf().fit(X)
model.covariance_
np.exp(model.score(X_test[0])), np.exp(model.score(X_test[1])) # calcualte probabilities
model.location_
plot_ellipse(X, model.covariance_)
from sklearn.covariance import OAS
model = OAS().fit(X)
model.covariance_
np.exp(model.score(X_test[0])), np.exp(model.score(X_test[1])) # calcualte probabilities
model.location_
plot_ellipse(X, model.covariance_)
from sklearn.covariance import GraphicalLassoCV
model = GraphicalLassoCV()
model.fit(X)
model.covariance_
np.exp(model.score(X_test[0])), np.exp(model.score(X_test[1])) # calcualte probabilities
model.location_
plot_ellipse(X, model.covariance_)