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

构建文本与分类数据混合分类器时遇TensorFlow ValueError问题求助

解决TensorFlow Functional模型的ValueError问题:输出必须是Layer的输出张量

错误原因

你代码里的核心问题出在最后一层Dense的定义上:

outs = tf.keras.layers.Dense(3, activation = 'softmax')

这里你只创建了一个Dense层对象,但没有把上一层的输出z传入这个层,导致返回的Model的outputs参数是层对象,而不是该层处理后的张量输出——这违反了TensorFlow Functional API的要求:模型的输出必须是经过Layer计算后的张量(包含计算图的连接元数据)。

修正代码

只需要把最后一层Dense的定义改成接收z作为输入,生成张量输出即可:

def create_model():
    seq  = tf.keras.layers.Input(shape=(100,))
    embeddings = tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length)(seq)
    x = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128))(embeddings)
    x = tf.keras.layers.Dense(64, activation = 'relu')(x)
    x = tf.keras.layers.Dense(32, activation = 'relu')(x)

    categorical_input = tf.keras.layers.Input(shape =(4198, ) )
    y = tf.keras.layers.Dense(128, activation = 'relu')(categorical_input)
    y = tf.keras.layers.Dense(64, activation = 'relu')(y)

    combined = tf.keras.layers.concatenate([x, y])
    z = tf.keras.layers.Dense(32, activation='relu')(combined)
    z = tf.keras.layers.Dense(16, activation = 'relu')(z)
    # 关键改动:将z传入Dense层,生成张量输出
    outs = tf.keras.layers.Dense(3, activation = 'softmax')(z)
    return tf.keras.Model(inputs = [seq, categorical_input], outputs = outs)

model = create_model()
model.summary()

关键说明

在TensorFlow Functional API中,每一层的调用格式都是层对象(输入张量),这样才能在计算图中建立连接。你之前的写法相当于只实例化了层,但没有把它接入到整个模型的计算流程里,所以TensorFlow无法识别这是模型的输出张量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:51:10