【发布时间】:2019-06-05 04:35:08
【问题描述】:
我正在尝试为我的 CNN 模型实现自定义损失函数。我找到了一个IPython notebook,它实现了一个名为Dice的自定义损失函数,如下:
from keras import backend as K
smooth = 1.
def dice_coef(y_true, y_pred, smooth=1):
intersection = K.sum(y_true * y_pred, axis=[1,2,3])
union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])
return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)
def bce_dice(y_true, y_pred):
return binary_crossentropy(y_true, y_pred)-K.log(dice_coef(y_true, y_pred))
def true_positive_rate(y_true, y_pred):
return K.sum(K.flatten(y_true)*K.flatten(K.round(y_pred)))/K.sum(y_true)
seg_model.compile(optimizer = 'adam',
loss = bce_dice,
metrics = ['binary_accuracy', dice_coef, true_positive_rate])
我以前从未使用过 keras 后端,并且对 keras 后端的矩阵计算感到困惑。所以,我创建了一些张量来查看代码中发生了什么:
val1 = np.arange(24).reshape((4, 6))
y_true = K.variable(value=val1)
val2 = np.arange(10,34).reshape((4, 6))
y_pred = K.variable(value=val2)
现在我运行dice_coef 函数:
result = K.eval(dice_coef(y_true=y_true, y_pred=y_pred))
print('result is:', result)
但它给了我这个错误:
ValueError: Invalid reduction dimension 2 for input with 2 dimensions. for 'Sum_32' (op: 'Sum') with input shapes: [4,6], [3] and with computed input tensors: input[1] = <1 2 3>.
然后我将所有[1,2,3] 更改为-1,如下所示:
def dice_coef(y_true, y_pred, smooth=1):
intersection = K.sum(y_true * y_pred, axis=-1)
# intersection = K.sum(y_true * y_pred, axis=[1,2,3])
# union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])
union = K.sum(y_true, axis=-1) + K.sum(y_pred, axis=-1)
return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)
现在它给了我一个价值。
result is: 14.7911625
问题:
- 什么是
[1,2,3]? - 为什么当我将
[1,2,3]更改为-1时代码有效? -
dice_coef函数有什么作用?
【问题讨论】:
-
[1,2,3]表示求和(视为聚合操作)穿过张量的第二到第四轴。 -
同样
axis=-1insum表示总和在最后一个轴上运行。
标签: python tensorflow keras conv-neural-network