np.random.seed()函数用于生成指定随机数。
seed()被设置了之后,np,random.random()可以按顺序产生一组固定的数组;
如果使用相同的seed()值,则每次生成的随机数都相同,如果不设置这个值,那么每次生成的随机数不同;
只在调用的时候seed()一下并不能使生成的随机数相同,需要每次调用都seed()一下,表示种子相同,从而生成的随机数相同。
- >>> import random
-
- # 随机数不一样
- >>> random.seed()
- >>> print('随机数1:',random.random())
- >>> random.seed()
- >>> print('随机数2:',random.random())
-
- # 随机数一样
- >>> random.seed(1)
- >>> print('随机数3:',random.random())
- >>> random.seed(1)
- >>> print('随机数4:',random.random())
- >>> random.seed(2)
- >>> print('随机数5:',random.random())
-
- '''
- 随机数1: 0.7643602170615428
- 随机数2: 0.31630323818329664
- 随机数3: 0.13436424411240122
- 随机数4: 0.13436424411240122
- 随机数5: 0.9560342718892494
- '''
-
- >>> import numpy as np
-
- >>> np.random.seed(1)
- >>> L1 = np.random.randn(3, 3)
- >>> np.random.seed(1)
- >>> L2 = np.random.randn(3, 3)
- >>> print(L1)
- >>> print(L2)
- # 结果
- [[ 1.62434536 -0.61175641 -0.52817175]
- [-1.07296862 0.86540763 -2.3015387 ]
- [ 1.74481176 -0.7612069 0.3190391 ]]
-
- [[ 1.62434536 -0.61175641 -0.52817175]
- [-1.07296862 0.86540763 -2.3015387 ]
- [ 1.74481176 -0.7612069 0.3190391 ]]
-
torch.manual_seed(args.seed)
为CPU设置种子用于生成随机数,以使得结果是确定的, 方便下次复现;
随机种子作用域是在设置时到下一次设置时
torch.manual_seed(seed) → torch._C.Generator
seed,int类型,是种子 – CPU生成随机数的种子。取值范围为 [-0x8000000000000000, 0xffffffffffffffff] ,十进制是 [-9223372036854775808, 18446744073709551615] ,超出该范围将触发 RuntimeError 报错。
- # 为CPU中设置种子,生成随机数:
- torch.manual_seed(number)
-
- #为特定GPU设置种子,生成随机数:
- torch.cuda.manual_seed(number)
-
- #为所有GPU设置种子,生成随机数:
- # 如果使用多个GPU,应该使用torch.cuda.manual_seed_all()为所有的GPU设置种子。
- torch.cuda.manual_seed_all(number)
参考:【PyTorch】torch.manual_seed() 详解_想变厉害的大白菜的博客-CSDN博客_torch.manual_seed