简介
在本实验中,我们将学习高斯混合模型(Gaussian Mixture Models,GMM)的不同初始化方法。我们将使用 scikit-learn 库生成样本数据并可视化聚类结果。初始化参数init_param有四种不同的方法:kmeans(默认)、random、random_from_data和k-means++。
虚拟机提示
虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会立即为你解决问题。
导入库并生成样本数据
我们将首先导入必要的库,并使用 scikit-learn 中的make_blobs函数生成一些样本数据。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.mixture import GaussianMixture
from sklearn.utils.extmath import row_norms
from sklearn.datasets._samples_generator import make_blobs
from timeit import default_timer as timer
## 生成一些数据
X, y_true = make_blobs(n_samples=4000, centers=4, cluster_std=0.60, random_state=0)
X = X[:, ::-1]
n_samples = 4000
n_components = 4
x_squared_norms = row_norms(X, squared=True)
定义一个获取初始均值的函数
接下来,我们将定义一个函数get_initial_means,它以样本数据、初始化方法和随机状态作为输入,并返回初始化均值。
def get_initial_means(X, init_params, r):
## 运行一个 max_iter=0 的高斯混合模型以输出初始化均值
gmm = GaussianMixture(
n_components=4, init_params=init_params, tol=1e-9, max_iter=0, random_state=r
).fit(X)
return gmm.means_
绘制样本数据和初始化中心
现在,我们将使用不同颜色绘制每种初始化方法的样本数据和初始化中心。我们还将计算初始化所需的时间以及高斯混合模型(GMM)收敛所需的迭代次数。
methods = ["kmeans", "random_from_data", "k-means++", "random"]
colors = ["navy", "turquoise", "cornflowerblue", "darkorange"]
times_init = {}
relative_times = {}
plt.figure(figsize=(4 * len(methods) // 2, 6))
plt.subplots_adjust(
bottom=0.1, top=0.9, hspace=0.15, wspace=0.05, left=0.05, right=0.95
)
for n, method in enumerate(methods):
r = np.random.RandomState(seed=1234)
plt.subplot(2, len(methods) // 2, n + 1)
start = timer()
ini = get_initial_means(X, method, r)
end = timer()
init_time = end - start
gmm = GaussianMixture(
n_components=4, means_init=ini, tol=1e-9, max_iter=2000, random_state=r
).fit(X)
times_init[method] = init_time
for i, color in enumerate(colors):
data = X[gmm.predict(X) == i]
plt.scatter(data[:, 0], data[:, 1], color=color, marker="x")
plt.scatter(
ini[:, 0], ini[:, 1], s=75, marker="D", c="orange", lw=1.5, edgecolors="black"
)
relative_times[method] = times_init[method] / times_init[methods[0]]
plt.xticks(())
plt.yticks(())
plt.title(method, loc="left", fontsize=12)
plt.title(
"Iter %i | Init Time %.2fx" % (gmm.n_iter_, relative_times[method]),
loc="right",
fontsize=10,
)
plt.suptitle("GMM iterations and relative time taken to initialize")
plt.show()
解释结果
从图中我们可以看出,k-means++ 在初始化时间短和高斯混合模型收敛所需的迭代次数少这两方面都表现出色。当使用random_from_data或random进行初始化时,模型需要更多的迭代次数才能收敛。与kmeans相比,所有这三种替代方法的初始化时间都更短。
总结
在本实验中,我们了解了高斯混合模型(GMM)的不同初始化方法,以及如何使用 scikit-learn 库中的这些方法对样本数据进行聚类。我们绘制了每种初始化方法的样本数据和初始化中心,并对结果进行了解释。