numpy.random.RandomState的使用
作者:互联网
import numpy as np
numpy.random.RandomState是一个伪随机数生成器,主要用来生成一组伪随机数。伪随机数是用确定性的算法计算出来的似来自[0,1]均匀分布的随机数序列。并不真正的随机,但具有类似于随机数的统计特征,如均匀性、独立性等
import numpy as np
rng=np.random.RandomState(123)
a=rng.randn(2,3)
a
import numpy as np
rng=np.random.RandomState(0)
b=rng.randn(2,3)
b
rng=np.random.RandomState(123)
c=rng.randn(2,3)
c
d=rng.randn(3,2)
d
因为是伪随机数,所以必须在rng这个变量下使用,如果不这样做,那么就得不到相同的随机数组了,即便你再次输入了numpy.random.RandomState():
下面给出两个自定义函数来帮助更好地理解:
def rng1():
for i in range(4):
rng = np.random.RandomState(0)
print("i = ",i)
print(rng.rand(3,2))
rng1()
i = 0
[[0.5488135 0.71518937]
[0.60276338 0.54488318]
[0.4236548 0.64589411]]
i = 1
[[0.5488135 0.71518937]
[0.60276338 0.54488318]
[0.4236548 0.64589411]]
i = 2
[[0.5488135 0.71518937]
[0.60276338 0.54488318]
[0.4236548 0.64589411]]
i = 3
[[0.5488135 0.71518937]
[0.60276338 0.54488318]
[0.4236548 0.64589411]]
def rng2():
rng = np.random.RandomState(0)
for i in range(4):
print("i = ",i)
print(rng.rand(3,2))
rng2()
i = 0
[[0.5488135 0.71518937]
[0.60276338 0.54488318]
[0.4236548 0.64589411]]
i = 1
[[0.43758721 0.891773 ]
[0.96366276 0.38344152]
[0.79172504 0.52889492]]
i = 2
[[0.56804456 0.92559664]
[0.07103606 0.0871293 ]
[0.0202184 0.83261985]]
i = 3
[[0.77815675 0.87001215]
[0.97861834 0.79915856]
标签:random,rng,RandomState,随机数,np,numpy 来源: https://www.cnblogs.com/Ada-CN/p/15660208.html