4

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.

mattdns
  • 894
  • 1
  • 11
  • 26
  • 3
    in 2020, is there a built-in function for this now? – mitchus May 27 '20 at 14:25
  • The .apply_() function of Pytorch is similar to the .apply() function from pandas. Also , _ , in torch means the function will work "inPlace=True" – Yash Sep 07 '21 at 14:12

1 Answers1

3

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]
Alexander Lutsenko
  • 2,130
  • 8
  • 14