实现:
>>> import torch
>>> from torch import nn
>>> input = torch.randn([3,3], requires_grad=True)
>>> target = torch.empty([3,3]).random_(2)
>>> mask = torch.Tensor([[0.,0.,1.],[0.,0.,1],[1.,1.,1.]])
>>> input
tensor([[ 1.5863, 2.4546, 1.7292],
[-0.5053, 0.4821, 0.2166],
[-0.0112, 0.8775, -1.9882]], requires_grad=True)
>>> target
tensor([[1., 1., 0.],
[1., 0., 1.],
[1., 1., 0.]])
>>> mask
tensor([[0., 0., 1.],
[0., 0., 1.],
[1., 1., 1.]])
>>> input_s=input.sigmoid()
>>> input_s
tensor([[0.8301, 0.9209, 0.8493],
[0.3763, 0.6182, 0.5539],
[0.4972, 0.7063, 0.1204]], grad_fn=<SigmoidBackward>)
>>> i,u=[t.sum() for t in [input_s* target, input_s+target]]
>>> i
tensor(3.8847, grad_fn=<SumBackward0>)
>>> u
tensor(11.4727, grad_fn=<SumBackward0>)
>>> input_s1=torch.Tensor([r for r,rm in zip(input_s.flatten(),mask.flatten()) if rm==1])
>>> target1=torch.Tensor([r for r,rm in zip(target.flatten(),mask.flatten()) if rm==1])
>>> input_s1
tensor([0.8493, 0.5539, 0.4972, 0.7063, 0.1204])
>>> target1
tensor([0., 1., 1., 1., 0.])
>>> i1,u1=[t.sum() for t in [input_s1* target1, input_s1+target1]]
>>> i1
tensor(1.7575)
>>> u1
tensor(5.7272)
>>> input_s2=input_s*mask
>>> target2=target*mask
>>> i2,u2=[t.sum() for t in [input_s2* target2, input_s2+target2]]
>>> i2
tensor(1.7575, grad_fn=<SumBackward0>)
>>> u2
tensor(5.7272, grad_fn=<SumBackward0>)
>>> dc = (2 * i2 + 1) / (u2 + 1)
>>> dc = 1 - dc.mean()
>>> dc
tensor(0.3289, grad_fn=<RsubBackward1>)