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

Python 如何使用lambda层更改模型的输入形状,python,python-3.x,keras,deep-learning,keras-layer,Python,Python 3.x,Keras,Deep Learning,Keras 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=

假设我以这种方式指定了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()
但我想通过以下方式将自定义层添加到预压输入图像:

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()

它工作得很好,但是现在我需要让它输入shape
2242243
而不是
(None,2242243)
-如何使它

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

将tensorflow.keras.backend导入为K
#向张量添加新维度
K.展开维(张量,0)
然而,我不明白你为什么需要它,就像前面提到的
@meonwongac
一样

如果您仍然希望使用
Lambda
层,而不是使用
skimage
/
OpenCV
/other库对图像进行调整大小/应用其他操作,则使用
Lambda
层的一种方法如下:

将tensorflow导入为tf
输入=输入(形状=(无,无,3))
下一层=Lambda(Lambda图像:tf.image.resize_图像(图像,(128,128))(输入)

我不明白你的问题。我想你是在考虑输入\形状=(2242243)在Lambda层中。如果使用“input\u shape”,实际上batch\u size为None是默认值。如果确实要指定batch\u size,可以使用batch\u input\u shape而不是input\u shape。我所知道的唯一需要张量中特定batch\u size的情况是有状态LSTM块