【问题标题】:Make values in tensor fit in given range使张量中的值适合给定范围
【发布时间】:2017-11-09 01:51:06
【问题描述】:

我有一个 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 上限以上的每个值。

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

【问题讨论】:

  • 抱歉,数组/张量周围的格式不太理想,它一直抱怨未格式化的代码,我认为关键字 in 然后混淆了它。如果您还有任何问题,请发表评论。

标签: performance machine-learning lua torch


【解决方案1】:

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

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

将张量中的所有元素夹在 [min_value, 最大值]。即:

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) 将返回一个新的张量,其结果为 x 介于 0 和 1 之间。

torch.clamp(z,x,0,1) 会将结果放入 z 中。

x:clamp(0,1) 将执行夹紧操作(将 结果是 x)。

z:clamp(x,0,1) 会将结果放入 z 中。

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

【讨论】:

  • 啊,谢谢,clamped 是我要找的词!
猜你喜欢
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
相关资源
最近更新 更多