random.seed()的作用(python)

random.seed(1)作用:使得随机数据可预测,即只要seed的值一样,后续生成的随机数都一样。
当我们设置相同的seed,每次生成的随机数相同。如果不设置seed,则每次会生成不同的随机数

设置seed()且seed的值一样—生成的随机数相同

import numpy as np
np.random.seed(2)
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
print(syn0)
print(syn1)

运行多次结果都是一样的:

#######第一次运行结果##########
[[-0.1280102  -0.94814754  0.09932496 -0.12935521]
 [-0.1592644  -0.33933036 -0.59070273  0.23854193]
 [-0.40069065 -0.46634545  0.24226767  0.05828419]]
[[-0.73084011]
 [ 0.02715624]
 [-0.63112027]
 [ 0.5706703 ]]
#######第二次运行结果##########
[[-0.1280102  -0.94814754  0.09932496 -0.12935521]
 [-0.1592644  -0.33933036 -0.59070273  0.23854193]
 [-0.40069065 -0.46634545  0.24226767  0.05828419]]
[[-0.73084011]
 [ 0.02715624]
 [-0.63112027]
 [ 0.5706703 ]]

设置seed()且seed的值不一样—生成的随机数不同

当seed值为2时

import numpy as np
np.random.seed(2)
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
print(syn0)
print(syn1)

结果:

[[-0.1280102  -0.94814754  0.09932496 -0.12935521]
 [-0.1592644  -0.33933036 -0.59070273  0.23854193]
 [-0.40069065 -0.46634545  0.24226767  0.05828419]]
[[-0.73084011]
 [ 0.02715624]
 [-0.63112027]
 [ 0.5706703 ]]

当seed的值为0时

import numpy as np
np.random.seed(0)
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
print(syn0)
print(syn1)

结果:

[[ 0.09762701  0.43037873  0.20552675  0.08976637]
 [-0.1526904   0.29178823 -0.12482558  0.783546  ]
 [ 0.92732552 -0.23311696  0.58345008  0.05778984]]
[[ 0.13608912]
 [ 0.85119328]
 [-0.85792788]
 [-0.8257414 ]]

当不设置seed时—生成的随机数不同

import numpy as np
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1
print(syn0)
print(syn1)

结果:

#######第一次运行结果##########
[[ 0.63051603 -0.87816765  0.90623517  0.47393602]
 [-0.5947253   0.39207476 -0.701234   -0.63498633]
 [-0.99398242 -0.94448909 -0.38235113 -0.41548786]]
[[-0.97505187]
 [-0.89961779]
 [ 0.81003048]
 [ 0.54686106]]
#######第二次运行结果##########
[[-0.49437935  0.77174974  0.92061198 -0.99606444]
 [-0.48872823  0.3233608  -0.50048627 -0.53339642]
 [-0.7347141   0.30212213 -0.78579018 -0.68301276]]
[[ 0.72968294]
 [ 0.11085167]
 [ 0.34996692]
 [-0.48830381]]

你可能感兴趣的:(python,python,seed,numpy,random)