背景
在深度学习训练过程中,为帮保证算法的可复现,通常设置随机种子保证多次训练的随机变量一致。
代码
本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.7148193894513688
第2个随机数: 0.801382391706327
设置参数后:
第3个随机数: 0.5714025946899135
第4个随机数: 0.4288890546751146
第5个随机数: 0.5714025946899135
第6个随机数: 0.4288890546751146
第7个随机数: 0.5780913011344704
第8个随机数: 0.20609823213950174
第1个随机数组:
[[ 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]]