我有一个关于 numpy 随机的问题,尤其是随机播放和种子。
'seed' 用于生成相同的随机序列。
'shuffle' 用于洗牌。
要以相同的顺序打乱两个列表,此代码有效:
idx = [1, 2, 3, 4, 5, 6]
idx2 = [1, 2, 3, 4, 5, 6]
seed = np.random.randint(0, 100000)
np.random.seed(seed)
np.random.shuffle(idx)
np.random.seed(seed)
np.random.shuffle(idx2)
结果 :
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
[5, 3, 1, 2, 4, 6] [5, 3, 1, 2, 4, 6]
[1, 5, 3, 2, 4, 6] [1, 5, 3, 2, 4, 6]
[2, 5, 3, 4, 6, 1] [2, 5, 3, 4, 6, 1]
[2, 5, 6, 3, 4, 1] [2, 5, 6, 3, 4, 1]
[4, 5, 6, 1, 2, 3] [4, 5, 6, 1, 2, 3]
我可以检查此代码是否运行良好。
...省略
解决了,但是问题不清楚。
在简化版本中重新定义问题:
idx = [1, 2, 3, 4, 5, 6]
for i in range(10):
seed = np.random.randint(0, 10000)
idx2 = [1, 2, 3, 4, 5, 6]
np.random.seed(seed)
np.random.shuffle(idx)
np.random.seed(seed)
np.random.shuffle(idx2)
然后,对于每次迭代, idx != idx2 是明确的。
- 问题是这样的:为什么 idx 和 idx2 不一样?
但是,我没有注意到 idx2 的重新初始化。(实际上,原始代码并非如此简单 - 对于每次迭代,idx2 都会获取新的图像目录。 - 答案中的“imlist”与简化版中的 idx2 扮演相同的角色。)
阅读@tel 的评论后,我发现了问题。- idx 也应该重新初始化或只使用基于索引的洗牌。
固定版本
for i in range(10):
seed = np.random.randint(0, 10000)
idx2 = [1, 2, 3, 4, 5, 6]
idx = [1, 2, 3, 4, 5, 6]
np.random.seed(seed)
np.random.shuffle(idx)
np.random.seed(seed)
np.random.shuffle(idx2)
然后, idx == idx2 :真