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>
我假设第一种形式允许:
-
明确地将
inputs
和outputs
作为模型(相同名称)的属性附加,因此我们可以在其他地方重用它们 . 例如与其他TF操作 . -
将作为输入的张量转换为Keras输入,并附加其他元数据(如the source code中所述的
_keras_history
) .
但这不是我们不能用第二种形式做的事情,因此,是否有 InputLayer
(和 Input
一个更为明确的)的特殊用法(除了多个输入)?
此外, InputLayer
是棘手的,因为它使用 input_shape
与其他keras层不同:我们指定批量大小(此处为 None
),通常情况并非如此......
1 回答
似乎
InputLayer
有一些用途:这有几个显而易见的原因很好,其中包括更少的重复 .
如果没有
InputLayer
,则需要显式提供conv1
和conv2
相同的张量,或者在模型顶部创建任意标识层 . 两者都不是很令人愉快 .InputLayer
,您可以编写代码,其中明确区分哪个层是输入,哪个层执行某些操作 . 这提高了代码的可读性,使重构更容易 . 例如,替换第一层变得像替换任何其他层一样容易,您不需要考虑input_shape
.