使用MindSpore设置了随机种子,但ops.Randperm 输出不符合预期

我的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接口,能够符合要求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值