我成功地用 Keras 训练了一个用于图像分割的宪法神经网络。现在我正在尝试对我的图像应用一些数据增强来提高性能。为此,我使用ImageDataGenerator
然后flow_from_directory
仅将批次加载到内存中(我尝试不使用但出现内存错误)。代码示例是:
training_images = np.array(training_images)
training_masks = np.array(training_masks)[:, :, :, 0].reshape(len(training_masks), 400, 400, 1)
# generators for data augmentation -------
seed = 1
generator_x = ImageDataGenerator(
featurewise_center=True,
featurewise_std_normalization=True,
rotation_range=180,
horizontal_flip=True,
fill_mode='reflect')
generator_y = ImageDataGenerator(
featurewise_center=False,
featurewise_std_normalization=False,
rotation_range=180,
horizontal_flip=True,
fill_mode='reflect')
generator_x.fit(training_images, augment=True, seed=seed)
generator_y.fit(training_masks, augment=True, seed=seed)
image_generator = generator_x.flow_from_directory(
'data',
target_size=(400, 400),
class_mode=None,
seed=seed)
mask_generator = generator_y.flow_from_directory(
'masks',
target_size=(400, 400),
class_mode=None,
seed=seed)
train_generator = zip(image_generator, mask_generator)
model = unet(img_rows, img_cols)
model.fit_generator(train_generator, steps_per_epoch=int(len(training_images)/4), epochs=1)
但是,当我运行代码时,出现以下错误(我使用的是 Tensorflow 后端):
InvalidArgumentError (see above for traceback): Incompatible shapes: [14400000] vs. [4800000]
[[Node: loss/out_loss/mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](loss/out_loss/Reshape, loss/out_loss/Reshape_1)]]
在错误中它抱怨不兼容的形状 14400000 (400x400x9) 与 4800000 (400x400x3)。我在这里使用了自定义损失函数(如果您查看错误,它会说明损失),即 Dice 系数,定义如下:
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + 1.) / (K.sum(y_true_f) + K.sum(y_pred_f) + 1.)
在这里,我使用 (400,400,3) 图像和 1 类形状 (400,400,1) 的蒙版。我的 NN 将输入定义为Input((img_rows, img_cols, 3))
,输出定义为Conv2D(1, (1, 1), activation='sigmoid', name='out')(conv9)
(但在没有数据增强的情况下进行训练时效果很好)。