pytorch torch.manual_seed()的用法详解

2022-06-20 14:35:19

描述

设置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)的均匀分布中抽取的一组随机数

输出:每次运行   输出结果一样

tensor([0.4963])#第1次运行结果
tensor([0.4963])#第2次运行结果
tensor([0.4963])#第2次运行结果

如果不加torch.manual_seed(0)

# test.py
import torch

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

会输出一组,每次运行的输出结果都不相同:

tensor([0.0959])#第1次运行结果
tensor([0.4833])#第2次运行结果
tensor([0.4329])#第3次运行结果

注意

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

请务必看懂上面的话

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

 第一次运行结果:

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

第二次运行结果

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

每次运行脚本,输出结果一样。

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

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

 输出

tensor([0.4963])
tensor([0.4963])
  • 作者:Vertira
  • 原文链接:https://blog.csdn.net/Vertira/article/details/123041194
    更新时间:2022-06-20 14:35:19