Home > Net >  How to change the input shape of model in Keras
How to change the input shape of model in Keras

Time:05-03

I have a model that I load this way:

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

I want to add a Dense at the end of it but since it takes an input with shape (None, 416,416,3) it doesn't let me do it and it returns an error:

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

I also tried this way with a Sequential (I want to use just the last output of 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

But it returns another error:

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

Is there a way to add the final Dense layer?

CodePudding user response:

The problem is that you are trying to reduce (flatten) an output with multiple None dimensions, which will not work if you want to use the output as input to another layer. You can try using a GlobalAveragePooling2D or GlobalMaxPooling2D instead:

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])
  • Related