我正在使用 VGG16 进行迁移学习。我的图像是灰度的。因此,我需要将 Vgg16 的输入 channel 形状从 (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'))
最佳答案
你不能,即使你去掉了输入层,这个模型有一个已经编译好的图表,并且你的第一个转换层需要一个带有3个 channel 的输入。我认为确实没有一个简单的解决方法可以让它接受 1 个 channel (如果有的话)。
您需要在三维空间中重复数据,并在所有 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
关于tensorflow - 如何将VGG16中的输入 channel 形状从(224, 224, 3)替换为(224, 224, 1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57914354/