
正文
nu.random.seed()如何理解
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
结论:
np.random.seed(a) # 按照规定的顺序生成随机数
# 参数a指定了随机数生成的起始位置;
# 如果两处都采用了np.random.seed(a),且两处的参数a相同,则生成的随机数也相同;
# 不同的参数a执行了随机数生成的不同位置;随便选即可;
验证:
1.以np.random.randn()函数为例
import numpy as np
if __name__ == '__main__':
i = 0
while(i < 6):
if(i < 3):
np.random.seed(0)
print(np.random.randn(1, 5)) # 1.打印之前都执行了np.random.seed(0),打印3组相同结果 i:[0,1,2]
else:
print(np.random.randn(1, 5)) # 2.接着上面随机数生成的位置,打印3组不同结果 i:[3,4,5]
pass
i += 1
i = 0
while(i<2):
print(np.random.randn(1, 5)) # 3.接着上面随机数生成的位置,打印2组不同结果 i:[0,1]
i += 1
print(np.random.randn(2, 5)) # 4.接着上面随机数生成的位置,打印1组不同结果 i:[2]
print("----------重置----------")
np.random.seed(0) # 重新从相同位置开始生成随机数
i = 0
while(i < 8):
print(np.random.randn(1, 5)) # 5.生成了8组和上面相同的随机数
i += 1
结果:
# 1.打印之前都执行了np.random.seed(0),打印3组相同结果 i:[0,1,2]
[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799]]
[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799]]
[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799]] # 2.接着上面随机数生成的位置,打印3组不同结果 i:[3,4,5]
[[-0.97727788 0.95008842 -0.15135721 -0.10321885 0.4105985 ]]
[[ 0.14404357 1.45427351 0.76103773 0.12167502 0.44386323]]
[[ 0.33367433 1.49407907 -0.20515826 0.3130677 -0.85409574]] # 3.接着上面随机数生成的位置,打印2组不同结果 i:[0,1]
[[-2.55298982 0.6536186 0.8644362 -0.74216502 2.26975462]]
[[-1.45436567 0.04575852 -0.18718385 1.53277921 1.46935877]] # 4.接着上面随机数生成的位置,打印1组不同结果 i:[2]
[[ 0.15494743 0.37816252 -0.88778575 -1.98079647 -0.34791215]
[ 0.15634897 1.23029068 1.20237985 -0.38732682 -0.30230275]] ----------重置---------- # 5.生成了8组和上面相同的随机数
[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799]]
[[-0.97727788 0.95008842 -0.15135721 -0.10321885 0.4105985 ]]
[[ 0.14404357 1.45427351 0.76103773 0.12167502 0.44386323]]
[[ 0.33367433 1.49407907 -0.20515826 0.3130677 -0.85409574]]
[[-2.55298982 0.6536186 0.8644362 -0.74216502 2.26975462]]
[[-1.45436567 0.04575852 -0.18718385 1.53277921 1.46935877]]
[[ 0.15494743 0.37816252 -0.88778575 -1.98079647 -0.34791215]]
[[ 0.15634897 1.23029068 1.20237985 -0.38732682 -0.30230275]]
2.指定不同的随机数种子
import numpy as np if __name__ == '__main__':
i = 0
np.random.seed(0)
while(i<3):
print(np.random.randn(1, 5))
i += 1
i = 0
np.random.seed(1)
i = 0
while(i<3):
print(np.random.randn(1, 5))
i += 1
[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799]]
[[-0.97727788 0.95008842 -0.15135721 -0.10321885 0.4105985 ]]
[[ 0.14404357 1.45427351 0.76103773 0.12167502 0.44386323]]
[[ 1.62434536 -0.61175641 -0.52817175 -1.07296862 0.86540763]]
[[-2.3015387 1.74481176 -0.7612069 0.3190391 -0.24937038]]
[[ 1.46210794 -2.06014071 -0.3224172 -0.38405435 1.13376944]]
总结:只要指定相同的随机数种子,在任何电脑上运行np.random.randn(),都会生成相同的结果;说明, 随机数种子只是指定了一个随机数生成的位置,不同的参数对应不同的位置 ,用0, 1, 2,...随意了







