【问题标题】:Return tensor by reference from a custom keras layer从自定义 keras 层通过引用返回张量
【发布时间】:2020-09-30 12:47:08
【问题描述】:

我创建了一个名为 Node 的自定义层,它继承自 keras.layers.Layer,该层代表神经网络中的单个节点。

我的目标是使用以下语法实现它:

n1, n2, n3 = Node(), Node(), Node()

n1(n2) # Connects n2 to n1
output1 = n1.output # activation(n1*w1 + b)

n1(n3) # Connects n3 to n1
output1 # output1 is now activation(n1*w1 + n2*w2 + b)

换句话说,Node 将出站连接存储在一个数组中,.output 应该以Tensor 形式返回这些连接的加权和(通过激活函数等),该形式会随着未来的变化而更新.

是否可以使用 keras.layers.Layer 类和 TensorFlow 来实现该行为?

【问题讨论】:

    标签: tensorflow keras tensorflow2.0


    【解决方案1】:

    您可以使用 python 列表提供可变数量的输入,并根据输入列表长度修改输出:

    图层的call 函数如下所示:

    def call(self, inputs, **kwargs):
        temp = # Your original computations
        if len(inputs) == 1:
            return temp
        elif len(inputs) == 2:
            return inputs[1] + temp
    

    然后,您的代码将变为:

    n1, n2, n3 = Node(), Node(), Node()
    output1 = n1([n2])
    output1 = n1([n3, output1]) # Connects n3 to n1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多