






















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的随机种子,方便下次复现实验结果。
# test.py
import torch
print(torch.rand(1))
则每次运行test.py返回的结果都是不同的处于(0, 1)之间的随机数:
输出结果:#1
输出结果:#2
输出结果:#3
# test.py
import torch
torch.manual_seed(0)
print(torch.rand(1))
输出结果:#1,#2,#3结果一致
# test.py
import torch
torch.manual_seed(1)
print(torch.rand(1))
输出结果:#1,#2,#3结果一致
# 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])
# 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])
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。