我的mindspore版本为1.7
我按照官网手册,指定了ms随机种子为固定值,并使用ops.Randperm获取指定长度的随机排列。
以下为代码:
import mindspore as ms
from mindspore import Tensor, int32
import mindspore.ops as op
ms.set_seed(56)
def randperm(x):
return op.Randperm(max_length=x)(Tensor([x], dtype=int32))
print(randperm(10))
print(randperm(10))
print(randperm(10))
在固定了随机种子后,多次运行程序的结果应该是相同的
我连续运行了三次程序,打印的结果不符合预期:
(mindspore_zyb) [root@localhost zyb_work]# python work.py
[1 9 3 4 8 2 0 6 7 5]
[4 8 3 2 1 7 0 9 5 6]
[9 1 3 4 0 7 8 2 5 6]
(mindspore_zyb) [root@localhost zyb_work]# python work.py
[8 4 7 6 9 0 5 2 3 1]
[8 6 1 0 9 3 7 5 4 2]
[9 2 7 0 3 6 8 4 5 1]
(mindspore_zyb) [root@localhost zyb_work]# python work.py
[1 2 7 5 9 8 0 6 3 4]
[7 3 5 4 0 2 1 6 9 8]
[7 6 9 0 3 5 2 1 4 8]
我使用pytorch实现了上述相同功能:
import torch
g = torch.Generator()
g.manual_seed(20)
print(torch.randperm(10, generator=g))
print(torch.randperm(10, generator=g))
print(torch.randperm(10, generator=g))
连续运行三次程序,输出符合预期:
(torch_zyb) [root@localhost zyb_work]# python work2.py
tensor([1, 2, 9, 5, 4, 3, 7, 6, 0, 8])
tensor([0, 2, 4, 5, 6, 3, 7, 9, 8, 1])
tensor([7, 3, 2, 5, 4, 8, 1, 6, 9, 0])
(torch_zyb) [root@localhost zyb_work]# python work2.py
tensor([1, 2, 9, 5, 4, 3, 7, 6, 0, 8])
tensor([0, 2, 4, 5, 6, 3, 7, 9, 8, 1])
tensor([7, 3, 2, 5, 4, 8, 1, 6, 9, 0])
(torch_zyb) [root@localhost zyb_work]# python work2.py
tensor([1, 2, 9, 5, 4, 3, 7, 6, 0, 8])
tensor([0, 2, 4, 5, 6, 3, 7, 9, 8, 1])
tensor([7, 3, 2, 5, 4, 8, 1, 6, 9, 0])
请问我该如何修改代码使得mindspore的输出也符合预期?
****************************************************解答*****************************************************
选择了numpy 的 np.random.permutation接口,能够符合要求。