导包
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
加载数据集
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
X.shape, y.shape
((70000, 784), (70000,))
原始数据集可视化
figure = plt.figure(figsize=(20, 20))
rows, cols = 8, 8
for i in range(1, rows * cols + 1):
# 随机选数据
# sample_idx = np.random.randint(0, len(X))
# img, label = X.values[sample_idx].reshape(28, 28), y[sample_idx]
# 按数据集的顺序选前几个数据
img, label = X.values[i - 1].reshape(28, 28), y[i - 1]
figure.add_subplot(rows, cols, i)
plt.title(label)
plt.axis('off')
plt.imshow(img, cmap='gray')
plt.show()
PCA压缩数据集
pca = PCA(n_components=154)
# pca = PCA(n_components=0.95) # 保留95%的方差,结果也是154个特征
X_reduced = pca.fit_transform(X) # 压缩
X_recovered = pca.inverse_transform(X_reduced) # 重构
重构后的图像
figure = plt.figure(figsize=(20, 20))
rows, cols = 8, 8
for i in range(1, rows * cols + 1):
# 随机选数据
# sample_idx = np.random.randint(0, len(X))
# img, label = X.values[sample_idx].reshape(28, 28), y[sample_idx]
# 按数据集的顺序选前几个数据
img, label = X_recovered[i - 1].reshape(28, 28), y[i - 1]
figure.add_subplot(rows, cols, i)
plt.title(label)
plt.axis('off')
plt.imshow(img, cmap='gray')
plt.show()
可以看到图像质量略有下降,但是数字仍然大部分保持完好。