Keras ResNet50训练正常但测试评估返回0准确率0损失问题排查
问题
用Keras实现的ResNet50适配HuggingFace的tiny-imagenet数据集后,训练、验证阶段能正常输出损失和准确率,但测试时模型返回0%准确率和0.0损失。之前看到Stack Overflow上有自定义模型重写test_step的解决方案,但这个方案不适用于当前场景。使用环境为Python 3.8.12、TensorFlow 2.9.1,相关代码及输出如下:
模型构建代码
from tensorflow.keras.applications.resnet import ResNet50, preprocess_input class ResNet_Interface: def __init__(self, incoming_data_shape): self.incoming_data_shape = incoming_data_shape self.model = ResNet50(input_shape=self.incoming_data_shape, include_top=True, weights=None, classes=200) self.model.trainable = True self.pre_process = preprocess_input def get_model(self): return self.model
训练评估代码
def evaluate_model_imagenet(dataset, resnet_interface): model = resnet_interface.get_model() pre_process = resnet_interface.pre_process opt = Adam() model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) score = model.fit(pre_process(dataset['x_train']), dataset['y_train'], batch_size=64, epochs=1, verbose=2, validation_data=(pre_process(dataset['x_val']), dataset['y_val'])) test_score = model.evaluate(pre_process(dataset['x_test']), verbose=2)
输出示例
1563/1563 - 227s - loss: 5.0075 - accuracy: 0.0418 - val_loss: 4.5963 - val_accuracy: 0.0833 - 227s/epoch - 145ms/step 94/94 - 1s - loss: 0.0000e+00 - accuracy: 0.0000e+00 - 569ms/epoch - 6ms/step
问题原因
- 测试集标签未传入:调用
model.evaluate时只传入了测试集的特征数据,没有传对应的标签dataset['y_test']。使用categorical_crossentropy损失函数时,无标签输入会直接跳过损失计算返回0.0;准确率计算依赖标签与预测结果的对比,没有标签自然无法得到有效数值,返回0%。 - (次要可能)测试集数据本身异常,比如样本为空、标签格式不匹配,但从代码逻辑看,核心问题就是缺失测试标签。
解决方法
直接修改训练评估函数里的测试评估代码,在model.evaluate中同时传入测试集的特征和标签:
test_score = model.evaluate(pre_process(dataset['x_test']), dataset['y_test'], verbose=2)
额外可以做以下验证确保数据有效性:
- 检查
dataset['y_test']的形状是否为(测试样本数, 200)的独热编码格式,与模型输出维度匹配 - 确认测试集样本数量不为空,且标签取值在0-199范围内(对应tiny-imagenet的200个类别)
内容的提问来源于stack exchange,提问作者Pedro Carvalho
相关产品推荐
相关产品推荐

