0

在尝试学习 keras 和深度学习时,我想创建一个图像抠图算法,该算法使用类似于修改后的自动编码器的架构,它需要两个图像输入(一个源图像和一个用户生成的 trimap)并产生一个图像输出(图像前景的 alpha 值)。编码器部分(两个输入)是使用预训练的 VGG16 进行简单的特征提取。我想使用低分辨率 alphamatting.com 数据集训练解码器。

运行附加的代码会产生错误: ValueError: Input 0 of layer block1_conv1 is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, None]

我无法理解这个错误。我验证了我的 twin_gen 闭包正在为两个输入生成形状 (22, 256,256,3) 的图像批次,所以我猜问题是我以某种方式创建了错误的模型,但我看不出错误在哪里. 任何人都可以帮助阐明我如何看到这个错误吗?

import tensorflow as tf
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2DTranspose, Concatenate, BatchNormalization, Input
from tensorflow.keras.preprocessing.image import ImageDataGenerator


def DeConvBlock(input, num_output):
    x = Conv2DTranspose(num_output, kernel_size=3, strides=2, activation='relu', padding='same')(input)
    x = BatchNormalization()(x)
    x = Conv2DTranspose(num_output, kernel_size=3, strides=1, activation='relu', padding='same')(x)
    x = BatchNormalization()(x)
    x = Conv2DTranspose(num_output, kernel_size=3, strides=1, activation='relu', padding='same')(x)
    x = BatchNormalization()(x)
    return x


img_input = Input((256, 256, 3))
img_vgg16 = VGG16(include_top=False, weights='imagenet')
img_vgg16._name = 'img_vgg16'
img_vgg16.trainable = False


tm_input = Input((256, 256, 3))
tm_vgg16 = VGG16(include_top=False, weights='imagenet')
tm_vgg16._name = 'tm_vgg16'
tm_vgg16.trainable = False

img_vgg16 = img_vgg16(img_input)
tm_vgg16 = tm_vgg16(tm_input)
x = Concatenate()([img_vgg16, tm_vgg16])
x = DeConvBlock(x, 512)
x = DeConvBlock(x, 256)
x = DeConvBlock(x, 128)
x = DeConvBlock(x, 64)
x = DeConvBlock(x, 32)
x = Conv2DTranspose(1, kernel_size=3, strides=1, activation='sigmoid', padding='same')(x)


m = Model(inputs=[img_input, tm_input], outputs=x)
m.summary()
m.compile(optimizer='adam', loss='mean_squared_error')

gen = ImageDataGenerator(width_shift_range=0.1, rotation_range=30, height_shift_range=0.1, horizontal_flip=True, validation_split=0.2, preprocessing_function=preprocess_input)
SEED = 49


def twin_gen(generator, subset):
    gen_img = generator.flow_from_directory('./data', classes=['input_training_lowres'], seed=SEED, shuffle=False, subset=subset, color_mode='rgb')
    gen_map = generator.flow_from_directory('./data/trimap_training_lowres', classes=['Trimap1'], seed=SEED, shuffle=False, subset=subset, color_mode='rgb')
    gen_truth = generator.flow_from_directory('./data', classes=['gt_training_lowres'], seed=SEED, shuffle=False, subset=subset, color_mode='rgb')

    while True:
        img = gen_img.__next__()
        tm = gen_map.__next__()
        gt = gen_truth.__next__()
        yield [[img, tm], gt]


train_gen = twin_gen(gen, 'training')
val_gen = twin_gen(gen, 'validation')


checkpoint_filepath = 'checkpoint'
checkpoint = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_weights_only=True,
    monitor='val_loss',
    mode='auto',
    save_freq='epoch',
    save_best_only=True)


r = m.fit(train_gen, validation_data=val_gen, epochs=10, callbacks=[checkpoint])
4

1 回答 1

1

首先你没有指定的输入形状VGG16和你设置include_top=False,所以默认的输入形状将是(None, None ,3)大小写channels_last

keras.applications.VGG16PS:您可以查看和keras.applications.imagenet_utils.obtain_input_shape详细的源代码。

None正如您可以通过调用看到的输出形状model.summary()

__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            [(None, 256, 256, 3) 0                                            
__________________________________________________________________________________________________
input_3 (InputLayer)            [(None, 256, 256, 3) 0                                            
__________________________________________________________________________________________________
img_vgg16 (Functional)          (None, None, None, 5 14714688    input_1[0][0]                    
__________________________________________________________________________________________________
tm_vgg16 (Functional)           (None, None, None, 5 14714688    input_3[0][0]                    
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 8, 8, 1024)   0           img_vgg16[0][0]                  
                                                                 tm_vgg16[0][0]                   
__________________________________________________________________________________________________
         

要解决这个问题,你可以简单地设置input_shape=(256, 256, 3),现在VGG16调用model.summary()会给你:

__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 256, 256, 3) 0
__________________________________________________________________________________________________
input_3 (InputLayer)            [(None, 256, 256, 3) 0
__________________________________________________________________________________________________
img_vgg16 (Functional)          (None, 8, 8, 512)    14714688    input_1[0][0]
__________________________________________________________________________________________________
tm_vgg16 (Functional)           (None, 8, 8, 512)    14714688    input_3[0][0]
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 8, 8, 1024)   0           img_vgg16[0][0]
                                                                 tm_vgg16[0][0]
__________________________________________________________________________________________________
            

错误的主要原因是当你调用__next__()它时返回两个数组(data, label)的元组 shape ((batch_size, 256, 256, 3), (batch_size, 1)),但我们真的只想要第一个。

此外,数据生成器不应该产生tuplelist否则将不会为任何变量提供梯度,因为fit函数期望(inputs, targets)返回数据生成器。

你还有另一个问题,你的模型的输出形状是(batch_size, 256, 256, 1),但你的gen_truth元素形状是(batch_size, 256, 256, 3)当你加载gen_truth图像时color_mode='rgb',为了获得与模型输出相同的形状,如果你有灰度图像,你应该加载gen_truthcolor_mode='grayscale',或者加载它color_mode='rgba'并获取最后一个通道值,如果你想使用 alpha 值(我只是从你问题中的描述中猜到它,但你应该明白)

运行没有任何问题的示例代码:

import tensorflow as tf
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2DTranspose, Concatenate, BatchNormalization, Input
from tensorflow.keras.preprocessing.image import ImageDataGenerator

def DeConvBlock(input, num_output):
    x = Conv2DTranspose(num_output, kernel_size=3, strides=2, activation='relu', padding='same')(input)
    x = BatchNormalization()(x)
    x = Conv2DTranspose(num_output, kernel_size=3, strides=1, activation='relu', padding='same')(x)
    x = BatchNormalization()(x)
    x = Conv2DTranspose(num_output, kernel_size=3, strides=1, activation='relu', padding='same')(x)
    x = BatchNormalization()(x)
    return x

img_input = Input((256, 256, 3))
img_vgg16 = VGG16(include_top=False, input_shape=(256, 256, 3), weights='imagenet')
img_vgg16._name = 'img_vgg16'
img_vgg16.trainable = False

tm_input = Input((256, 256, 3))
tm_vgg16 = VGG16(include_top=False, input_shape=(256, 256, 3), weights='imagenet')
tm_vgg16._name = 'tm_vgg16'
tm_vgg16.trainable = False

img_vgg16 = img_vgg16(img_input)
tm_vgg16 = tm_vgg16(tm_input)
x = Concatenate()([img_vgg16, tm_vgg16])
x = DeConvBlock(x, 512)
x = DeConvBlock(x, 256)
x = DeConvBlock(x, 128)
x = DeConvBlock(x, 64)
x = DeConvBlock(x, 32)
x = Conv2DTranspose(1, kernel_size=3, strides=1, activation='sigmoid', padding='same')(x)

m = Model(inputs=[img_input, tm_input], outputs=x)
m.summary()
m.compile(optimizer='adam', loss='mse')

gen = ImageDataGenerator(width_shift_range=0.1, rotation_range=30, height_shift_range=0.1, horizontal_flip=True, validation_split=0.2, preprocessing_function=preprocess_input)
SEED = 49

def twin_gen(generator, subset):
    gen_img = generator.flow_from_directory('./data', classes=['input_training_lowres'], seed=SEED, shuffle=False, subset=subset, color_mode='rgb')
    gen_map = generator.flow_from_directory('./data/trimap_training_lowres', classes=['Trimap1'], seed=SEED, shuffle=False, subset=subset, color_mode='rgb')
    gen_truth = generator.flow_from_directory('./data', classes=['gt_training_lowres'], seed=SEED, shuffle=False, subset=subset, color_mode='grayscale')

    while True:
        img = gen_img.__next__()[0]
        tm = gen_map.__next__()[0]
        gt = gen_truth.__next__()[0]
        yield ([img, tm], gt)

train_gen = twin_gen(gen, 'training')

r = m.fit(train_gen, steps_per_epoch=5, epochs=3)
于 2021-01-15T03:36:08.213 回答