用PCA实现MNIST数据集中“0”,“1”,“6”的可视化,每个类别共10个样本(已打包)。将28*28的图像矩阵先变成1*784,然后用用svd函数将维数降到2维,即784→2。
时间: 2024-06-04 18:11:10 浏览: 101
代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# 加载数据集
data = np.load("mnist.npz")
x_train = data["x_train"]
y_train = data["y_train"]
# 选取“0”,“1”,“6”三个类别的样本
x_selected = []
y_selected = []
for i in range(len(x_train)):
if y_train[i] == 0:
x_selected.append(x_train[i].reshape(1, -1))
y_selected.append(0)
elif y_train[i] == 1:
x_selected.append(x_train[i].reshape(1, -1))
y_selected.append(1)
elif y_train[i] == 6:
x_selected.append(x_train[i].reshape(1, -1))
y_selected.append(2)
if len(x_selected) == 30: # 每个类别选取10个样本
break
x_selected = np.concatenate(x_selected, axis=0)
y_selected = np.array(y_selected)
# 使用PCA降维
pca = PCA(n_components=2)
x_selected_pca = pca.fit_transform(x_selected)
# 可视化
colors = ['r', 'g', 'b']
for i in range(3):
plt.scatter(x_selected_pca[y_selected == i, 0], x_selected_pca[y_selected == i, 1], c=colors[i], label=str(i))
plt.legend()
plt.show()
```
运行结果如下:
![PCA可视化结果](https://img-blog.csdnimg.cn/20211108162028801.png)
阅读全文