高斯混合模型是一种混合模型,混合的基本分布是高斯分布
参考《统计学习方法》
高斯混合模型(Gaussian Mixture Model,GMM)是一种用于对数据进行建模的概率模型。它假设数据是由多个高斯分布(正态分布)组成的混合体,每个分布代表一个潜在的子群。GMM 在聚类、密度估计和异常检测等领域具有广泛的应用。
以下是一个使用 Python 的 scikit-learn
库实现 GMM 的示例代码:
首先,确保已安装 scikit-learn
库,可以通过以下命令安装:
1
| pip install scikit-learn
|
接下来,使用下面的代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import numpy as np import matplotlib.pyplot as plt from sklearn.mixture import GaussianMixture from sklearn.datasets import make_blobs
n_samples = 300 X, y_true = make_blobs(n_samples=n_samples, centers=3, cluster_std=1.0, random_state=42)
gmm = GaussianMixture(n_components=3, random_state=42)
gmm.fit(X)
y_pred = gmm.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=y_pred, s=40, cmap='viridis') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('GMM Clustering') plt.show()
|
在上述代码中,我们首先使用 make_blobs
函数生成一个示例数据集,用于演示 GMM 的聚类效果。然后,我们创建了一个 GMM 模型,指定了期望的分布数量(n_components
),并使用 fit
方法训练模型。最后,我们根据 GMM 模型的预测结果绘制了原始数据和聚类效果。
链接:浅显易懂的GMM模型及其训练过程