python利用PCA实现minist数据集的可视化
时间: 2023-11-06 17:04:43 浏览: 99
首先,我们需要导入需要的库:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
```
然后,我们可以使用 `fetch_openml` 函数来获取 `minist` 数据集:
```python
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
```
接下来,我们可以使用 PCA 来将数据集降维到二维,然后将结果可视化:
```python
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='jet')
plt.colorbar()
plt.show()
```
这里,我们将 `n_components` 设置为 2,表示将数据集降到二维。然后,我们将降维后的数据集可视化,其中颜色表示数字的类别,颜色映射使用了 `jet`。
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='jet')
plt.colorbar()
plt.show()
```
阅读全文
相关推荐













