【python】numpy.random用法

numpy中的random主要是用来产生随机数的一个模块。

模块使用中的常见问题:

1、randn()和rand()的区别: 

  • numpy.random.randn(d0, d1, …, dn)是从标准正态分布(0均值1方差)中返回一个或多个样本值。 
  • numpy.random.rand(d0, d1, …, dn)是从[0, 1)随机采样。(或者叫均匀分布采样)
import numpy as np 
 
arr1 = np.random.randn(2,4)
print(arr1)
print('******************************************************************')
arr2 = np.random.rand(2,4)
print(arr2)

结果:

[[-1.03021018 0.5197033 0.52117459 -0.70102661]
[ 0.98268569 1.21940697 -1.095241 -0.38161758]]
******************************************************************
[[ 0.19947349 0.05282713 0.56704222 0.45479972]
[ 0.28827103 0.1643551 0.30486786 0.56386943]]

2、permutation(x)和shuffle(x)的区别:

  • 功能相同:对原来的数组进行重新洗牌(即随机打乱原来的元素顺序)
  • 两者区别:peumutation(x)不会修改X的顺序。

       shuffle直接在原来的数组上进行操作,改变原来数组的顺序,无返回值;而permutation不直接在原来的数组上进行操作,而是返回一个新的打乱顺序的数组,并不改变原来的数组。

 

random模块详解: 

详情可见:https://docs.scipy.org/doc/numpy/reference/routines.random.html

1、简单的随机数据

rand(d0, d1, ..., dn)

随机值

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random

randn(d0, d1, ..., dn)

返回一个样本,具有标准正态分布。

Notes

For random samples from 技术分享, use:

sigma * np.random.randn(...) + mu

Examples

>>> np.random.randn()
2.1923875335537315 #random

Two-by-four array of samples from N(3, 6.25):

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501,  4.00950034, -1.81814867,  7.29718677],  #random
       [ 0.39924804,  4.68456316,  4.99394529,  4.84057254]]) #random

randint(low[, high, size])

返回随机的整数,位于半开区间 [low, high)。

>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

Generate a 2 x 4 array of ints between 0 and 4, inclusive:

>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
       [3, 2, 2, 0]])

random_integers(low[, high, size])

返回随机的整数,位于闭区间 [low, high]。

Notes

To sample from N evenly spaced floating-point numbers between a and b, use:

a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)

Examples

>>> np.random.random_integers(5)
4
>>> type(np.random.random_integers(5))
<type ‘int‘>
>>> np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
       [3, 3],
       [4, 5]])

Choose five random numbers from the set of five evenly-spaced numbers betwee

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值