【发布时间】:2017-03-31 03:43:35
【问题描述】:
我想在 CNTK/Python 中使用 Wiki: Sørensen–Dice coefficient 作为损失函数。如何定义自定义损失函数。
【问题讨论】:
标签: python deep-learning cntk
我想在 CNTK/Python 中使用 Wiki: Sørensen–Dice coefficient 作为损失函数。如何定义自定义损失函数。
【问题讨论】:
标签: python deep-learning cntk
要回答您更一般的问题“我如何定义自定义损失函数:”
在 CNTK 中,损失函数并不特殊。任何导致标量的表达式都可以用作损失函数。学习器将通过对小批量中所有样本的标量损失值求和来计算小批量级别的损失,并像通过任何 CNTK 表达式一样通过它进行反向传播。
例如,下面是定义平方误差损失的一种方式:
def my_square_error(x,y):
diff = x-y
return times_transpose(diff, diff)
cross_entropy_with_softmax() 损失可以用 Python 写成这样:
def my_cross_entropy_with_softmax(output, labels):
logZ = reduce_log_sum(output) # log of softmax denominator
return times_transpose(labels, output) - logZ
最后,多任务学习可以通过使用多个损失的加权和的损失函数轻松实现。
【讨论】:
import numpy as np
import cntk as C
def dice_coefficient(x, y):
# https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
intersection = C.reduce_sum(C.element_times(x, y))
return 2 * intersection / (C.reduce_sum(x) + C.reduce_sum(y))
shape = (1, 2, 2)
x1 = np.ones(shape)
y1 = np.reshape([0, 1, 0, 1], shape)
x = C.sanitize_input(x1)
y = C.sanitize_input(y1)
dice_coefficient(x, y).eval({x: x1, y: y1})
数组([0.66666669],dtype=float32)
【讨论】: