如何在 Keras 中更改模型的输入形状

How to change the input shape of model in Keras

我有一个以这种方式加载的模型:

def YOLOv3_pretrained(n_classes=12, n_bbox=3):

yolo3 = tf.keras.models.load_model("yolov3/yolo3.h5")
yolo3.trainable = False
l3 = yolo3.get_layer('leaky_re_lu_71').output
l3_flat = tf.keras.layers.Flatten()(l3)
out3 = tf.keras.layers.Dense(100*(4+1+n_classes))(l3_flat)
out3 = Reshape((100, (4+1+n_classes)), input_shape=(12,))(out3)
yolo3 = Model(inputs=yolo3.input, outputs=[out3])
return yolo3

我想在它的末尾添加一个 Dense,但由于它需要一个形状为 (None, 416,416,3) 的输入,所以它不允许我这样做 returns一个错误:

ValueError: The last dimension of the inputs to a Dense layer should be defined. Found None. Full input shape received: (None, None)

我也用 Sequential 尝试过这种方式(我只想使用 yolo 的最后一个输出):

def YOLOv3_Dense(n_classes=12):

yolo3 = tf.keras.models.load_model("yolov3/yolo3.h5")

model = Sequential()
model.add(yolo3)
model.add(Flatten())
model.add(Dense(100*(4+1+n_classes)))
model.add(Reshape((100, (4+1+n_classes)), input_shape=(413,413,3)))
return model

但它 returns 另一个错误:

ValueError: All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.

有没有办法添加最后的 Dense 层?

问题是您正在尝试减少(展平)具有多个 None 维度的输出,如果您想将输出用作另一层的输入,这将不起作用。您可以尝试使用 GlobalAveragePooling2DGlobalMaxPooling2D 代替:

import tensorflow as tf

yolo3 = tf.keras.models.load_model("yolo3.h5")
yolo3.trainable = False
l3 = yolo3.get_layer('leaky_re_lu_71').output
l3_flat = tf.keras.layers.GlobalMaxPooling2D()(l3)
out3 = tf.keras.layers.Dense(100*(4+1+12))(l3_flat)
out3 = tf.keras.layers.Reshape((100, (4+1+12)), input_shape=(12,))(out3)
yolo3 = tf.keras.Model(inputs=yolo3.input, outputs=[out3])