火炬-在尺寸上应用功能 [英] Torch - Apply function over dimension

查看:97
本文介绍了火炬-在尺寸上应用功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将针对3D张量设计的功能应用于4D张量中的每个3D张量,即image.translate().例如,我可以将函数分别应用于两张尺寸为(3,50,50)的图像,但是如果我可以输入它们的4D串联(2,3,50,50),那就太好了.

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).

这可能可以在for循环中完成,但是我想知道是否有任何内置函数可以做到这一点.谢谢.

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

推荐答案

我没有设法在Torch中找到这样的功能.当然,您可以定义自己,让自己的生活更快乐:

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

示例:

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]

这篇关于火炬-在尺寸上应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆