numpy.random详解

numpy库中的random模块中有很多函数,下面,我做一个简要的归类、举例:

1、rand(d0,d1,d2,d3....dn)  

     创建一个数组,随机产生一个[0,-1)的值,参数:整数,可以为空。

1 In [6]: np.random.randn(4,2)
2 Out[6]:
3 array([[-0.17971383, -1.84787176],
4        [-0.1860349 ,  0.5546173 ],
5        [-1.57698523,  0.7272754 ],
6        [ 0.45259596,  0.32255619]])
View Code

2、randn(d0,d1,d2,d3....dn)

     从正态分布中返回数组。d0,d1...dn 表示维度

In [15]: np.random.randn(2,3)
Out[15]:
array([[-0.81662523,  0.01087083, -2.38323491],
       [-1.67111495, -0.08231917, -0.65780322]])

In [17]: 5*np.random.randn(2,4)+6
Out[17]:
array([[ 5.24384164,  1.86308445, -2.85359765,  1.13427893],
       [ 3.70242114,  6.28739043,  7.23047234,  0.36169486]])
View Code

3、numpy.random.randint(lowhigh=Nonesize=Nonedtype='l')

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

    low: 整数,且当high不为空时,low<high

    high:整数

    size: 可以是整数,或者元组。  默认是空值,如果为空,则仅返回一个整数。

In [39]: np.random.randint(4,size=5)
Out[39]: array([0, 2, 3, 2, 0])


In [37]: np.random.randint(4,5)
Out[37]: 4
View Code
 1 In [19]: np.random.randint(2)
 2 Out[19]: 1
 3 
 4 In [21]: np.random.randint(2,size=3)
 5 Out[21]: array([0, 0, 1])
 6 
 7 In [24]: np.random.randint(6,size=(4,2))
 8 Out[24]:
 9 array([[0, 0],
10        [5, 5],
11        [3, 5],
12        [1, 3]])
View Code

4、numpy.random.random_integers(lowhigh=Nonesize=None)

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

     low:int

In [25]: np.random.random_integers(6,size=(4,2))
Out[25]:
array([[6, 4],
       [1, 2],
       [5, 1],
       [3, 6]])
View Code

5、numpy.random.random_sample(size=None)

    返回随机的浮点数,在半开区间[0.0,1.0)

 1 In [26]: np.random.random_sample()
 2 Out[26]: 0.2688857900293471
 3 
 4 In [26]: np.random.random_sample()
 5 Out[26]: 0.2688857900293471
 6 
 7 In [29]: np.random.random_sample((2,4))
 8 Out[29]:
 9 array([[0.30813872, 0.99138326, 0.44217795, 0.06136415],
10        [0.19094554, 0.70575706, 0.3388763 , 0.55259917]])
11 
12 In [30]: np.random.random_sample((5,))
13 Out[30]: array([0.0560845 , 0.30932191, 0.78202398, 0.06572516, 0.57067096])
View Code

6、numpy.random.random(size=None)

    返回随机的浮点数,在半开区间[0.0,1.0),与random_sample一样。

7、numpy.random.ranf(size=None)

    返回随机的浮点数,在半开区间 [0.0, 1.0)。 与random_sample完全一样

8、numpy.random.choice(asize=Nonereplace=Truep=None)

     通过一个给定的一维数据,产生随机采样

     a : int ,如果只有一个参数,则返回小于参数的随机整数。

     size: 是整数 or 元组。

In [31]: np.random.choice(5)
Out[31]: 0

In [32]: np.random.choice(8)
Out[32]: 3

In [33]: np.random.choice(7,6)
Out[33]: array([2, 4, 6, 6, 6, 5])

In [34]: np.random.choice(2,size = 5)
Out[34]: array([1, 1, 0, 0, 0])

In [35]: np.random.choice(2,size=(2,4))
Out[35]:
array([[0, 0, 0, 1],
       [0, 0, 0, 1]])
View Code

9、numpy.random.bytes(length)

     随机返回字节。

     length: int

 

 

 

    

     

     

    

    

posted on 2019-01-18 13:53  天辰飘雪  阅读(2710)  评论(0编辑  收藏  举报

导航