在 Tensorflow 2.x 中我们不需要指定输入形状吗?

Is in Tensorflow 2.x we aren't need to specify the input shape?

刚刚看了官方教程in this page。创建模型的代码示例如下:

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.conv1 = Conv2D(32, 3, activation='relu')
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10, activation='softmax')

  def call(self, x):
    x = self.conv1(x)
    x = self.flatten(x)
    x = self.d1(x)
    return self.d2(x)

# Create an instance of the model
model = MyModel()

我的问题是,为什么在上面的代码中我们不需要在第一层 (Conv2D) 中指定输入形状?是否有任何官方文档提到此行为?

因为如果我阅读有关 Conv Layer 的官方文档,它会说:

When using this layer as the first layer in a model, provide the keyword argument input_shape (tuple of integers, does not include the sample axis), e.g. input_shape=(128, 128, 3) for 128x128 RGB pictures in data_format="channels_last"

一切正常。

无论输入形状如何,卷积作为一种运算都有效。只是输入通道需要匹配。 您可以在 tf.nn.conv2d 中看到此行为按预期工作。 (这是您的代码片段正在使用的)

现在,您正在链接对 keras.conv2d 的引用,它强制用户指定输入形状以使代码更具可读性和 'validate' 用户输入。