Pytorch随机种子详解

Pytorch随机数生成和获取详解

pytorch的random模块是支持设置和获取随机种子的,主要的方法为torch.random.manual_seed(),这个方法是用于设置种子的,参数为种子的值,获取种子的方法为torch.random.initial_seed(),返回种子的值。

设置随机种子的注意点有两个:

1.torch.random.manual_seed()设置了随机种子后,随机数会按同一种规则发散生成。

2.torch.random.manual_seed()设置了随机种子,同种初始化函数,在cpu和gpu上初始化的张量可能是不同的,这是由于cpu和gpu的随机数生成逻辑是不同的

import torch

torch.random.manual_seed(100)
data1 = torch.randn(2, 2)
print(data1)
data2 = torch.randint(0, 10, (2, 2))
print(data2)
print(torch.rand(2, 2))
print(torch.random.initial_seed())

torch.random.manual_seed(100)
data3 = torch.randn(2, 2)
print(data3)
data4 = torch.randint(0, 10, (2, 2))
print(data4)
print(torch.rand(2, 2))
print(torch.random.initial_seed())

# tensor([[ 0.3607, -0.2859],
#         [-0.3938,  0.2429]])
# tensor([[8, 0],
#         [4, 3]])
# tensor([[0.7118, 0.7876],
#         [0.4183, 0.9014]])
# 100
# tensor([[ 0.3607, -0.2859],
#         [-0.3938,  0.2429]])
# tensor([[8, 0],
#         [4, 3]])
# tensor([[0.7118, 0.7876],
#         [0.4183, 0.9014]])
# 100

由上述代码可以看出设置了随机种子后,随机数生成具有固定规则 

import torch

torch.random.manual_seed(100)
data1 = torch.randn(2, 2)
print(torch.random.initial_seed())

torch.random.manual_seed(100)
data2 = torch.randn(2, 2, device="cuda")
print(torch.random.initial_seed())

print(data1)
print(data2)
# 100
# 100
# tensor([[ 0.3607, -0.2859],
#         [-0.3938,  0.2429]])
# tensor([[ 1.4350, -1.4982],
#         [-0.8099, -1.1784]], device='cuda:0')

又上述代码可以看出,虽然随机数种子同为100,但是在cpu和gpu上生成的随机数是不同的。 

补充python random库及np.random库的随机数设置方式

python random库
import random

random.seed(100)
print(random.randint(0, 10))
random.seed(100)
print(random.randint(0, 10))
# 2
# 2
np.random库
import numpy as np

np.random.seed(100)
print(np.random.randn(2, 2))

np.random.seed(100)
print(np.random.randn(2, 2))
# [[-1.74976547  0.3426804 ]
#  [ 1.1530358  -0.25243604]]
# [[-1.74976547  0.3426804 ]
#  [ 1.1530358  -0.25243604]]

注意,在python的random库和np.random中,随机种子的设置后也会影响后续的所有随机初始化函数直至随机种子重新设置

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值