自定义Keras损失的怪异损失结果

时间:2018-12-11 02:48:24

标签: python tensorflow keras image-segmentation loss-function

我试图在Keras中自定义骰子得分损失功能。

Dice是一个值,介于0到1之间。我使用1-dice作为损失函数。因此结果也应该在0到1之间,但是当我训练模型时,结果会大于1。这太奇怪了。

这里是骰子损失功能。

def dice_coef(y_true, y_pred):
    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.0 * intersection + 1.0) / (K.sum(y_true_f) + K.sum(y_pred_f) + 1.0)
def dice_coef_loss(y_true, y_pred):
    return 1-dice_coef(y_true, y_pred)

以及模型功能的一部分。

def UResNet34(input_shape=(1, 512, 512), classes=1, decoder_filters=16, decoder_block_type='upsampling',
                   encoder_weights=None, input_tensor=None, activation='sigmoid', **kwargs):

    backbone = ResnetBuilder.build_resnet_34(input_shape=input_shape,input_tensor=input_tensor)

    skip_connections = list([97,54,25])  # for resnet 34
    model = build_unet(backbone, classes, decoder_filters,
                   skip_connections, block_type=decoder_block_type,
                   activation=activation, **kwargs)
    model.name = 'u-resnet34'
    sgd = SGD(lr=0.01, decay=0.0005, momentum=0.9, nesterov=False)
    model.compile(optimizer=sgd, loss=dice_coef_loss, metrics=[dice_coef])
    return model

我引用了here中的模型。

并通过代码训练模型

model = UResNet34()
cp = ModelCheckpoint(model_h5_path, monitor='val_loss', save_best_only=True, 
save_weights_only=True, verbose=0, mode='auto')
history = model.fit(
    x_train, yy_train,
    validation_data=(x_test, yy_test), 
    epochs=epochs,
    batch_size=batch_size,
    verbose=1,
    callbacks=[cp])

培训过程。

Train on 520 samples, validate on 55 samples
Epoch 1/2000
520/520 [==============================] - 27s 52ms/step - loss: 2.6956 - dice_coef: 0.0075 - val_loss: 2.7011 - val_dice_coef: 0.0012
Epoch 2/2000
520/520 [==============================] - 15s 28ms/step - loss: 2.6933 - dice_coef: 0.0082 - val_loss: 2.6993 - val_dice_coef: 0.0014
Epoch 3/2000
520/520 [==============================] - 15s 28ms/step - loss: 2.6907 - dice_coef: 0.0091 - val_loss: 2.6972 - val_dice_coef: 0.0017
Epoch 4/2000
520/520 [==============================] - 15s 28ms/step - loss: 2.6864 - dice_coef: 0.0117 - val_loss: 2.6951 - val_dice_coef: 0.0021
Epoch 5/2000
520/520 [==============================] - 15s 28ms/step - loss: 2.6829 - dice_coef: 0.0136 - val_loss: 2.6934 - val_dice_coef: 0.0022

损失和val_loss很奇怪。损失函数有什么问题吗?

0 个答案:

没有答案