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 来㗎,黐线

相关推荐

  1. pytorch交换数组元素

    2024-01-29 10:18:01       38 阅读
  2. Matlab矩阵中元素交换

    2024-01-29 10:18:01       39 阅读
  3. Pytorch安装小(Windows+cu111)

    2024-01-29 10:18:01       11 阅读
  4. pytorch环境配置踩记录

    2024-01-29 10:18:01       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-29 10:18:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-29 10:18:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-29 10:18:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-29 10:18:01       18 阅读

热门阅读

  1. “语法糖“

    2024-01-29 10:18:01       29 阅读
  2. IndexedDB

    IndexedDB

    2024-01-29 10:18:01      38 阅读