使用GMM的Pairplot:可视化高维数据和聚类

本示例展示了如何使用pairplot_with_gmm函数来可视化高维数据。这个函数特别有用,因为如果我们想要对高维数据进行聚类或了解其几何结构,我们可以调用此函数并利用其能力进行数据的每一维度的成对比较,以及通过GMM协方差绘制的椭圆进行GMM聚类。

[1]:
import graspologic

import numpy as np
import seaborn as sns
%matplotlib inline
/home/runner/.cache/pypoetry/virtualenvs/graspologic-pkHfzCJ8-py3.10/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

使用随机块模型模拟二值图

3块模型在下一个单元格中定义如下。

因此,前50个顶点属于块1,接下来的50个顶点属于块2,最后50个顶点属于块3。

[2]:
from graspologic.simulations import sbm

n_communities = [50, 50, 50]
p = [[0.5, 0.1, 0.05],
     [0.1, 0.4, 0.15],
     [0.05, 0.15, 0.3],]

np.random.seed(2)
A = sbm(n_communities, p)

使用邻接谱嵌入来获得图的低维表示

嵌入维度是自动选择的。它应该嵌入到3个维度。

[3]:
from graspologic.embed import AdjacencySpectralEmbed

ase = AdjacencySpectralEmbed()
X = ase.fit_transform(A)

print(X.shape)
(150, 3)

使用 pairplot_with_gmm 绘制带有椭圆的嵌入数据

首先,我们生成与块对应的标签。我们将这些标签与数据一起传递,以创建一个配对图,其中包含由GMM估计的椭圆,覆盖数据的每个组成部分。

[4]:
import warnings
warnings.filterwarnings('ignore')

from graspologic.plot import pairplot_with_gmm
from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=3, covariance_type='full').fit(X)
graph = pairplot_with_gmm(X, gmm, labels = None, cluster_palette = None,  label_palette = None)
../../_images/tutorials_plotting_pairplot_with_gmm_7_0.png

如果你想为你的椭圆指定特定的颜色,你可以按照以下步骤操作。请注意,由于我们正在分配聚类分配编号(在这种情况下为0、1、2),因此以下图表中的聚类颜色不一定与基础散点的颜色相匹配。这是因为GMM不会以任何特定顺序标记聚类,从而导致颜色的排列。

[5]:
import warnings
warnings.filterwarnings('ignore')

from sklearn.mixture import GaussianMixture
gmm = GaussianMixture(n_components=3, covariance_type='full').fit(X)
labels = ['Block 1'] * 50 + ['Block 2'] * 50 + ['Block 3'] * 50
#we need 2*n_components to get two differnt colors for labels and clusters but from same palette
color = sns.color_palette("Set1", 2*3)
cluster_palette = {0: color[0], 1:color[1], 2: color[2]}
label_palette = {"Block 1": color[3], 'Block 2':color[4], 'Block 3': color[5]}
graph = pairplot_with_gmm(X, gmm, labels = labels, cluster_palette = cluster_palette,  label_palette = label_palette)
../../_images/tutorials_plotting_pairplot_with_gmm_9_0.png