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

Keras 3中获取指定层输入连接的等效代码实现

Keras 3.x 中获取层关联输入的等效实现

问题背景

Keras 2.x中通过inbound_nodes获取层输入的代码在Keras 3.x中运行时会抛出AttributeError: 'InputLayer' object has no attribute 'inbound_nodes'错误,且用户自行修改后的代码错误获取了LSTM层的全部输出(预期仅获取('LSTM3', 'tanh', 0)),需要适配Keras 3.x的正确实现。

解决方案

Keras 3.x 中,层的输入连接信息已迁移至inbound_edges属性,以下是与原Keras 2.x代码功能完全等效的实现:

def get_inputs(layer):
    """Get the inputs of a layer in Keras 3.x."""
    inputs = []
    for edge in layer.inbound_edges:
        inbound_layer = edge.source_layer
        tensor_index = edge.source_tensor_index
        try:
            activation = inbound_layer.activation.__name__
        except AttributeError:
            activation = None
        inputs.append((inbound_layer.name, activation, tensor_index))
    return inputs

关键说明

  • inbound_edges是Keras 3.x中层用于存储输入连接的核心属性,每个Edge实例包含源层、源张量索引等关键信息,替代了Keras 2.x中的inbound_nodes
  • 该实现会精准获取目标层的直接输入关联,例如依赖LSTM3输出的LSTM4,只会返回预期的('LSTM3', 'tanh', 0),不会错误捕获无关输出
  • 对于InputLayer,inbound_edges为空列表,避免了原代码中的属性不存在错误

内容的提问来源于stack exchange,提问作者Jean-Francois T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:41:03