我正在使用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'))

最佳答案

即使您摆脱了输入层,您也无法做到,该模型的图形已经被编译,并且您的第一个转换层期望输入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

关于tensorflow - 如何在VGG16中将输入 channel 形状从(224,224,3)替换为(224,224,1)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57914354/

10-12 23:18