瑞士卷和瑞士洞降维#

本 notebook 旨在比较两种流行的非线性降维技术,t 分布随机邻域嵌入 (t-SNE) 和局部线性嵌入 (LLE),在经典的瑞士卷数据集上的表现。然后,我们将探讨它们如何处理数据中添加的孔洞。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

瑞士卷#

我们首先生成瑞士卷数据集。

import matplotlib.pyplot as plt

from sklearn import datasets, manifold

sr_points, sr_color = datasets.make_swiss_roll(n_samples=1500, random_state=0)

现在,让我们来看看我们的数据

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection="3d")
fig.add_axes(ax)
ax.scatter(
    sr_points[:, 0], sr_points[:, 1], sr_points[:, 2], c=sr_color, s=50, alpha=0.8
)
ax.set_title("Swiss Roll in Ambient Space")
ax.view_init(azim=-66, elev=12)
_ = ax.text2D(0.8, 0.05, s="n_samples=1500", transform=ax.transAxes)
Swiss Roll in Ambient Space

计算 LLE 和 t-SNE 嵌入后,我们发现 LLE 似乎能相当有效地展开瑞士卷。另一方面,t-SNE 能够保留数据的总体结构,但却不能很好地表示原始数据的连续性。相反,它似乎不必要地将点群聚集在一起。

sr_lle, sr_err = manifold.locally_linear_embedding(
    sr_points, n_neighbors=12, n_components=2
)

sr_tsne = manifold.TSNE(n_components=2, perplexity=40, random_state=0).fit_transform(
    sr_points
)

fig, axs = plt.subplots(figsize=(8, 8), nrows=2)
axs[0].scatter(sr_lle[:, 0], sr_lle[:, 1], c=sr_color)
axs[0].set_title("LLE Embedding of Swiss Roll")
axs[1].scatter(sr_tsne[:, 0], sr_tsne[:, 1], c=sr_color)
_ = axs[1].set_title("t-SNE Embedding of Swiss Roll")
LLE Embedding of Swiss Roll, t-SNE Embedding of Swiss Roll

注意

LLE 似乎正在拉伸瑞士卷中心(紫色)的点。然而,我们观察到这仅仅是数据生成方式的副产品。卷的中心附近点密度更高,这最终影响了 LLE 在较低维度中重建数据的方式。

瑞士洞#

现在,让我们看看这两种算法如何处理我们在数据中添加一个孔洞的情况。首先,我们生成瑞士洞数据集并绘制它。

sh_points, sh_color = datasets.make_swiss_roll(
    n_samples=1500, hole=True, random_state=0
)

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection="3d")
fig.add_axes(ax)
ax.scatter(
    sh_points[:, 0], sh_points[:, 1], sh_points[:, 2], c=sh_color, s=50, alpha=0.8
)
ax.set_title("Swiss-Hole in Ambient Space")
ax.view_init(azim=-66, elev=12)
_ = ax.text2D(0.8, 0.05, s="n_samples=1500", transform=ax.transAxes)
Swiss-Hole in Ambient Space

计算 LLE 和 t-SNE 嵌入后,我们得到了与瑞士卷类似的结果。LLE 能够非常有效地展开数据,甚至保留了孔洞。t-SNE 再次将点群聚集在一起,但我们注意到它保留了原始数据的总体拓扑结构。

sh_lle, sh_err = manifold.locally_linear_embedding(
    sh_points, n_neighbors=12, n_components=2
)

sh_tsne = manifold.TSNE(
    n_components=2, perplexity=40, init="random", random_state=0
).fit_transform(sh_points)

fig, axs = plt.subplots(figsize=(8, 8), nrows=2)
axs[0].scatter(sh_lle[:, 0], sh_lle[:, 1], c=sh_color)
axs[0].set_title("LLE Embedding of Swiss-Hole")
axs[1].scatter(sh_tsne[:, 0], sh_tsne[:, 1], c=sh_color)
_ = axs[1].set_title("t-SNE Embedding of Swiss-Hole")
LLE Embedding of Swiss-Hole, t-SNE Embedding of Swiss-Hole

总结#

我们注意到 t-SNE 受益于测试更多参数组合。通过更好地调整这些参数,可能会获得更好的结果。

我们观察到,正如在“手写数字上的流形学习”示例中所见,t-SNE 在真实世界数据上通常比 LLE 表现更好。

脚本总运行时间: (0 分钟 16.853 秒)

相关示例

手写数字上的流形学习:局部线性嵌入、Isomap…-

手写数字上的流形学习:局部线性嵌入、Isomap...

流形学习方法比较

流形学习方法比较

层次聚类:结构化 vs 非结构化 Ward

层次聚类:结构化 vs 非结构化 Ward

截断球体上的流形学习方法

截断球体上的流形学习方法

由 Sphinx-Gallery 生成的画廊