高斯混合模型GMM
首先介绍高斯分布的概率密度函数。一维高斯分布的概率密度函数如下:
多维变量X=(x1,x2,…xn)的联合概率密度函数为:
这里引用李航《统计学习方法》书中的定义
简而言之,GMM是多个高斯分布的加权和,并且权重α之和等于1 。
Sklearn
sklearn.mixture 是一个应用高斯混合模型进行非监督学习的包(支持 diagonal,spherical,tied,full 四种协方差矩阵)。GaussianMixture 对象实现了用来拟合高斯混合模型的期望最大 (EM) 算法。它还可以为多变量模型绘制置信椭圆体,同时计算 BIC(Bayesian Information Criterion,贝叶斯信息准则)来评估数据中聚类的数量。详情见Sklearn中文官网2.1. 高斯混合模型。
期望最大算法EM
这里引用周志华《机器学习》书中的定义
上面是基本概念。关于数学公式推导,真心建议直接看吴恩达老师的课件。这里给出自己推导的结果
示例演示
演示GMM的使用。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from sklearn import mixture
n_samples = 300
# generate random sample, two components
np.random.seed(0)
# generate spherical data centered on (20, 20)
shifted_gaussian = np.random.randn(n_samples, 2) + np.array([20, 20])
# generate zero centered stretched Gaussian data
C = np.array([[0., -0.7], [3.5, .7]])
stretched_gaussian = np.dot(np.random.randn(n_samples, 2), C)
# concatenate the two datasets into the final training set
X_train = np.vstack([shifted_gaussian, stretched_gaussian])
# fit a Gaussian Mixture Model with two components
clf = mixture.GaussianMixture(n_components=2, covariance_type='full')
clf.fit(X_train)
# display predicted scores by the model as a contour plot
x = np.linspace(-20., 30.)
y = np.linspace(-20., 40.)
X, Y = np.meshgrid(x, y)
XX = np.array([X.ravel(), Y.ravel()]).T
Z = -clf.score_samples(XX)
Z = Z.reshape(X.shape)
CS = plt.contour(X, Y, Z, norm=LogNorm(vmin=1.0, vmax=1000.0),
levels=np.logspace(0, 3, 10))
CB = plt.colorbar(CS, shrink=0.8, extend='both')
plt.scatter(X_train[:, 0], X_train[:, 1], .8)
plt.title('Negative log-likelihood predicted by a GMM')
plt.axis('tight')
plt.show()