performance - 使张量中的值符合给定范围

标签 performance machine-learning lua torch

我有一个 3d 张量,并希望确保所有值都落在给定范围内(在本例中为 0-1)。为了做到这一点,我已经编写了以下代码:

    function capTo1or0 (Tensor3d)

       tensor_width=Tensor3d:size()[2]
       tensor_height=Tensor3d:size()[3]
       tensor_depth=Tensor3d:size()[1]
       for i=1,tensor_width,1 do
           for j=1,tensor_height,1 do
               for k=1,tensor_depth,1 do 
                   if(Tensor3d[k][i][j])>1 then

                       Tensor3d[k][i][j]=1

                   end  
                   if(Tensor3d[k][i][j]<0.0) then
                        Tensor3d[k][i][j]=0.0           
                   end
               end
           end
        end
       return Tensor3d
    end

它有效,只有一个问题:性能很糟糕,我知道必须有一些更好的方法来做到这一点,然后循环整个数组,因为大多数张量操作不涉及手动循环数组速度更快。有人知道如何使其更快吗?

An example in this is say that I have a `2-3-3` array with the values

    [1,  2,  0.5][0.5,0.2,-0.2]
     [0.1,0.2,0.3][1,  1,   1  ]
    [-2, -1, 2  ][0.2,-5,-1   ]

then I expect an outcome of 
    [1,  1,  0.5][0.5,0.2,0]
    [0.1,0.2,0.3][1,  1,   1  ]
    [0, 0, 1  ]  [0.2,0,-1   ]

将 0 下限以下的每个值替换为 0,将 1 上限以上的每个值替换为 1。

有人知道如何快速做到这一点吗?

最佳答案

我从未使用过 Torch,但它的文档说: http://torch7.readthedocs.io/en/rtd/maths/#torch.clamp

[res] torch.clamp([res,] tensor1, min_value, max_value)

Clamp all elements in the tensor into the range [min_value, max_value]. ie:

y_i = x_i, if x_i >= min_value or x_i <= max_value
    = min_value, if x_i < min_value
    = max_value, if x_i > max_value

z=torch.clamp(x,0,1) will return a new tensor with the result of x bounded between 0 and 1.

torch.clamp(z,x,0,1) will put the result in z.

x:clamp(0,1) will perform the clamp operation in place (putting the result in x).

z:clamp(x,0,1) will put the result in z.

我猜这就是您要找的东西?

关于performance - 使张量中的值符合给定范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417227/

相关文章:

java - apache HttpClients 的奇怪瓶颈(同步和异步)

machine-learning - 各个 LSTM 单元中的隐藏单元是什么?

c++ - 如何从 C++ 中的 Lua 函数获取返回表?

Lua:如何使用 debug.getlocal

lua - Lua 有语言标准吗?

javascript - 如何将过期 header 添加到 Meteor 静态 Assets

c# - 使用反射的对象审计

python - Keras 损失仅在 epoch 结束时变为 nan

machine-learning - 训练/测试拆分之前或之后的欠采样

java - 延迟加载 PDF