以下资料待梳理。
随机数种子
torch.manual_seed()
:为CPU
设置随机数种子
torch.cuda.manual_seed()
:为GPU
设置随机数种子
torch.cuda.manual_seed_all()
:为所有的GPU
设置随机数种子
random.seed()
:为random模块的随机数种子
说明
- torch.manual_seed() 一般和 torch.rand()、torch.randn() 等函数搭配使用。
- 通过指定seed值,可以令每次生成的随机数相同,从而
方便复现实验结果
。 - 设置随机种子后,是每次运行 py 文件的输出结果都一样,而不是每次随机函数生成的结果一样。
import torch
torch.manual_seed(0)
print(torch.rand(1, 2)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
print(torch.randn(1, 2)) # 返回一个张量,包含了均值0,方差1的正态分布中抽取的一组随机数
# torch.manual_seed(0)
print(torch.rand(1, 2))
print(torch.randn(1, 2))
'''
tensor([[0.4963, 0.7682]])
tensor([[-0.2905, -1.0704]])
tensor([[0.4901, 0.8964]])
tensor([[-1.0845, -1.3986]])
'''
import torch
torch.manual_seed(0)
print(torch.rand(1, 2)) # 返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数
print(torch.randn(1, 2)) # 返回一个张量,包含了均值0,方差1的正态分布中抽取的一组随机数
torch.manual_seed(0)
print(torch.rand(1, 2))
print(torch.randn(1, 2))
'''
tensor([[0.4963, 0.7682]])
tensor([[-0.2905, -1.0704]])
tensor([[0.4963, 0.7682]])
tensor([[-0.2905, -1.0704]])
'''