【问题标题】:Shapes are incompatible with Keras Functional Model and VGG16 model形状与 Keras 功能模型和 VGG16 模型不兼容
【发布时间】:2021-03-10 04:59:13
【问题描述】:

我现在尝试使用 Keras 功能 API 将我自己的模型层和 VGG16 模型中的层合并到一个新模型中时有点迷茫。我需要在 block3_pool 之后用我的自定义图层添加新图层。将使用 8 个类(Fashion Mnist)。所有图像都从 28x28 放大到 32x32。这就是我已经走了多远:

# VGG16 Model
vgg_model = VGG16(include_top=False, weights='imagenet', input_shape=(32, 32, 3), classes=8)
vgg_model.save_weights('vgg.model')
# vgg_model.summary()

for layer in model.layers:
   layer.trainable = False

inputs = Input(shape=(4, 4,))
x = tf.keras.layers.Dense(64, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(8, activation=tf.nn.softmax)(x)

new_model = tf.keras.Model(inputs=inputs, outputs=outputs, name='new_model')
new_model.load_weights('vgg.model')

block3_pool = vgg_model.get_layer('block3_pool').output

# Now combine the two models
full_output = new_model(block3_pool)
full_model = Model(inputs=vgg_model.input, outputs=full_output)
full_model.summary()

尝试运行此代码时,我在 Google Colab 中收到以下错误:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_shape.py in assert_is_compatible_with(self, other)
   1132     """
   1133     if not self.is_compatible_with(other):
-> 1134       raise ValueError("Shapes %s and %s are incompatible" % (self, other))
   1135 
   1136   def most_specific_compatible_shape(self, other):

ValueError: Shapes (4, 64) and (3, 3, 3, 64) are incompatible

我似乎不完全理解为什么会这样以及我必须做些什么才能让它发挥作用。

【问题讨论】:

    标签: python tensorflow keras jupyter-notebook google-colaboratory


    【解决方案1】:

    你给出了 2 个不同的形状。 VGG16 中的input_shape 参数和Input 中的shape 参数必须具有相同的形状

    inputs = Input(shape=(32, 32, 3))
    

    在你的代码中替换它

    【讨论】:

    • 感谢您的回答。改变这一点听起来很合理。当我改变它时,虽然我得到一个新的错误:ValueError: Shapes (3, 64) and (3, 3, 3, 64) are incompatible
    • 是的,它是一种类型。应该是 vgg_model
    猜你喜欢
    • 2022-08-02
    • 2021-07-07
    • 2020-09-02
    • 2022-11-06
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2021-08-05
    相关资源
    最近更新 更多