描述

设置CPU生成随机数的种子,方便下次复现实验结果。

语法

torch.manual_seed(seed) → torch._C.Generator

参数

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

返回

返回一个torch.Generator对象。

示例

设置随机种子

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

每次运行test.py的输出结果都是一样:

tensor([0.4963])

没有随机种子

# test.py
import torch

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

每次运行test.py的输出结果都不相同:

tensor([0.2079])
----------------------------------
tensor([0.6536])
----------------------------------
tensor([0.2735])

注意

设置随机种子后,是每次运行test.py文件的输出结果都一样,而不是每次随机函数生成的结果一样:

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

输出:

tensor([0.4963])
tensor([0.7682])

可以看到两次打印torch.rand(1)函数生成的结果是不一样的,但如果你再运行test.py,还是会打印:

tensor([0.4963])
tensor([0.7682])

但是,如果你就是想要每次运行随机函数生成的结果都一样,那你可以在每个随机函数前都设置一模一样的随机种子:

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

输出:

tensor([0.4963])
tensor([0.4963])

引用

https://pytorch.org/docs/stable/generated/torch.manual_seed.html

相关

【python】random.seed()用法详解

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐