补全代码,使用 PCA 对MNIST的数据降维到2维 做一下KMeans并显示: import numpy as np from sklearn.datasets import fetch_openml # Load data from https://www.openml.org/d/554 X, y = fetch_openml("mnist_784", version=1, return_X_y=True, as_frame=False) print(X.shape,y.shape) #(70000, 784) (70000,) print(np.unique(y)) ##可只选择前10000条数据做实验 X=X[:10000] y=y[:10000]
时间: 2024-01-09 07:03:18 浏览: 176
```python
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# Load data from https://www.openml.org/d/554
X, y = fetch_openml("mnist_784", version=1, return_X_y=True, as_frame=False)
# Print the shape of X and y
print(X.shape, y.shape) #(70000, 784) (70000,)
# Print the unique values of y
print(np.unique(y))
# Select the first 10000 samples for experiment
X = X[:10000]
y = y[:10000]
# Perform PCA to reduce dimensionality to 2
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
# Perform KMeans clustering on the reduced data
kmeans = KMeans(n_clusters=10)
kmeans.fit(X_pca)
# Plot the clustered data
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=kmeans.labels_, cmap='viridis')
plt.title('KMeans Clustering on MNIST Data')
plt.show()
```
阅读全文