pytorch保证实验的可重复性方法——torch.manual_seed()设置随机数种子使用方法

保证可重复性实验方法

参考以下代码:

import torch
import numpy as np

SEED=0
np.random.seed(SEED)
torch.manual_seed(SEED)  # 为CPU设置种子用于生成随机数,以使得结果是确定的
torch.cuda.manual_seed(SEED)  # 为GPU设置随机种子
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.benchmark = False  # if benchmark=True, deterministic will be False
torch.backends.cudnn.deterministic = True

torch.manual_seed()作用

为CPU/GPU生成随机数种子,方便下次根据这次的随机数参数进行复现实验结果。

torch.manual_seed()参数

torch.manual_seed()为CPU/GPU生成随机数的种子。取值范围为[-0x8000000000000000, 0xffffffffffffffff],十进制是[-9223372036854775808, 18446744073709551615],超出该范围将触发RuntimeError报错。

实践

# test.py
import torch
SEED=0
torch.manual_seed(SEED)
print(torch.rand(2))`在这里插入代码片`

每次运行完test.py文件的输出结果都是不变的:

tensor([0.4963, 0.7682])

在不设随机种子的情况下:

# test.py
import torch
print(torch.rand(2))

多次运行test.py结果都将不同:

tensor([0.1324, 0.0356])

tensor([0.8799, 0.4172])

tensor([0.0461, 0.6507])

小结

设置随机种子后,每次执行test.py文件产生的随机数都会根据随机种子来固定产生随机数据,即每次都是一样的结果,但文件同一次运行中执行多个随机函数(即rand()函数)产生的随机数之间是不同的,示例如下:

# test.py
import torch
SEED=0
torch.manual_seed(SEED)
print(torch.rand(2))
print(torch.rand(2))
print(torch.rand(2))

输出结果:

tensor([0.4963, 0.7682])
tensor([0.0885, 0.1320])
tensor([0.3074, 0.6341])

附加知识

前面的torch.manual_seed(SEED)都是为CPU设置随机数种子。下面是为GPU建立随机种子的方法

torch.cuda.manual_seed(SEED)  # 为GPU设置随机种子
torch.cuda.manual_seed_all(SEED)  # 为所有GPU设置随机种子

为了保证每次每次能完全复现出来相同的结果,可能还要加上如下代码:

torch.backends.cudnn.benchmark = False  # if benchmark=True, deterministic will be False
torch.backends.cudnn.deterministic = True

当benchmark = True时,可以让内置的cudnn的auto-tuner自动寻找最适合当前配置的高效算法,来达到优化运行效率的问题,但是这样可能导致选择的算法不同,不利于复现;但如果时为了增强运行效率可以设置True。
当deterministic = True时,每次返回的卷积算法都时确定的。

benchmark下回提升计算速度,但是由于计算中有随机性,每次网络的前馈结果略有差异,要想避免这种结果的波动就可以设置在deterministic模式下。

官方参考文档:
torch.manual_seed(seed)官方描述文档

猜你喜欢

转载自blog.csdn.net/m0_67505927/article/details/123265773