torch/lua 中的推土机距离(或如何使用标准来获得比较)

Earth movers distance in torch/lua (or how to use a criterion to just obtain a comparison)

我正在尝试计算 torch7 中两个直方图之间的距离,为此我正在考虑使用推土机的距离。现在我知道在 python 中使用 https://github.com/garydoranjr/pyemd 之类的东西并不难,但是我的数据在 torch 中,需要多次执行此计算。因此,在 torch7 和 python 之间移动整个数据不是一种选择。

所以我的问题是 torch7 中最快的推土机距离计算器是什么?我已经搜索但找不到任何类似库的东西,希望有一些更好的方法来实现这个然后逐行翻译 python 代码,特别是看到火炬通常如何更好地处理 gpu 上的事情。

编辑 我找到了 this 但不确定如何使用它。

我目前有以下代码:

    function ColourCompareHistEMD (imagers)
        sumdistance=0
        k={}
        for i=1,$images do 
            k[i]=torch.bhistc(images[i],20,-100,100)
        end

        for i=1,$images do 
           for j=1,$images do 
                #what to do here? 
           end
        end
    end


My current best guess is something like this:

function ColourCompareHistEMD (images)
    sumdistance=0
    r={}
    for i=1,#images do 
        print(images[i])

        r[i]=torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    end

    for i=1,#images do 
       for j=1,#images do 
            criterion = nn.EMDCriterion()
            criterion:forward(r[i],r[j])
            sumdistance=sumdistance+criterion.loss          

       end
   end

return sumdistance
end 

但这似乎不起作用,因为 criterion.loss 不起作用,它给了我一个错误

/home/thijser/torch/install/bin/luajit: bad argument #2 to '?' (out of range at /home/thijser/torch/pkg/torch/generic/Tensor.c:704)
stack traceback:
    [C]: at 0x7f2048fdc530
    [C]: in function '__newindex'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:52: in function 'preprocess'
    /home/thijser/torch/install/share/lua/5.1/EMDCriterion.lua:255: in function 'forward'
    imageSelector.lua:343: in function 'evalHueImages'
    imageSelector.lua:66: in function 'evaluate'
    imageSelector.lua:81: in function 'SelectTop'
    imageSelector.lua:151: in function 'evolve'
    imageSelector.lua:158: in function <imageSelector.lua:156>
    [C]: in function 'dofile'
    ...jser/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x5641c3f40470

但我不确定如何使用它,以便在评论中计算图像 i 和 j 之间的推土机距离。

看来 EMDCriterion 期望输入和目标至少是二维的。它还希望您比较中的点水平放置。由于 torch.histc 的结果是一维的,您可以将其重塑为二维行张量,如下所示:

for i=1,#images do 
    print(images[i])
    local hist = torch.histc(images[i][1]:view(images[i][1]:nElement()),20,-100,100)
    r[i] = hist:reshape(1,hist:nElement())
end

此外,我尝试了 运行 代码

criterion:forward(r[i],r[j])
print(criterion.loss)

结果是 nil。试试这个来累积损失:

local loss = criterion:forward(r[i],r[j])
sumdistance = sumdistance + loss

此外,如果您在嵌套 for 循环之外定义条件 criterion = nn.EMDCriterion(),效率会更高一些。