【问题标题】:How do I use input_shape and input_tensor in Transfer Learning in Keras?如何在 Keras 的迁移学习中使用 input_shape 和 input_tensor?
【发布时间】:2019-11-15 18:45:14
【问题描述】:

当我们在 Keras2 中进行迁移学习时,Arguments 需要“input_shape”和“input_tensor”。但我只使用了 input_tensor,从未使用过 input_shape。我觉得只有input_tensor就够了,不知道什么时候用input_shape。 我应该如何单独使用它们?

我同时使用了input_tensor和input_shape,分别取值,只采用了input_tensor的值,忽略了input_shape。

vgg16_model = VGG16(include_top=False, weights='imagenet', 
                    input_tensor = Input(shape=(150, 150, 3)), 
                    input_shape=(224,224,3))

top_model = Sequential()
top_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))
top_model.add(Dense(256, activation='relu'))
top_model.add(Dense(1, activation='sigmoid'))
model = Model(input=vgg16_model.input, output=top_model(vgg16_model.output))

model.summary()
Layer (type)                 Output Shape              Param #   
================================================================
input_6 (InputLayer)         (None, 150, 150, 3)       0         
_________________________________________________________________
block1_conv1 (Conv2D)        (None, 150, 150, 64)      1792      
_________________________________________________________________
block1_conv2 (Conv2D)        (None, 150, 150, 64)      36928     
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, 75, 75, 64)        0         
_________________________________________________________________
block2_conv......

我预计这段代码会出现一些错误,但没有错误,而且这个模型可以接受 (150, 150, 3) 的形状。 Input_shape=(224,224,3) 被忽略。

你能给我一点帮助吗?谢谢。

【问题讨论】:

  • 当不使用完全连接的分类层时,两者都是可选参数。这些模型可以接受可变大小的输入,但随后会提供可变大小的输出
  • 谢谢!但我还有一个问题。我添加了代码的详细信息。我什么时候必须使用 input_shape 而不是 input_tensor?

标签: python machine-learning keras deep-learning transfer-learning


【解决方案1】:

VGG16 代码可能只是忘记检查这两个参数。

当然,两者兼有是没有意义的。

  • 当您希望模型以该大小自动创建自己的输入层时,您可以使用input_shape
  • 当你有一个想要作为输入的张量时,你可以使用input_tensor

您可以在input_tensor 中使用任何张量,这意味着使用其他模型/层的输出作为VGG16 的输入。当然,您可以像以前一样传递一个虚拟输入张量,代码没有理由抱怨,它收到了一个张量,好的。

唯一的事情是编码器忘记验证“如果两个参数都存在,则抛出错误”。

【讨论】:

【解决方案2】:

实际上,当您设置 input_tensor 参数时,给定的张量(假设它是 Keras 张量)将用于输入,因此 input_shape 参数将被忽略。 Herekeras-applications源码中的相关部分:

if input_tensor is None:
    img_input = layers.Input(shape=input_shape)
else:
    if not backend.is_keras_tensor(input_tensor):
        img_input = layers.Input(tensor=input_tensor, shape=input_shape)
    else:
        img_input = input_tensor

如您所见,在最后一行中,给定的input_tensor 将用于输入张量,而不考虑input_shape

【讨论】:

  • 对于 else 的 fit if 语句,我不确定逻辑是什么意思。如果 input_tensor 不是 keras_tensor,那么我们希望张量的占位符等于输入张量吗?为什么会这样?谢谢。
  • @IntegrateThis 如果是 Keras 张量,则意味着它连接到层/模型,并且可以从那里获取值;因此,按原样使用它就可以了。但是,如果它不是 Keras 张量,则应将其包裹在 Input 层中,以便可以使用 placeholder(这是 Input 层的底层结构)对其进行馈送(即取值)。
猜你喜欢
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2019-08-24
  • 2019-03-08
  • 2019-09-19
  • 2019-09-09
  • 1970-01-01
  • 2021-02-01
相关资源
最近更新 更多