您的位置:首页 > 其它

np.random.RandomState、np.random.rand、np.random.random、np.random_sample

2015-12-25 23:07 441 查看

0. np.random.RandomState

计算机实现的随机数生成通常为伪随机数生成器,为了使得具备随机性的代码最终的结果可复现,需要设置相同的种子值;

np.random.randn(…) ⇒

rng = np.random.RandomState(123)

rng.randn(…)

1. np.random.uniform()

首先从numpy.random.uniform说起(也即其他函数是对该函数的进一步封装)。

numpy.random.uniform(low=0.0, high=1.0, size=None)


顾名思义,从一个均匀分布(
[low, high)
:半开区间)中进行采样。

例如产生
[1, 2)
(五行五列):

>>> import numpy
>>> np.random.uniform(1, 2, (5, 5))
array([[ 1.16902081,  1.90805984,  1.30759311,  1.90598113,  1.32047656],
[ 1.58571077,  1.88009484,  1.66531622,  1.0262826 ,  1.40534658],
[ 1.81087389,  1.87981194,  1.65670468,  1.46972606,  1.66454007],
[ 1.81041299,  1.52561204,  1.79701198,  1.17840313,  1.86364978],
[ 1.72654371,  1.92870279,  1.11207754,  1.5091156 ,  1.35108628]])


2. np.random.random is Alias for np.random.random_sample

alias: 别名;

>>> id(np.random.random) == id(np.random.random_sample)
True


numpy.random.random(size=None)
# 已指定区间为[0., 1.),自然是float类型


必须以元组形式指定
size


>>> np.random.random((2, 3))
array([[ 0.14367   ,  0.48649543,  0.38761876],
[ 0.11565701,  0.6474381 ,  0.84394864]])
>>> np.random.random(2, 3)
TypeError: random_sample() takes at most 1 positional argument (2 given)


3. np.random.rand: a convenience function for np.random.uniform(0, 1)

numpy.random.rand(d0, d1, ..., dn)
# 以参数列表的形式指定参数,而非元组
# 内部指定区间为[0., 1.)


>>> np.random.rand(2, 2)
array([[ 0.9978749 ,  0.43597209],
[ 0.30804578,  0.9632462 ]])

>>> np.random.rand((2, 2))
TypeError: an integer is required


4. 使用 np.random.RandomState() 获取随机数生成器

>> rng = np.random.RandomState(22)
>> rng.rand(2, 3)
array([[ 0.48168106,  0.42053804,  0.859182  ],
[ 0.17116155,  0.33886396,  0.27053283]])


references

[1] numpy.random.uniform
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: