gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:51:24 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com