在定义一个自定义的tf.keras Layer时,是否还需要实现 "compute_output_shape()"?

问题描述 投票:1回答:1

我已经实现了一个自定义的 Layertf.keras,使用TensorFlow 2.1.0。

在过去,当使用独立的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()虽然没有一个例子明确地实现它。

谢谢你

tensorflow keras tensorflow2.0 keras-layer tf.keras
1个回答
2
投票

在Tensorflow文档中没有提到,但在 第十二章, 使用TensorFlow进行自定义模型和训练 的书。使用Scikit-Learn和Tensorflow进行机器学习(第2版更新为Tensorflow 2)。 由Aurelien Geron撰写的《O'RIELLY Publications》一书中提到,如下图所示。

enter image description here

回答你的问题,是的,可以肯定地说 compute_output_shape 不需要,除非该层是动态的。

从这一点可以看出 Tensorflow自定义图层教程 哪儿 compute_output_shape 是不用的。

希望对大家有所帮助。祝大家学习愉快!

© www.soinside.com 2019 - 2024. All rights reserved.