【问题标题】:Is it still necessary to implement `compute_output_shape()` when defining a custom tf.keras Layer?定义自定义 tf.keras 层时是否还需要实现 `compute_output_shape()`?
【发布时间】:2020-08-14 17:38:25
【问题描述】:

我使用 TensorFlow 2.1.0 在tf.keras 中实现了一个自定义Layer

过去,当使用独立的 Keras 时,在任何自定义层中定义 compute_output_shape(input_shape) 方法非常重要,这样才能创建计算图。

现在,在迁移到 TF2 之后,我发现即使我从自定义实现中删除了该方法,该层仍然可以按预期工作。显然,它可以在急切模式和图形模式下工作。 这是我的意思的一个例子:

from tensorflow.keras.layers import Layer, Input
from tensorflow.keras.models import Sequential
import numpy as np


class MyLayer(Layer):
    def call(self, inputs):
        return inputs[:, :-1]  # Do something that changes the shape


m = Sequential([MyLayer(), MyLayer()])
m.predict(np.ones((10, 3)))  # This would not have worked in the past

可以说compute_output_shape() 不再需要了吗?我错过了什么重要的东西吗?

在文档中没有明确提及删除compute_output_shape(),尽管没有一个示例明确实现它。

谢谢

【问题讨论】:

  • 您通常可以省略compute_output_shape() 方法,因为 tf.keras 会自动推断输出形状,除非图层是动态的。在其他 Keras 实现中,此方法要么是必需的,要么其默认实现假定输出形状与输入形状相同。
  • 根据Implementing custom layers,正在使用__init__buildcall

标签: tensorflow keras tensorflow2.0 keras-layer tf.keras


【解决方案1】:

在 Tensorflow 文档中没有提到,但在 第 12 章Custom Models and Training with TensorFlowHands-on Machine Learning using Scikit -O'REILLY Publications 的Learn and Tensorflow (Tensorflow 2 的第二版更新),作者 Aurelien Geron,如下截图所示:

要回答您的问题,是的,可以肯定地说,除非图层是动态的,否则不需要 compute_output_shape

这从Tensorflow Tutorial on Custom Layer 可以明显看出,其中compute_output_shape 没有使用。

希望这会有所帮助。快乐学习!

【讨论】:

猜你喜欢
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多