np.random的用法

1
import numpy as np

np.random.rand() 均匀分布

返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1

语法:numpy.random.rand(d0,d1,…,dn)

  • rand函数根据给定维度生成[0,1)之间的数据,包含0,不包含1,
  • dn表格每个维度
  • 返回值为指定维度的array
1
np.random.rand()
0.590981296371817
1
np.random.rand(2,3)
array([[0.56714467, 0.63703995, 0.49941825],
       [0.38784079, 0.99935756, 0.66107952]])
1
np.random.rand(2,3,2)
array([[[0.70563167, 0.15160447],
        [0.89421227, 0.15558841],
        [0.54421821, 0.74809854]],

       [[0.6801572 , 0.73294346],
        [0.5165121 , 0.41113331],
        [0.35180961, 0.89124573]]])

np.random.randn() 正态分布

返回一个或一组服从标准正态分布的随机样本值。
标准正态分布是以0为均数、以1为标准差的正态分布,记为N(0,1)

语法: numpy.random.randn(d0,d1,…,dn)

  • randn函数返回一个或一组样本,具有标准正态分布。
  • dn表格每个维度
  • 返回值为指定维度的array
1
np.random.randn()
-1.2663606042268423
1
np.random.randn(3,2)
array([[-0.62827097,  0.29785748],
       [-0.37728649, -0.32416302],
       [ 0.84430754,  0.90935055]])

np.random.randint()

语法:np.random.randint(low[,high,size,dtype])
参数:

  • low:最小值
  • hith:最大值,不包含最大值.high没有填写时,默认生成随机数的范围是[0,low)
  • size:数据个数
  • dtype:数据类型 默认np.int
1
np.random.randint(2)
0
1
np.random.randint(1,3)
2
1
np.random.randint(1,5,2)
array([4, 4])
1
np.random.randint(1,9,5)
array([8, 8, 5, 4, 5])

np.random.sample()

语法:np.random.sample(size) 在[0-1]之间产生随机数

参数:

  • size: 随机数的维度 list形式
1
np.random.sample([3,])
array([0.53148489, 0.68699926, 0.10226921])
1
np.random.sample([3,2])
array([[0.13305405, 0.14498214],
       [0.51758694, 0.93313971],
       [0.20195698, 0.83993463]])
1
2
3
4
a = [i for i in range(100,150,10)]
a

np.random.choice(a,2)
[100, 110, 120, 130, 140]

array([140, 140])
1
2
3
4
a = [i for i in range(100,150,10)]
a

np.random.choice(a,[2,3])
[100, 110, 120, 130, 140]

array([[140, 130, 120],
       [120, 120, 120]])

np.random.choice()

语法:numpy.random.choice(a, size=None, replace=True, p=None)
参数:

  • 从给定的一维数组中生成随机数
  • a为一维数组类似数据或整数;
  • size为数组维度;
  • p为数组中的数据出现的概率;长度与参数a的长度需要一致;p里的数据之和应为1
  • a为整数时,对应的一维数组为np.arange(a)
1
2
3
a = [i for i in range(100,150,10)]

np.random.choice(a,3)
1
2
3
a = [i for i in range(100,150,10)]

np.random.choice(a,[2,3])
array([[140, 130, 120],
       [120, 100, 100],
       [100, 120, 140]])
1
2
3
a = [i for i in range(100,150,10)]

np.random.choice(a,[2,3],[0.2,0.1,0.3,0.1,0.3])
array([[140, 130, 140],
       [130, 120, 140]])

numpy.random.seed()

语法:np.random.seed(a=None,version=2)
作用:使得随机数据可预测。没有返回值。称为随机数种子。不设置随机数种子,你每次随机抽样得到的数据都是不一样的。设置了随机数种子,能够确保每次抽样的结果一样。而random.seed()括号里的数字,相当于一把钥匙,对应一扇门,同样的数值能够使得抽样的结果一致。
参数:

  • a :生成随机数的种子,可以设置为一个整数(int)
1
2
np.random.seed(0)
np.random.rand(5)
array([0.5488135 , 0.71518937, 0.60276338, 0.54488318, 0.4236548 ])
1
2
np.random.seed(12345)
np.random.rand(5)
array([0.92961609, 0.31637555, 0.18391881, 0.20456028, 0.56772503])
1
2
np.random.seed(12345)
np.random.rand(5)
array([0.92961609, 0.31637555, 0.18391881, 0.20456028, 0.56772503])