numpy.random随机数使用函数¶
一般随机数生成¶
| 函数 | 说明 |
|---|---|
| rand(d0,d1,...,dn) | 根据d0-dn创建随机数组,生成[0,1)服从均匀分布的浮点数 |
| randn(d0,d1,...,dn) | 维度为(d0,d1,...,dn),服从标准正态分布 |
| randint(low[,high,shape]) | 根据shape创建随机整数或整数数组,范围是[low,high] |
| seed(s) | 随机数种子,s是给定的种子值(使相同seed生成的随机数相同) |
1、rand()函数
[[[0.56854466 0.90548802 0.97692517 0.34645166]
[0.81929329 0.91578082 0.32355212 0.21200828]
[0.42583598 0.1681713 0.26240466 0.42300891]]
[[0.15552507 0.16605262 0.02707879 0.47793804]
[0.84865168 0.90674428 0.63758455 0.39801214]
[0.3702098 0.86093161 0.14815401 0.23033124]]]
[[0.56854466 0.81929329 0.42583598]
[0.15552507 0.84865168 0.3702098 ]]
3、randint()函数
# 范围[1,5)
c = np.random.randint(1,5,size=(2,2))
print(c)
# 默认从0开始,size默认是一维
d = np.random.randint(3,size=2)
print(d)
numpy.random.randint()的详细用法¶
函数的作用是,返回一个随机整型数,范围从低(包括)到高(不包括),即[low, high)。如果没有写参数high的值,则返回[0,low)的值。
numpy.random.randint(low, high=None, size=None, dtype='l')
参数如下:
| 参数 | 描述 |
|---|---|
| low:int | 生成的数值最低要大于等于low |
| high:int(可选) | 如果使用这个值,则生成的数值在[low,high)区间 |
| size:整数或元组 | 输出随机数尺寸 |
| dtype:dtype(可选) | 想要输出的格式,如int64、int等 |
服从均匀、正态、泊松分布的随机数组¶
| 函数 | 说明 |
|---|---|
| uniform(low,high,size) | 产生具有均匀分布的数组,low起始值,high结束值,size形状 |
| normal(loc,scale,size) | 产生具有正态分布的数组,loc均值,scale标准差,size形状 |
| poisson(lam,size) | 产生具有泊松分布的数组,lam随机事件发生率,size形状 |
对生成的随机数组打乱和随机提取¶
| 函数 | 说明 |
|---|---|
| shuffle(a) | 根据数组a的第1轴(最外层的维度)进行随机排列,改变原数组a |
| permutation(a) | 根据数组a的第1轴产生一个新的乱序数组,不改变数组a |
| choice(a[,size,replace,p]) | 从一维数组a中以概率p抽取元素,形成size形状新数组replace表示是否可以重用元素,默认为False |
1、shuffle函数
[[113 191 127 161]
[165 157 118 195]
[179 111 123 163]]
[[165 157 118 195]
[179 111 123 163]
[113 191 127 161]]
2、permutation函数
b = np.random.randint(10,20,(3,4))
print(b)
c = np.random.permutation(b) #可以赋值
print(b) #不改变原数组b
print(c)
[[18 12 13 10]
[16 15 14 18]
[17 11 14 15]]
[[18 12 13 10]
[16 15 14 18]
[17 11 14 15]]
[[16 15 14 18]
[17 11 14 15]
[18 12 13 10]]
3、choice函数