pytorch好像没有直接原地进行shuffle函数。
如果使用外部的库函数random对pytorch的张量shuffle,同一个值可能会被取多次,并不是对数据进行打乱。
所以尝试对下标进行shuffle,然后根据下标取对应的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import torch import random a = torch.rand(9) print('a:\n', a) random.shuffle(a) print('random.shuffle(a):\n', a) index = [i for i in range(len(a))] print('index\n', index) random.shuffle(index) print('random.shuffle(index):\n', index) print('shuffle tensor:\n', a[index]) |

总结:random.shuffle()用于对列表打乱,对tensor打乱时会出现问题,所以构建一个下标列表,对列表shuffle。