
jupyter notebook运行这串代码很慢出不了图片
有没有人可以帮忙看怎么解决
用的是最新版jupyter notebook
import numpy as np
import time
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_openml # 用于下载 MNIST 数据集
from sklearn.model_selection import train_test_split # 划分训练集和测试集
from sklearn.linear_model import LogisticRegression # 逻辑回归分类器
from sklearn.decomposition import PCA # 主成分分析(PCA)降维
from sklearn.metrics import accuracy_score # 计算准确率
import warnings
from sklearn.exceptions import ConvergenceWarning
# 忽略逻辑回归未收敛的警告(ConvergenceWarning)
warnings.filterwarnings("ignore", category=ConvergenceWarning)
print("加载数据...")
# fetch_openml 会下载 MNIST 数据集,并缓存到 './data' 文件夹
mnist = fetch_openml('mnist_784', version=1, as_frame=False,
parser='auto', data_home='./data')
X, y = mnist.data, mnist.target.astype(int) # 将标签转换为整数类型
# 数据归一化到 [0,1],提升模型训练稳定性
X = X / 255.0
# 70% 训练集, 30% 测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)
pca = PCA(n_components=32) # PCA 降维 原始特征维度 28x28=784,加快训练速度
X_train_pca = pca.fit_transform(X_train) # PCA 训练并转换训练集
X_test_pca = pca.transform(X_test) # 将测试集也投影到 PCA 空间
print("训练...")
clf = LogisticRegression(max_iter=100) # max_iter 可修改,用于对比训练迭代次数的影响
start_time = time.time() # 记录训练开始时间
clf.fit(X_train_pca, y_train) # 训练逻辑回归模型
end_time = time.time() # 记录训练结束时间
total_time = end_time - start_time # 计算总训练时间
print("测试...")
y_pred = clf.predict(X_test_pca) # 对测试集进行预测
acc = accuracy_score(y_test, y_pred) # 计算测试集准确率
print(f"训练时间: {total_time:.2f} s")
print(f"测试集准确率: {acc*100:.2f}%")
plt.figure(figsize=(30,10)) # 随机选取图片进行显示
for i in range(30):
idx = np.random.randint(0, len(X_test)) # 随机选择索引
img = X_test[idx].reshape(28,28) # 将一维向量恢复成 28x28 图像
plt.subplot(3,10,i+1)
plt.imshow(img, cmap="gray") # 显示灰度图
plt.title(f"Pred:{y_pred[idx]} True:{y_test[idx]}") # 显示预测值和真实值
plt.axis("off") # 关闭坐标轴
plt.show()