如何在 VGG16 中将输入通道形状从 (224, 224, 3) 替换为 (224, 224, 1)?

How to replace the input channel shape from (224, 224, 3) to (224, 224, 1) in VGG16?

我正在使用 VGG16 进行迁移学习。我的图像是灰度的。因此,我需要将 Vgg16 的输入通道形状从 (224, 224, 3) 更改为 (224, 224, 1)。我尝试了以下代码并出现错误:

TypeError: build() takes from 1 to 2 positional arguments but 4 were given

任何人都可以帮助我哪里做错了吗?

vgg16_model= load_model('Fetched_VGG.h5')
vgg16_model.summary()

# transform the model to Sequential
model= Sequential()
for layer in vgg16_model.layers[1:-1]:
    model.add(layer)

# Freezing the layers (Oppose weights to be updated)
for layer in model.layers:
    layer.trainable = False

model.build(224,224,1)
model.add(Dense(2, activation='softmax', name='predictions'))

你不能,即使你摆脱了输入层,这个模型有一个已经编译过的图,你的第一个 conv 层需要一个输入 3渠道。我不认为真的有一个简单的解决方法可以让它接受 1 个频道(如果有的话)。

您需要在三维中重复您的数据,并在所有 3 个波段中使用相同的灰度图像而不是 RGB,这样效果很好。

如果您的图像具有以下形状:(224,224,1):

import numpy as np
gray_image_3band = np.repeat(gray_img, repeats = 3, axis = -1)

如果您的图像具有以下形状:(224,224)

gray_image_3band = np.repeat(gray_img[..., np.newaxis], repeats = 3, axis = -1)

您不再需要以这种方式调用 model.build(),保留输入层。但是如果你想调用它,你需要像这样将形状作为元组传递:

model.build( (224, 224, 1) ) # this is correct, notice the parentheses