python - 为什么调用方法在构建时在 Keras 层中被调用

标签 python keras keras-layer

所以我尝试使用提供的示例在 Keras 中实现我自己的层:

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(MyLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        # Create a trainable weight variable for this layer.
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        return K.dot(x, self.kernel)

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

我注意到当我这样做时,调用中的内容会在构建时被调用:

model.add(MyLayer(4, input_dim=(1))

这在没有调用 fit、train、predict 等的情况下发生......

为什么?

最佳答案

它会在您向模型添加图层时调用,以检查形状是否有效。

如果你想看看它在哪里被调用,改变你的代码:

import sys
import traceback

class MyLayer(Layer):
    ....
    def call(self, x):
         traceback.print_stack(file=sys.stdout)
         return K.dot(x, self.kernel)

关于python - 为什么调用方法在构建时在 Keras 层中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44835819/

相关文章:

python - Ajax 的 Django csrf token

python - Keras 段错误(核心已转储)

python - Keras 自定义损失函数 : Accessing current input pattern

python - 展平层的输入必须是张量

python - Keras 输入层和 Tensorflow 占位符之间的区别

python - i3 WM(平铺管理器)创建弹出窗口

python - Python-如何拆分和加入音频?

python - "Decoder"模型的 "Sequence-to-Sequence"应该输入什么?

python - 为第三方创建 api token

python - keras模型的权重为nan