球形数据上的流形学习

Machine LearningMachine LearningBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

流形学习是机器学习的一个子领域,致力于学习高维数据的潜在结构。在本实验中,我们将在一个球形数据集上应用不同的流形学习技术。我们将使用降维来深入了解流形学习方法。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向Labby提问。课程结束后提供反馈,我们会及时为你解决问题。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/UtilitiesandDatasetsGroup -.-> sklearn/utils("Utilities") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/utils -.-> lab-49208{{"球形数据上的流形学习"}} ml/sklearn -.-> lab-49208{{"球形数据上的流形学习"}} end

导入库

我们将首先导入必要的库。我们会用到scikit-learn、matplotlib和numpy。

from time import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from sklearn import manifold
from sklearn.utils import check_random_state

import mpl_toolkits.mplot3d

创建球形数据集

接下来,我们将创建一个球形数据集。我们会创建一个球体,去掉两极,并沿着球体侧面切下一个薄片。这将使流形学习技术能够在将其投影到二维的同时“展开它”。

n_neighbors = 10
n_samples = 1000

random_state = check_random_state(0)
p = random_state.rand(n_samples) * (2 * np.pi - 0.55)
t = random_state.rand(n_samples) * np.pi

indices = (t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))
colors = p[indices]
x, y, z = (
    np.sin(t[indices]) * np.cos(p[indices]),
    np.sin(t[indices]) * np.sin(p[indices]),
    np.cos(t[indices]),
)

fig = plt.figure(figsize=(15, 8))
plt.suptitle(
    "Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14
)

ax = fig.add_subplot(251, projection="3d")
ax.scatter(x, y, z, c=p[indices], cmap=plt.cm.rainbow)
ax.view_init(40, -10)

sphere_data = np.array([x, y, z]).T

执行局部线性嵌入流形学习

现在我们将执行局部线性嵌入(Locally Linear Embedding,LLE)流形学习。LLE是一种强大的技术,它能够用少量样本展开复杂的流形。我们将使用LLE的四种变体并比较它们的结果。

methods = ["standard", "ltsa", "hessian", "modified"]
labels = ["LLE", "LTSA", "Hessian LLE", "Modified LLE"]

for i, method in enumerate(methods):
    t0 = time()
    trans_data = (
        manifold.LocallyLinearEmbedding(
            n_neighbors=n_neighbors, n_components=2, method=method
        )
     .fit_transform(sphere_data)
     .T
    )
    t1 = time()
    print("%s: %.2g sec" % (methods[i], t1 - t0))

    ax = fig.add_subplot(252 + i)
    plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
    plt.title("%s (%.2g sec)" % (labels[i], t1 - t0))
    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    plt.axis("tight")

执行等距映射(Isomap)流形学习

接下来,我们将执行等距映射(Isomap)流形学习。等距映射是一种非线性降维技术,它寻求数据的低维嵌入,同时保持所有点对之间的测地距离。

t0 = time()
trans_data = (
    manifold.Isomap(n_neighbors=n_neighbors, n_components=2)
  .fit_transform(sphere_data)
  .T
)
t1 = time()
print("%s: %.2g sec" % ("ISO", t1 - t0))

ax = fig.add_subplot(257)
plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
plt.title("%s (%.2g sec)" % ("Isomap", t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis("tight")

执行多维缩放(MDS)

现在我们将执行多维缩放(Multi-dimensional Scaling,MDS)流形学习。MDS是一种技术,它寻求数据的低维表示,其中点之间的距离与原始高维空间中的距离一致。

t0 = time()
mds = manifold.MDS(2, max_iter=100, n_init=1, normalized_stress="auto")
trans_data = mds.fit_transform(sphere_data).T
t1 = time()
print("MDS: %.2g sec" % (t1 - t0))

ax = fig.add_subplot(258)
plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
plt.title("MDS (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis("tight")

执行谱嵌入

接下来,我们将执行谱嵌入(Spectral Embedding)流形学习。谱嵌入是一种技术,它寻求数据的低维表示,这种表示能保留各点之间的成对距离。

t0 = time()
se = manifold.SpectralEmbedding(n_components=2, n_neighbors=n_neighbors)
trans_data = se.fit_transform(sphere_data).T
t1 = time()
print("Spectral Embedding: %.2g sec" % (t1 - t0))

ax = fig.add_subplot(259)
plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
plt.title("Spectral Embedding (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis("tight")

执行t分布随机邻域嵌入(t-SNE)

最后,我们将执行t分布随机邻域嵌入(t-distributed Stochastic Neighbor Embedding,t-SNE)流形学习。t-SNE是一种技术,它寻求数据的低维表示,这种表示能保留各点之间的局部距离。

t0 = time()
tsne = manifold.TSNE(n_components=2, random_state=0)
trans_data = tsne.fit_transform(sphere_data).T
t1 = time()
print("t-SNE: %.2g sec" % (t1 - t0))

ax = fig.add_subplot(2, 5, 10)
plt.scatter(trans_data[0], trans_data[1], c=colors, cmap=plt.cm.rainbow)
plt.title("t-SNE (%.2g sec)" % (t1 - t0))
ax.xaxis.set_major_formatter(NullFormatter())
ax.yaxis.set_major_formatter(NullFormatter())
plt.axis("tight")

plt.show()

总结

在本实验中,我们在一个球形数据集上应用了不同的流形学习技术。我们使用了局部线性嵌入(Locally Linear Embedding,LLE)、等距映射(Isomap)、多维缩放(Multi-dimensional Scaling,MDS)、谱嵌入和t分布随机邻域嵌入(t-distributed Stochastic Neighbor Embedding,t-SNE),以获得一些关于流形学习方法的直观认识。这些技术对于分析和可视化高维数据很有用。