首页 > 解决方案 > 密集层 Keras 中的输出维度

问题描述

我有以下模型的样本

from tensorflow.keras import models
from tensorflow.keras import layers

sample_model = models.Sequential()
sample_model.add(layers.Dense(32, input_shape=(4,)))
sample_model.add(layers.Dense(16, input_shape = (44,)))

sample_model.compile(loss="binary_crossentropy",
                     optimizer="adam", metrics = ["accuracy"])

模型IP:

sam_x = np.random.rand(10,4)
sam_y = np.array([0,1,1,0,1,0,0,1,0,1,])
sample_model.fit(sam_x,sam_y)

混淆是fit应该抛出一个错误,shape mismatch因为expected_input_shapefor the2nd Dense Layer是给定的,(None,44)但是outputfor the 1st Dense Layer(这是 的输入2nd Dense Layer)将是 shape (None,32)。但它运行成功。

我不明白为什么没有错误。任何澄清都会有所帮助

标签: tensorflowkerasdeep-learningtensorflow2.0tf.keras

解决方案


input_shape关键字参数仅对 a 的第一层有效Sequential。其他层的输入形状将来自它们的前一层。

这种行为在以下文档中有所暗示tf.keras.layers.InputShape

当使用带有 Keras Sequential 模型的 InputLayer 时,可以通过将 input_shape 参数移动到 InputLayer 之后的第一层来跳过它。

并在顺序模型指南中。

可以通过查看Sequential.add方法的来源来确认该行为:

if not self._layers:
  if isinstance(layer, input_layer.InputLayer):
    # Case where the user passes an Input or InputLayer layer via `add`.
    set_inputs = True
  else:
    batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer)
    if batch_shape:
      # Instantiate an input layer.
      x = input_layer.Input(
          batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input')
      # This will build the current layer
      # and create the node connecting the current layer
      # to the input layer we just created.
      layer(x)
      set_inputs = True 

如果模型中还没有层,则将使用Input从模型的第一层派生的形状添加到模型中。当模型中尚不存在任何层时才执行此操作。

该形状要么是完全已知的(如果input_shape已传递到模型的第一层),要么在模型构建后将是完全已知的(例如,调用model.build(input_shape))。


推荐阅读