torch.manual_seed()解析

torch.manual_seed() 介绍

  1. 概述

    用于设置CPU生成随机数的种子。返回一个torch.Generator对象。此时接下来运行随机函数生成的随机数都不会发生变化,方便论文复现结果。

  2. 语法

    torch.manual_seed(seed)
    
  3. 参数

    seed (int) – The desired seed. Value must be within the inclusive range [-0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff]. Otherwise, a RuntimeError is raised. Negative inputs are remapped to positive values with the formula 0xffff_ffff_ffff_ffff + seed.

测试一:不设置seed,生成随机数

代码如下:

import torch

print(torch.rand(1))  # 随机生成[0, 1)的数

每次运行结果都不同:

tensor([0.1580])
tensor([0.9103])
tensor([0.8117])

测试二:设置seed,生成随机数

代码如下:

import torch

seed = 1
torch.manual_seed(seed)

print(torch.rand(1))  # 随机生成[0, 1)的数

每次运行的结果都一样

tensor([0.7576])

测试三:设置不同seed,生成随机数

代码如下:

import torch

seed = 2
torch.manual_seed(seed)

print(torch.rand(1))  # 随机生成[0, 1)的数

每次运行结果都一样:

tensor([0.6147])

将seed改为3:

import torch

seed = 3
torch.manual_seed(seed)

print(torch.rand(1))  # 随机生成[0, 1)的数

发现运行结果不同:

tensor([0.0043])

测试五:设置相同seed,但是每次产生多个随机数

代码如下:

import torch

seed = 1
torch.manual_seed(seed)

print(torch.rand(1))  # 随机生成[0, 1)的数
print(torch.rand(1))

可以看到两次打印 torch.rand(1) 函数生成的随机数结果不同,但每次运行产生的结果还是一致。

tensor([0.7576])
tensor([0.2793])

测试四:设置相同seed,使得每次产生的随机数一致

在每个随机函数前都设置一模一样的随机种子:

import torch

seed = 1

torch.manual_seed(seed)
print(torch.rand(1))  # 随机生成[0, 1)的数

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

可以看到每次运行的结果都一样:

tensor([0.7576])
tensor([0.7576])

总结

设置不同的随机种子产生不同的随机数,只有随机数一致,每次运行代码产生的随机数就一样(不同机器上运行也一致)。

相当于一个库,不同的种子对应一个随机数库,设置不同的种子就从其对应的库中取数据,从而使得每次运行产生的随机数都一致。

参考链接

【PyTorch】torch.manual_seed() 详解

你可能感兴趣的:(pytorch,人工智能,python,深度学习)