tensorflow tf.keras.input "tensor" 参数有什么作用?

What does tensorflow tf.keras.input "tensor" parameter do?

官方文档并没有说清楚这个参数到底是干什么的。任何人都可以用一个例子来解释吗?

通常当您设置 shape 参数和可选的 dtype 时,它会为输入创建一个占位符:

input = tf.keras.layers.Input(shape=(w,h,c))

传递 tensor 参数是用另一个张量指定输入参数(使用 tf.TypeSpec)的另一种方法:

input = tf.keras.layers.Input(tensor=some_tensor)

它的意思是通过另一个模型或层的输出来指定一个模型的输入。

例如这里是model1:

model1 = tf.keras.Sequential([
                   tf.keras.layers.InputLayer(input_shape=(28,28,1)),
                   tf.keras.layers.Flatten()])

我可以通过 model1 的输出指定 model2 的输入,如下所示:

input = tf.keras.layers.Input(tensor=model1.output)
x = tf.keras.layers.Dense(12, activation="relu")(input)
output = tf.keras.layers.Dense(10, activation="softmax")(x)
model2 = tf.keras.Model(inputs=input, outputs=output)
model2.summary()

输出:

Model: "model_01"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_20 (InputLayer)        [(None, 784)]             0         
_________________________________________________________________
dense_42 (Dense)             (None, 12)                9420      
_________________________________________________________________
dense_43 (Dense)             (None, 10)                130       
=================================================================
Total params: 9,550
Trainable params: 9,550
Non-trainable params: 0
_________________________________________________________________

P.S:另一种创建输入的方法是传递 type_spec 参数。如果传递此参数,则除名称之外的所有其他参数必须是 None.