numpy 随机数种类np.random.RandomState、np.random.rand、np.random.random、np.random_sample

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)
 
 
  • 1
  • 1

顾名思义,从一个均匀分布([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]])
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

alias: 别名;

>>> id(np.random.random) == id(np.random.random_sample)
True
 
 
  • 1
  • 2
  • 1
  • 2
numpy.random.random(size=None)
                # 已指定区间为[0., 1.),自然是float类型
 
 
  • 1
  • 2
  • 1
  • 2

必须以元组形式指定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)
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

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

numpy.random.rand(d0, d1, ..., dn)
                # 以参数列表的形式指定参数,而非元组
                # 内部指定区间为[0., 1.)
 
 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
>>> np.random.rand(2, 2)
array([[ 0.9978749 ,  0.43597209],
       [ 0.30804578,  0.9632462 ]])

>>> np.random.rand((2, 2))
TypeError: an integer is required
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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]])
  • 11
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值