如何在Pytorch的FloatTensor中更改(分配)新值?

时间:2019-04-04 01:37:53

标签: pytorch assign

我正在更改/分配数组(torch.cuda.floatTensor)上的值。我尝试了一些方法,但是没有用。请帮帮我!

#1

#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0) #3185
for i in range (0,s,1):
    if (dis[i,0] < 0):
        dis[i,0]== 0
#There is no error but It does not work.

#2

#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0)
a = torch.zeros(s, 1).cuda()
idx = (dis > a)
dis[idx] = a[idx]

AssertionError: can't compare Variable and tensor

#3

#dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)]

s = dis.size(0)
a = torch.zeros(s, 1).cuda()
for i in range (0,s,1):
    if (dis[i,0] < a[i, 0]):
        dis[i,0]==a[i, 0]

#RuntimeError: bool value of Variable objects containing non-empty      torch.cuda.ByteTensor is ambiguous

1 个答案:

答案 0 :(得分:1)

IIUC,您需要将小于0的值替换为0,只需使用torch.clamp,这是针对以下用例:

dis = dis.clamp(min=0)

示例

import torch
dis = torch.tensor([[1], [-3], [0]])
#tensor([[ 1],
#        [-3],
#        [ 0]])

dis.clamp(min=0)
#tensor([[1],
#        [0],
#        [0]])