如何更新张量?
How to update a Tensor?
我在使用以前的张量更新张量时遇到了一些麻烦。
我的问题:假设我有一个张量 x1
[Nx1] 和一个通过前一个 x2
[Nx1] 计算的新张量。现在我想更新 x2
小于 x1
的元素。我正在使用 dtype=torch.cuda.FloatTensor
。
This is the straight code in Python
:
import numpy as np
...
index = np.where(x1 > x2)
x2[index] = x1[index]
Why can I do this using PyTorch
with dtype=torch.cuda.FloatTensor
?
And if the x1
change to [NxD]
谢谢!
代码看起来与 numpy 非常相似:
idx = (x1 > x2)
x2[idx] = x1[idx]
使用一些预定义数组并打印 x2
:
x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda()
x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda()
3 3 3 4 5
[torch.cuda.FloatTensor of size 5 (GPU 0)]
NxN 维张量的代码相同。使用:
x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda()
x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda()
3 3 5
3 4 5
[torch.cuda.FloatTensor of size 2x3 (GPU 0)]
我在使用以前的张量更新张量时遇到了一些麻烦。
我的问题:假设我有一个张量 x1
[Nx1] 和一个通过前一个 x2
[Nx1] 计算的新张量。现在我想更新 x2
小于 x1
的元素。我正在使用 dtype=torch.cuda.FloatTensor
。
This is the straight code in
Python
:
import numpy as np
...
index = np.where(x1 > x2)
x2[index] = x1[index]
Why can I do this using
PyTorch
withdtype=torch.cuda.FloatTensor
? And if thex1
change to [NxD]
谢谢!
代码看起来与 numpy 非常相似:
idx = (x1 > x2)
x2[idx] = x1[idx]
使用一些预定义数组并打印 x2
:
x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda()
x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda()
3 3 3 4 5 [torch.cuda.FloatTensor of size 5 (GPU 0)]
NxN 维张量的代码相同。使用:
x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda()
x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda()
3 3 5
3 4 5 [torch.cuda.FloatTensor of size 2x3 (GPU 0)]