简介
在本实验中,我们将学习如何使用信息论标准,通过高斯混合模型(Gaussian Mixture Models,GMM)进行模型选择。模型选择涉及模型的协方差类型和组件数量。我们将使用赤池信息准则(Akaike Information Criterion,AIC)和贝叶斯信息准则(Bayes Information Criterion,BIC)来选择最佳模型。我们将通过对标准正态分布进行随机采样来生成两个组件。一个组件保持球形,但进行了平移和重新缩放。另一个组件则变形为具有更一般的协方差矩阵。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟,以便 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
数据生成
我们通过对 numpy.random.randn 返回的标准正态分布进行随机采样,生成两个组件(每个组件包含 n_samples 个样本)。一个组件保持球形,但进行了平移和重新缩放。另一个组件则变形为具有更一般的协方差矩阵。
import numpy as np
n_samples = 500
np.random.seed(0)
C = np.array([[0.0, -0.1], [1.7, 0.4]])
component_1 = np.dot(np.random.randn(n_samples, 2), C) ## 一般
component_2 = 0.7 * np.random.randn(n_samples, 2) + np.array([-4, 1]) ## 球形
X = np.concatenate([component_1, component_2])
可视化
我们可以使用 Matplotlib 来可视化不同的组件。
import matplotlib.pyplot as plt
plt.scatter(component_1[:, 0], component_1[:, 1], s=0.8)
plt.scatter(component_2[:, 0], component_2[:, 1], s=0.8)
plt.title("Gaussian Mixture components")
plt.axis("equal")
plt.show()
模型训练与选择
我们将组件数量从 1 变化到 6,并改变要使用的协方差参数类型:
- “full”:每个组件都有自己的通用协方差矩阵。
- “tied”:所有组件共享相同的通用协方差矩阵。
- “diag”:每个组件都有自己的对角协方差矩阵。
- “spherical”:每个组件都有自己的单一方差。
我们对不同的模型进行评分,并保留最佳模型(最低的 BIC)。这是通过使用GridSearchCV和一个用户定义的评分函数来完成的,该函数返回负的 BIC 分数。最佳参数集和估计器分别存储在best_parameters_和best_estimator_中。
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import GridSearchCV
def gmm_bic_score(estimator, X):
"""Callable to pass to GridSearchCV that will use the BIC score."""
## Make it negative since GridSearchCV expects a score to maximize
return -estimator.bic(X)
param_grid = {
"n_components": range(1, 7),
"covariance_type": ["spherical", "tied", "diag", "full"],
}
grid_search = GridSearchCV(
GaussianMixture(), param_grid=param_grid, scoring=gmm_bic_score
)
grid_search.fit(X)
绘制 BIC 分数
我们根据网格搜索进行的交叉验证结果创建一个pandas.DataFrame。我们将 BIC 分数的符号重新取反,以展示最小化它的效果。我们使用seaborn来绘制 BIC 分数。
import pandas as pd
import seaborn as sns
df = pd.DataFrame(grid_search.cv_results_)[
["param_n_components", "param_covariance_type", "mean_test_score"]
]
df["mean_test_score"] = -df["mean_test_score"]
df = df.rename(
columns={
"param_n_components": "组件数量",
"param_covariance_type": "协方差类型",
"mean_test_score": "BIC 分数"
}
)
df.sort_values(by="BIC 分数").head()
sns.catplot(
data=df,
kind="bar",
x="组件数量",
y="BIC 分数",
hue="协方差类型"
)
plt.show()
绘制最佳模型
我们绘制一个椭圆来展示所选模型的每个高斯组件。为此,需要找到由covariances_属性返回的协方差矩阵的特征值。这些矩阵的形状取决于covariance_type:
- “full”:(
n_components,n_features,n_features) - “tied”:(
n_features,n_features) - “diag”:(
n_components,n_features) - “spherical”:(
n_components,)
from matplotlib.patches import Ellipse
from scipy import linalg
color_iter = sns.color_palette("tab10", 2)[::-1]
Y_ = grid_search.predict(X)
fig, ax = plt.subplots()
for i, (mean, cov, color) in enumerate(
zip(
grid_search.best_estimator_.means_,
grid_search.best_estimator_.covariances_,
color_iter,
)
):
v, w = linalg.eigh(cov)
if not np.any(Y_ == i):
continue
plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], 0.8, color=color)
angle = np.arctan2(w[0][1], w[0][0])
angle = 180.0 * angle / np.pi ## convert to degrees
v = 2.0 * np.sqrt(2.0) * np.sqrt(v)
ellipse = Ellipse(mean, v[0], v[1], angle=180.0 + angle, color=color)
ellipse.set_clip_box(fig.bbox)
ellipse.set_alpha(0.5)
ax.add_artist(ellipse)
plt.title(
f"Selected GMM: {grid_search.best_params_['covariance_type']} model, "
f"{grid_search.best_params_['n_components']} components"
)
plt.axis("equal")
plt.show()
总结
在本实验中,我们学习了如何使用信息论标准,通过高斯混合模型(GMM)进行模型选择。我们使用赤池信息准则(AIC)和贝叶斯信息准则(BIC)来选择最佳模型。我们通过对标准正态分布进行随机采样生成了两个组件。一个组件保持球形,但进行了平移和重新缩放。另一个组件则进行了变形,以具有更一般的协方差矩阵。我们可视化了不同的组件,训练并选择了最佳模型,绘制了 BIC 分数,并绘制了最佳模型。