You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义盲文识别模型预测报错:decode_predictions不支持26分类输出

解决方案

你遇到的报错是因为tf.keras.applications.imagenet_utils.decode_predictions仅适配输出1000个ImageNet类别的模型,而你的模型是针对26个英文字母的自定义分类模型,需要自己实现类别到字母的映射逻辑,具体步骤如下:

1. 获取类别-字母映射关系

你使用flow_from_directory生成训练/验证数据时,生成器对象train_generator自带class_indices属性,这是一个{字母: 类别索引}的字典。我们可以反转这个字典,得到{索引: 字母}的映射,用于后续预测结果转换:

# 反转class_indices,得到索引到字母的映射
idx_to_char = {v: k for k, v in train_generator.class_indices.items()}

2. 修正测试代码的预处理逻辑

注意:你的模型训练时没有使用ResNet50的预处理逻辑(tf.keras.applications.resnet50.preprocess_input),测试时误用该预处理会导致输入数据分布和训练时不一致,影响预测准确性。需要替换为和训练阶段一致的预处理(你用的ImageDataGenerator默认没有额外缩放,只需保证输入尺寸和训练时的(28,28)一致即可)。

3. 替换decode_predictions,实现自定义预测结果转换

以下是修改后的完整测试代码:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

img_path = "./test/a1.JPG10whs.jpg"
img = plt.imread(img_path)
# 调整图片尺寸和训练时一致
img = tf.image.resize(img, (28, 28))
img_array = tf.keras.utils.img_to_array(img)
img_batch = np.expand_dims(img_array, axis=0)

# 这里去掉ResNet的预处理,改用和训练一致的逻辑(如果训练时ImageDataGenerator设置了rescale=1./255,这里也要加:img_batch = img_batch / 255.0)

prediction = model.predict(img_batch)

# 获取top3的预测索引和概率
top3_indices = np.argsort(prediction[0])[::-1][:3]
top3_results = [(idx_to_char[idx], prediction[0][idx]) for idx in top3_indices]

# 输出结果
print("Top3预测结果:")
for char, prob in top3_results:
    print(f"字符: {char}, 概率: {prob:.4f}")
# 输出最可能的字符
print(f"最可能的字符: {idx_to_char[np.argmax(prediction)]}")

额外说明

如果训练后保存了模型,后续加载模型时没有train_generator对象,可以手动构建索引-字母映射:

# 手动构建a-z的索引映射,索引0对应a,1对应b,以此类推
idx_to_char = {i: chr(ord('a') + i) for i in range(26)}

内容的提问来源于stack exchange,提问作者Fran Fernández

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:31:07