如何使用 lambda 层更改模型的输入形状

How to change input shape of the model with lambda layer

假设我以这种方式从 keras 模型指定了 mobilenet:

base_model = MobileNetV2(weights='imagenet', include_top=False,  input_shape=(224, 224, 3))

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x) 
predictions = Dense(12, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(loss='categorical_crossentropy', optimizer = Adam(),
              metrics=['accuracy'])

但我想通过这种方式将自定义图层添加到预处理输入图像中:

def myFunc(x):
     return K.reshape(x/255,(-1,224,224,3))
new_model = Sequential()
new_model.add(Lambda(myFunc,input_shape =( 224, 224, 3),  output_shape=(224, 224, 3)))
new_model.add(model)
new_model.compile(loss='categorical_crossentropy', optimizer = Adam(),
              metrics=['accuracy'])
new_model.summary()

它工作得很好,但现在我需要让它输入形状 224 224 3 而不是 (None, 224, 224, 3) - 如何制作它

为了扩展你的张量的维度,你可以使用

import tensorflow.keras.backend as K  
# adds a new dimension to a tensor
K.expand_dims(tensor, 0)

但是,我不明白你为什么需要它,就像 @meonwongac 提到的那样。

如果您仍想使用 Lambda 图层而不是使用 skimage/OpenCV/ 其他库对图像调整大小/应用其他操作,一种使用 Lambda层如下:

import tensorflow as tf
input_ = Input(shape=(None, None, 3))
next_layer = Lambda(lambda image: tf.image.resize_images(image, (128, 128))(input_)