random.seed和np.random.seed用法

背景

在深度学习训练过程中,为帮保证算法的可复现,通常设置随机种子保证多次训练的随机变量一致。

代码

本blog通过一下测试代码,验证说明了两种随机数随机数组的设置方法的有效性:

random.seed + random.random 数
np.random.seed +np.random.randn 数组
import random
import numpy as np

# random.seed  +  random.random (能够一致)

print('未设置参数:')
print('第1个随机数:',random.random()) 
print('第2个随机数:',random.random()) 


print('设置参数后:')
random.seed( 10 )
print('第3个随机数:',random.random()) 
print('第4个随机数:',random.random()) #seed一次有效
random.seed( 10 )
print('第5个随机数:',random.random()) 

# np.random.seed  +random.random  (不能够一致)
np.random.seed(1)
L1 = random.random()
np.random.seed(1)
L2 = random.random()
np.random.seed(1)
L3 = random.random()
print('第6个随机数:',L1)
print('第7个随机数:',L2)
print('第8个随机数:',L3)

# np.random.seed  +np.random.randn  (能够一致)
np.random.seed(4)
L1 = np.random.randn(3,3)
np.random.seed(4)
L2 = np.random.randn(3,3)
print('第1个随机数组:\n',L1)
print('第2个随机数组:\n',L2)

# random.seed  +np.random.randn   (不能够一致)
random.seed(2)
L1 = np.random.randn(3,3)
random.seed(2)
L2 = np.random.randn(3,3)
print('第2个随机数组:\n',L1)
print('第3个随机数组:\n',L2)
未设置参数:1个随机数: 0.71481938945136882个随机数: 0.801382391706327
设置参数后:3个随机数: 0.57140259468991354个随机数: 0.42888905467511465个随机数: 0.57140259468991356个随机数: 0.42888905467511467个随机数: 0.57809130113447048个随机数: 0.206098232139501741个随机数组:
 [[ 0.05056171  0.49995133 -0.99590893]
 [ 0.69359851 -0.41830152 -1.58457724]
 [-0.64770677  0.59857517  0.33225003]]2个随机数组:
 [[ 0.05056171  0.49995133 -0.99590893]
 [ 0.69359851 -0.41830152 -1.58457724]
 [-0.64770677  0.59857517  0.33225003]]2个随机数组:
 [[-1.14747663  0.61866969 -0.08798693]
 [ 0.4250724   0.33225315 -1.15681626]
 [ 0.35099715 -0.60688728  1.54697933]]3个随机数组:
 [[ 0.72334161  0.04613557 -0.98299165]
 [ 0.05443274  0.15989294 -1.20894816]
 [ 2.22336022  0.39429521  1.69235772]]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值