如何将张量流对象包装为 Keras 层?

How to wrap a tensorflow object as Keras layer?

我想将 Hierarchical Multiscale LSTM 实现为 Keras 层。
它已发布 here and implemented in tensorflow here
我的理解是,有一种方法可以将 Keras 中的此类 tensorflow 对象包装为一层。我不确定它有多复杂,但我认为它是可行的。你能帮我看看怎么做吗?

这通常由 implementing a custom Layer. To be more specific, you should inherit from keras.engine.topology.layer 完成,并为以下方法提供自定义实现(并将 TensorFlow 代码放入其中):

  • build(input_shape): this is where you will define your weights. This method must set self.built = True, which can be done by calling super([Layer], self).build()
  • call(x): this is where the layer's logic lives. Unless you want your layer to support masking, you only have to care about the first argument passed to call: the input tensor.
  • compute_output_shape(input_shape): in case your layer modifies the shape of its input, you should specify here the shape transformation logic. This allows Keras to do automatic shape inference.

由于您正在尝试实现循环层,因此直接从 keras.legacy.layers.recurrent 继承也很方便。在这种情况下,您可能不需要重新定义 compute_output_shape(input_shape)。如果您的层需要额外的参数,您可以将它们传递给自定义层的 __init__ 方法。