使用fashion_mnist运行程序遇EOFError问题求助
解决FashionMNIST的EOFError及代码预测问题
一、解决EOFError(压缩文件损坏)
该错误是本地缓存的FashionMNIST数据集文件下载不完整或损坏导致的,按以下步骤处理:
- 定位本地数据集缓存目录:
- Windows:
C:\Users\<你的用户名>\.keras\datasets\fashion-mnist - Linux/macOS:
~/.keras/datasets/fashion-mnist
- Windows:
- 删除该目录下所有文件(含四个压缩包及可能的解压文件)
- 重新运行代码,让TensorFlow自动重新下载完整数据集
- 若自动下载失败,手动下载以下四个未解压的压缩包,放入上述缓存目录:
- train-images-idx3-ubyte.gz
- train-labels-idx1-ubyte.gz
- t10k-images-idx3-ubyte.gz
- t10k-labels-idx1-ubyte.gz
二、修复代码中的预测逻辑错误
你的代码最后一行predictions = model.predict(shoe)存在核心问题:model.predict()接收的是预处理后的张量,而非图片路径,同时还缺少模型编译步骤,修改后的完整代码如下:
import tensorflow as tf from tensorflow import keras from PIL import Image import numpy as np shoe = "shoe.png" # 加载并预处理数据集 fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # 归一化(与后续预测图片处理逻辑保持一致) train_images = train_images / 255.0 test_images = test_images / 255.0 # 构建并编译模型(必须编译才能训练) model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_images, train_labels, epochs=5) test_loss, test_acc = model.evaluate(test_images, test_labels) # 处理待预测图片 img = Image.open(shoe).convert('L') # 转为灰度图 img = img.resize((28, 28)) # 调整尺寸至28x28,匹配模型输入 img_array = np.array(img) img_array = img_array / 255.0 # 归一化 img_array = np.expand_dims(img_array, 0) # 扩展为批量维度 (1, 28, 28) # 执行预测 predictions = model.predict(img_array) predicted_label = np.argmax(predictions[0]) print(f"预测类别索引:{predicted_label}")
内容的提问来源于stack exchange,提问作者kool
相关产品推荐
相关产品推荐

