【问题标题】:What is the advantage of using an InputLayer (or an Input) in a Keras model with Tensorflow tensors?在带有 Tensorflow 张量的 Keras 模型中使用 InputLayer(或 Input)有什么好处?
【发布时间】:2017-12-26 08:14:30
【问题描述】:

Keras 模型可以通过函数 API 用作 Tensor 上的 Tensorflow 函数,如 here 所述。

所以我们可以这样做:

from keras.layers import InputLayer

a = tf.placeholder(dtype=tf.float32, shape=(None, 784))

model = Sequential()
model.add(InputLayer(input_tensor=a, input_shape=(None, 784)))
model.add(Dense(32, activation='relu'))
model.add(Dense(10, activation='softmax'))

output = model.output

张量是什么:

<tf.Tensor 'dense_24/Softmax:0' shape=(?, 10) dtype=float32>

但是,这也可以在没有任何 InputLayer 的情况下工作:

a = tf.placeholder(dtype=tf.float32, shape=(None, 784))

model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(784,)))
model.add(Dense(10, activation='softmax'))

output = model(a)

有效,output 的形状和以前一样:

<tf.Tensor 'sequential_9/dense_22/Softmax:0' shape=(?, 10) dtype=float32>

我假设第一种形式允许:

  • 明确附加inputsoutputs 作为模型的属性(同名),以便我们可以在其他地方重用它们。例如与其他 TF 操作。
  • 将作为输入给出的张量转换为 Keras 输入,并带有额外的元数据(例如 _keras_history,如 the source code 中所述)。

但这不是我们不能用第二种形式做的事情,所以,InputLayer(和Input更是如此)有什么特殊用法吗(除了多个输入)?
此外,InputLayer 很棘手,因为它使用 input_shape 与其他 keras 层不同:我们指定批量大小(此处为None),但通常情况并非如此......

【问题讨论】:

    标签: python tensorflow deep-learning keras


    【解决方案1】:

    InputLayer 似乎有一些用途:

    • 首先,它允许您按原样提供纯张量流张量,而无需指定它们的形状。例如。你可以写

        model.add(InputLayer(input_tensor=a))
      

      这很好,有几个明显的原因,其中包括更少的重复。

    • 其次,它们允许您使用单个输入编写非序列网络,例如

            input
             / \
            /   \
           /     \
        conv1   conv2
          |       |
      

      如果没有 InputLayer,您将需要显式地提供 conv1conv2 相同的张量,或者在模型顶部创建任意身份层。两者都不是很讨人喜欢。

    • 最后,它们消除了“也是输入的层”和“普通层”之间的任意区别。如果您使用InputLayer,您可以编写代码,明确区分哪一层是输入和哪一层做某事。这提高了代码的可读性并使重构变得更加容易。例如,替换第一层变得和替换任何其他层一样容易,您无需考虑input_shape

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2018-02-11
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多