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]]

猜你喜欢

转载自blog.csdn.net/qq_35568823/article/details/126461753