CNTK:定义自定义损失函数(Sørensen-Dice 系数)
CNTK: Define a custom loss function (Sørensen-Dice coefficient)
我想在 CNTK/Python 中使用 Wiki: Sørensen–Dice coefficient 作为损失函数。如何定义自定义损失函数。
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)
回答你更笼统的问题"How can I define a custom loss function:"
在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
最后,多任务学习可以通过使用损失函数来简单实现,损失函数是多个损失的加权和。
我想在 CNTK/Python 中使用 Wiki: Sørensen–Dice coefficient 作为损失函数。如何定义自定义损失函数。
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)
回答你更笼统的问题"How can I define a custom loss function:"
在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
最后,多任务学习可以通过使用损失函数来简单实现,损失函数是多个损失的加权和。