如有错误,恳请指出。
以下内容将使用一个非常经典的手写数字数据集来进行降维与可视化展示。在原始的数据中,手写数字的维度是64,因为其像素表示是64,以下内容将分别使用不同的算法对其降维到2~3维并展示。所以分别可以实现2D可视化展示降维效果与3D可视化降维效果。
文章目录
首先导入必要的工具包:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
1. t-SNE降维效果
1.1 2D可视化
from sklearn import datasets
from sklearn import preprocessing
from sklearn.manifold import TSNE
# 数据集导入
X, y = datasets.load_digits(return_X_y=True)
# t-SNE降维处理
tsne = TSNE(n_components=2, verbose=1 ,random_state=42)
result = tsne.fit_transform(X)
# 归一化处理
scaler = preprocessing.MinMaxScaler(feature_range=(-1,1))
result = scaler.fit_transform(result)
# 颜色设置
color = ['#FFFAFA', '#BEBEBE', '#000080', '#87CEEB', '#006400',
'#00FF00', '#4682B4', '#D02090', '#8B7765', '#B03060']
# 可视化展示
plt.figure(figsize=(10, 10))
plt.title('t-SNE process')
# plt.xlim((-1.1, 1.1))
# plt.ylim((-1.1, 1.1))
# for i in range(len(result)):
# plt.text(result[i,0], result[i,1], str(y[i]),
# color=color[y[i]], fontdict={'weight': 'bold', 'size': 9})
plt.scatter(result[:,0], result[:,1], c=y, s=10)
输出:
[t-SNE] Computing 91 nearest neighbors...
[t-SNE] Indexed 1797 samples in 0.000s...
[t-SNE] Computed neighbors for 1797 samples in 0.116s...
[t-SNE] Computed conditional probabilities for sample 1000 / 1797
[t-SNE] Computed conditional probabilities for sample 1797 / 1797
[t-SNE] Mean sigma: 11.585657
[t-SNE] KL divergence after 250 iterations with early exaggeration: 61.555897
[t-SNE] KL divergence after 1000 iterations: 0.743767

1.2 3D可视化
from sklearn.manifold import TSNE
from sklearn import preprocessing
from sklearn import datasets
# 导入数据
X, y = datasets.load_digits(return_X_y=True)
# t-SNE降维处理
tsne = TSNE(n_components=3, verbose=1 ,random_state=42)
result = tsne.fit_transform(X)
# 归一化处理
scaler = preprocessing.MinMaxScaler(feature_range=(-1,1))
result = scaler.fit_transform(result)
# 3D可视化展示
fig = plt.figure(figsize=(14, 14))
ax = fig.add_subplot(projection='3d')
ax.set_title('t-SNE process')
ax.scatter(result[:,0], result[:,1], result[:,2

本文通过使用t-SNE、PCA、KernelPCA和MDS等降维算法,对手写数字数据集进行2D和3D可视化展示。t-SNE在降维效果上表现出色,能清晰地呈现数据分布。PCA和KernelPCA作为线性方法,可能丢失非线性结构信息,而MDS和SpectralEmbedding则在保留非线性结构方面有一定优势。降维选择应考虑时间成本和效果平衡,并注意数据预处理和目的明确。
最低0.47元/天 解锁文章
&spm=1001.2101.3001.5002&articleId=124603643&d=1&t=3&u=b277464b33cf464199c5578d159c031d)
171





