陆地移动距离的python实现
Earth Mover s Distance,即陆地移动距离,是一种度量准则。光线变化能引起颜色直方图的漂移,引起颜色值位置发生变化,这时候一些直方图的比较匹配策略失效。EMD算法本身是一个通用的算法,它实际上度量的是怎样讲一个直方图的形状转变为另一个直方图的形状,包括直方图的部分(或全部)到一个新的位置,可以在直方图任何维的直方图上进行这种度量。
代码中的输入是我们要度量的直方图!
class EarthMoversDistanceLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x, y):
# input has dims: (Batch x Bins)
bins = x.size(1)
r = torch.arange(bins)
s, t = torch.meshgrid(r, r)
tt = t >= s
cdf_x = torch.matmul(x, tt.float().cuda())
cdf_y = torch.matmul(y, tt.float().cuda())
return torch.sum(torch.square(cdf_x - cdf_y), dim=1)