在使用深度学习中,大家有各种各样的训练任务,torch.optim中存在的优化算法难免不能满足大家的需求,此时就需要自定义损失函数了,可参考如下过程:
import torch.nn as nn
class DiceLoss(nn.Module):
def __init__(self):
super(DiceLoss, self).__init__()
def forward(self, input, target):
return -dice_coef(input, target)
def dice_coef(input, target):
smooth = 1
input_flat = input.view(-1) # 拉平成一列,即第一维度是计算得来的
target_flat = target.view(-1)
intersection = input_flat * target_flat
return (2 * intersection.sum() + smooth) / (input_flat.sum() + target_flat.sum() + smooth)
criterion = DiceLoss().cuda() # 使用自己定义的损失函数