Torch - Apply function over dimension

2019-02-27 17:54发布

问题:

I would like to be able to apply a function which is designed for a 3D tensor to each 3D tensor in a 4D tensor, namely image.translate(). For example, I can apply the function individually to two images of dimension (3,50,50) but it would be great if I could feed their 4D concatenation of (2,3,50,50).

This could probably be done in a for loop but I was wondering if there was any built in function for this. Thanks.

回答1:

I haven't managed to find such a function in Torch. You can, of course, define one yourself to make your life a little bit happier:

function apply_to_slices(tensor, dimension, func, ...)
    for i, slice in ipairs(tensor:split(1, dimension)) do
        func(slice, i, ...)
    end
    return tensor
end

Example:

function power_fill(tensor, i, power)
    power = power or 1
    tensor:fill(i ^ power)
end

A = torch.Tensor(5, 6)

apply_to_slices(A, 1, power_fill)

 1  1  1  1  1  1
 2  2  2  2  2  2
 3  3  3  3  3  3
 4  4  4  4  4  4
 5  5  5  5  5  5
[torch.DoubleTensor of size 5x6]

apply_to_slices(A, 2, power_fill, 3)

   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
   1    8   27   64  125  216
[torch.DoubleTensor of size 5x6]


标签: lua torch