使张量中的值适合给定范围

Make values in tensor fit in given range

我有一个 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.

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