pytorch交换数组元素坑

写 PermutePatch 时遇到一个 bug:在试图交换 PyTorch 数组的两个元素时,两个位置都变成同一个元素!具体见测试代码。本文兼测几种交换情况:

  • 两个 python 变量
  • list 两个元素
  • numpy 数组两个元素
  • pytorch 数组两个元素
import numpy as np
import torch

print("\tvar")
a, b = 1, 2
print("before:", a, b)
a, b = b, a
print("after:", a, b)

print("\tlist")
c = [1, 2, 3, 4]
print("before:", c)
c[0], c[2] = c[2], c[0]
print("after:", c)

print("\tnumpy")
d = np.array([1, 2, 3, 4])
print("before:", d)
d[0], d[2] = d[2], d[0]
print("after:", d)

print("\ttorch")
e = torch.tensor([1, 2, 3, 4])
print("before:", e)
e[0], e[2] = e[2], e[0]
print("after:", e) # 出事

f = torch.tensor([1, 2, 3, 4])
f[0], f[2] = f[2].item(), f[0].item()
print("after 2:", f) # 如期

输出:

        var
before: 1 2
after: 2 1
        list
before: [1, 2, 3, 4]
after: [3, 2, 1, 4]
        numpy
before: [1 2 3 4]
after: [3 2 1 4]
        torch
before: tensor([1, 2, 3, 4])
after: tensor([3, 2, 3, 4])		# <- 两个 `3`
after 2: tensor([3, 2, 1, 4])

其中 e 组的换法会出现两个 3;而 f 组加上 .item() 之后,结果就如预期了。

哇,呢啲乜嘢 bug 来㗎,黐线

你可能感兴趣的:(环境,pytorch,python,numpy,bug)