固定所有(pytorch,python,numpy)的随机种子

    args.seed =42
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)
    torch.cuda.manual_seed(args.seed)

    np.random.seed(args.seed)
    random.seed(args.seed)
    torch.backends.cudnn.deterministic = True

在需要生成随机数据的实验中,每次实验都需要生成数据。设置随机种子是为了确保每次生成固定的随机数,这就使得每次实验结果显示一致了,有利于实验的比较和改进。使得每次运行该 .py 文件时生成的随机数相同。

pytorch (cpu,gpu,多gpu)

1. 为CPU中设置种子,生成随机数:

torch.manual_seed(seed)

2. 为特定GPU设置种子,生成随机数:

torch.cuda.manual_seed(number)

3. 为所有GPU设置种子,生成随机数:

torch.cuda.manual_seed_all(number)

不设置随机种子,则每次随机结果不同。设置之后随机结果相同。

# 不设置随机种子
import torch
print(torch.rand(1)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数


# 设置随机种子
import torch
# 设置随机种子
torch.manual_seed(0) # 不同的随机种子生成随机数不同,换成其他值随机数不一样
# 生成随机数
print(torch.rand(1)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
print(torch.rand(1)) # 设置随机种子后,是每次运行.py文件的输出结果都一样,随机函数结果不同。
# 输出结果:
tensor([0.4963])
tensor([0.7682])


#若想要结果都一样,那你可以在每个随机函数前都设置一模一样的随机种子
torch.manual_seed(0)
print(torch.rand(1))
torch.manual_seed(0)
print(torch.rand(1))
# 输出结果:
tensor([0.4963])
tensor([0.4963])


numpy

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 ]]

python

random.seed(1)
print(random.randrange(10))

本质就是使用自己的函数,使用种子后随机数固定。像random.seed(),使用random的随机函数就会固定随机数。使用np.random.seed(),np.random.randn()就会固定随机数。

参考:

【PyTorch】torch.manual_seed() 详解_想变厉害的大白菜的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_41458274/article/details/129740005
今日推荐