from sklearn.decomposition import PCA from sklearn.cluster import KMeans from sklearn.metrics import accuracy_score import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data import datetime # 导入数据集 start = datetime.datetime.now() #计算程序运行时间 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) X_train = mnist.train.images y_train = mnist.train.labels X_test = mnist.test.images y_test = mnist.test.labels #PCA降维 pca = PCA(n_components=10) X_train_pca = pca.fit_transform(X_train) X_test_pca = pca.fit_transform(X_test) # 可视化 plt.scatter(X_train_pca[:, 0], X_train_pca[:, 1], c=np.argmax(y_train, axis=1)) plt.show() # K-means聚类 kmeans_centers = [] # 用于存储初始类中心 for i in range(10): idx = np.where(np.argmax(y_train, axis=1) == i)[0] # 获取第i类数字的索引列表 sample_idx = np.random.choice(idx) # 随机指定一个样本作为初始类中心 kmeans_centers.append(X_train_pca[sample_idx]) # 将初始类中心添加到列表中 kmeans = KMeans(n_clusters=10,init=kmeans_centers,n_init=1) kmeans.fit(X_train_pca) # 计算分类错误率 y_pred = kmeans.predict(X_test_pca) acc = accuracy_score(np.argmax(y_test, axis=1), y_pred) print("分类错误率:{:.2%}".format(1-acc)) # 计算程序运行时间 end = datetime.datetime.now() print("程序运行时间为:"+str((end-start).seconds)+"秒")优化这段代码,输出其中pca降维的因子负荷量
时间: 2023-06-16 12:02:17 浏览: 196
PCA(numpy版+sklearn版).zip
5星 · 资源好评率100%
可以优化代码如下:
```
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import accuracy_score
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
import datetime
# 导入数据集
start = datetime.datetime.now() #计算程序运行时间
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
X_train = mnist.train.images
y_train = mnist.train.labels
X_test = mnist.test.images
y_test = mnist.test.labels
# PCA降维
pca = PCA(n_components=10)
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)
# 输出因子负荷量
print("PCA降维后的因子负荷量为:")
print(pca.components_)
# 可视化
plt.scatter(X_train_pca[:, 0], X_train_pca[:, 1], c=np.argmax(y_train, axis=1))
plt.show()
# K-means聚类
kmeans_centers = []
# 用于存储初始类中心
for i in range(10):
idx = np.where(np.argmax(y_train, axis=1) == i)[0] # 获取第i类数字的索引列表
sample_idx = np.random.choice(idx) # 随机指定一个样本作为初始类中心
kmeans_centers.append(X_train_pca[sample_idx]) # 将初始类中心添加到列表中
kmeans = KMeans(n_clusters=10,init=kmeans_centers,n_init=1)
kmeans.fit(X_train_pca)
# 计算分类错误率
y_pred = kmeans.predict(X_test_pca)
acc = accuracy_score(np.argmax(y_test, axis=1), y_pred)
print("分类错误率:{:.2%}".format(1-acc))
# 计算程序运行时间
end = datetime.datetime.now()
print("程序运行时间为:"+str((end-start).seconds)+"秒")
```
输出结果中包含了PCA降维后的因子负荷量,即`pca.components_`。
阅读全文