torch.manual_seed(seed)用法及注意事项

torch.manual_seed(0) 是 PyTorch 中的函数调用,用于设置随机数生成器的种子。通过指定种子值,我们可以确保每次运行代码时生成的随机数序列是相同的,这样有助于保持实验的可复现性。

在深度学习中,训练过程中的随机化(例如权重初始化、数据采样等)可能会影响模型的性能和结果。因此,在进行实验时,通过设置种子可以确保每次运行代码时都使用相同的随机数序列,从而使结果可重现。

需要注意的是,torch.manual_seed(0) 只会对使用了 PyTorch 内置的随机数生成器的部分产生影响,有些库可能使用了自己的随机数生成器,不受该函数调用的影响。
但是同时应注意,每次生成随机数时,都应设置一样的随机种子,才能保证生成的随机数都相同。如:https://zhuanlan.zhihu.com/p/662224844。

 

“You can use torch.manual_seed() to seed the RNG for all devices (both CPU and CUDA):”

如官方文档所述,torch.manual_seed(seed)用来生成CPU或GPU的随机种子,方便下次复现实验结果。

1.如果未设置随机种子,在CPU中生成随机数:

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

则每次运行test.py返回的结果都是不同的处于(0, 1)之间的随机数:

输出结果:#1

tensor([0.5432])

输出结果:#2

tensor([0.3421])

输出结果:#3

tensor([0.8653])

2.设置随机种子后,每次运行生成的随机数都是相同的

# test.py
import torch

torch.manual_seed(0)
print(torch.rand(1))

输出结果:#1,#2,#3结果一致

tensor([0.3564])

3.若更改随机种子,则会生成不同的值

# test.py
import torch

torch.manual_seed(1)
print(torch.rand(1))

输出结果:#1,#2,#3结果一致

tensor([0.7653])

4.设置随机种子后,每次运行文件生成的随机值相同,但是每次生成的结果却不一样:

# test.py
import torch

torch.manual_seed(1)
print(torch.rand(1))
print(torch.rand(1))

输出结果:#1,#2,#3结果一致

tensor([0.4356])
tensor([0.5647])

5.若希望每次运行的随机数结果都一样,则需要在每次随机数前设置相同的种子

# test.py
import torch

torch.manual_seed(1)
print(torch.rand(1))
torch.manual_seed(1)
print(torch.rand(1))

输出结果:

tensor([0.4356])
tensor([0.4356])

 

 

 

posted on 2024-05-07 19:45  lmqljt  阅读(231)  评论(0编辑  收藏  举报

导航