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

Keras TensorFlow模型返回字典无自定义键名问题求助

Keras模型predict返回字典键名不符问题解决

问题现象

调用Keras模型的predict方法时,返回的字典响应中,自定义键名被替换为自动生成的map_script_1、map_script,而非预期的outputKeyVal、outputKeyStr。

预期响应

{
    "predictions": [
        {
            "outputKeyVal": [
                24.0
            ],
            "outputKeyStr": "O1"
        }
    ]
}

实际响应

{
    "predictions": [
        {
            "map_script_1": [
                24.0
            ],
            "map_script": "O1"
        }
    ]
}

问题原因

自定义MapScript层返回字典时,Keras默认会用层的名称(map_script)加上后缀自动命名输出张量,未保留字典中的自定义键名。此外代码存在笔误:outputs = ThirdScript(1)(inputs)应为outputs = MapScript(1)(inputs),否则会触发运行报错。

解决方法

方法1:在自定义层中为张量指定名称

修改MapScript层的call方法,给返回的每个张量添加name属性,强制Keras保留自定义键名:

@tf.function
def call(self, inputs):
    inputStr = tf.squeeze(inputs['inputStr'])
    inputVal = inputs['inputVal']
    outputVal = tf.add(inputVal, self.a_weight)
    # 为张量指定自定义名称
    outputVal = tf.identity(outputVal, name="outputKeyVal")
    outputStr = tf.identity(inputStr, name="outputKeyStr")
    return { "outputKeyVal": outputVal, "outputKeyStr": outputStr }

方法2:构建模型时显式指定输出名称

创建keras.Model时,显式将输出字典的键与对应张量绑定,确保自定义名称被保留:

# 修正笔误,使用自定义的MapScript层
outputs = MapScript(1)(inputs)

# 显式指定输出名称
model = keras.Model(inputs, {
    "outputKeyVal": outputs["outputKeyVal"],
    "outputKeyStr": outputs["outputKeyStr"]
})

完整修正后的代码

import tensorflow as tf
import pandas as pd
from tensorflow import keras

class MapScript(keras.layers.Layer):
    def __init__(self, units=32):
        super(MapScript, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.a_weight = self.add_weight(
            'a_weight',
            initializer=keras.initializers.Constant(20.00),
            dtype=tf.dtypes.float64,
            trainable=False)

    @tf.function
    def call(self, inputs):
        inputStr = tf.squeeze(inputs['inputStr'])
        inputVal = inputs['inputVal']
        outputVal = tf.add(inputVal,self.a_weight)
        # 为张量添加自定义名称
        outputVal = tf.identity(outputVal, name="outputKeyVal")
        outputStr = tf.identity(inputStr, name="outputKeyStr")
        return { "outputKeyVal": outputVal , "outputKeyStr": outputStr}


# 设置Keras后端默认 dtype 为 float64
keras.backend.set_floatx('float64')

# 定义输入张量
inputs = {
    "inputVal":keras.Input(shape=(1,),name="inputVal"),
    "inputStr":keras.Input(shape=(1,),name="inputStr", dtype=tf.string)
}

# 修正笔误,使用自定义的MapScript层
outputs = MapScript(1)(inputs)

# 构建模型时显式指定输出名称
model = keras.Model(inputs, {
    "outputKeyVal": outputs["outputKeyVal"],
    "outputKeyStr": outputs["outputKeyStr"]
})

# 保存模型
keras.models.save_model(model,'../../../../../../resources/models/saved_model_score/1',overwrite=True,include_optimizer=True,save_format=None,options=None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:17:13