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

Keras报错:添加对象需为Layer实例,实际为KerasTensor

解决TypeError: The added layer must be an instance of class Layer. Found: KerasTensor

错误原因

你在model_variant函数的ConvLSTM分支里,错误地将**张量(KerasTensor)**传入了model.add()方法。Sequential模型的add()只能接收Layer类的实例,而你通过Bidirectional(LSTM(...))(model.output)得到的是该层输出的张量,不是层本身,因此触发报错。

修正方案

把创建层和添加层的步骤分开:先实例化Bidirectional层,再用model.add()将其添加到模型中。Sequential模型会自动把前一层的输出作为当前层的输入,无需手动调用层处理model.output。

修改后的model_variant函数代码:

from tensorflow.keras import regularizers
from tensorflow.keras.layers import Permute, Reshape, Bidirectional, LSTM, Flatten, Dense, BatchNormalization, Dropout

def model_variant(model, num_feat_map, dim, network_type, p):
    print(network_type)
    if network_type == 'ConvLSTM':
        model.add(Permute((2, 1, 3)))
        model.add(Reshape((-1, num_feat_map * dim)))
        # 先实例化Bidirectional层,再添加到Sequential模型
        bidirectional_layer = Bidirectional(LSTM(128, return_sequences=False, stateful=False))
        model.add(bidirectional_layer)
    if network_type == 'CNN':
        model.add(Flatten())
        model.add(Dense(64, activation='relu'))
        model.add(BatchNormalization())
        model.add(Dropout(p))

补充说明

你的环境是tensorflow 2.4.1 + keras 2.14.0,注意tensorflow 2.x已内置Keras,建议统一使用from tensorflow.keras import ...导入所有层和模型,避免单独安装的Keras与TF内置Keras版本不兼容的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:07:20