高维数据的特征凝聚

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/DataPreprocessingandFeatureEngineeringGroup(["Data Preprocessing and Feature Engineering"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/feature_extraction("Feature Extraction") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/feature_extraction -.-> lab-49105{{"高维数据的特征凝聚"}} ml/sklearn -.-> lab-49105{{"高维数据的特征凝聚"}} end

导入库

在这一步中,我们将导入执行特征凝聚所需的库。

import numpy as np
import matplotlib.pyplot as plt

from sklearn import datasets, cluster
from sklearn.feature_extraction.image import grid_to_graph

加载数据集

在这一步中,我们将从scikit-learn中加载数字数据集。该数据集包含0到9的手写数字图像。

digits = datasets.load_digits()
images = digits.images
X = np.reshape(images, (len(images), -1))

定义连接矩阵

在这一步中,我们将使用scikit-learn中的grid_to_graph函数定义连接矩阵。此函数基于图像的像素网格创建一个连接图。

connectivity = grid_to_graph(*images[0].shape)

执行特征凝聚

在这一步中,我们将使用scikit-learn中的FeatureAgglomeration类执行特征凝聚。我们将把聚类数量设置为32。

agglo = cluster.FeatureAgglomeration(connectivity=connectivity, n_clusters=32)
agglo.fit(X)
X_reduced = agglo.transform(X)

逆变换

在这一步中,我们将对降维后的数据集执行逆变换,以恢复原始的特征数量。

X_restored = agglo.inverse_transform(X_reduced)
images_restored = np.reshape(X_restored, images.shape)

可视化结果

在这一步中,我们将可视化原始图像、凝聚后的图像以及分配给每个聚类的标签。

plt.figure(1, figsize=(4, 3.5))
plt.clf()
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.91)
for i in range(4):
    plt.subplot(3, 4, i + 1)
    plt.imshow(images[i], cmap=plt.cm.gray, vmax=16, interpolation="nearest")
    plt.xticks(())
    plt.yticks(())
    if i == 1:
        plt.title("Original data")
    plt.subplot(3, 4, 4 + i + 1)
    plt.imshow(images_restored[i], cmap=plt.cm.gray, vmax=16, interpolation="nearest")
    if i == 1:
        plt.title("Agglomerated data")
    plt.xticks(())
    plt.yticks(())

plt.subplot(3, 4, 10)
plt.imshow(
    np.reshape(agglo.labels_, images[0].shape),
    interpolation="nearest",
    cmap=plt.cm.nipy_spectral,
)
plt.xticks(())
plt.yticks(())
plt.title("Labels")
plt.show()

总结

在本教程中,我们学习了如何使用特征凝聚来合并数据集中的相似特征。通过减少特征数量,我们可以在保留数据集中最重要信息的同时,提高机器学习算法的性能。