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

如何在ResNet50模型中输出图像类别名称而非数组形式?

解决方案
  • 先定义类别名称映射列表,必须和训练时的类别标签顺序完全一致:

    class_names = ["airplane", "car", "motorcycle"]
    

    注:你示例里的输出是5维数组,但实际是3类分类任务,推测是示例笔误,调整列表长度对应你的实际类别数即可。

  • 处理模型输出得到类别名称:
    模型输出的是one-hot编码张量,先通过tf.argmax()获取概率最高的类别索引,再用索引从映射列表中取出对应名称:

    # model_output是模型的预测输出张量
    predicted_idx = tf.argmax(model_output, axis=1).numpy()[0]
    predicted_class = class_names[predicted_idx]
    print(predicted_class)  # 输出示例:"airplane"
    
  • 如果想让模型直接输出类别名称(无需额外后处理),可以给原模型添加一个Lambda层,整合索引映射逻辑:

    import tensorflow as tf
    from tensorflow.keras.layers import Lambda
    
    # 定义类别映射函数
    def idx_to_class(x):
        class_names = tf.constant(["airplane", "car", "motorcycle"])
        return tf.gather(class_names, tf.argmax(x, axis=1))
    
    # 构建带类别名称输出的新模型
    named_output_model = tf.keras.Model(
        inputs=model.input,
        outputs=Lambda(idx_to_class)(model.output)
    )
    
    # 预测时直接得到类别名称
    prediction = named_output_model.predict(processed_image)
    # 若输出是字节形式,可转成字符串
    print(prediction[0].decode())  # 输出:"airplane"
    

内容的提问来源于stack exchange,提问作者ZHLN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:38:15