Skip to content

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()函数

import numpy as np

a = np.random.rand(2,3,4)
print(a)
print(a[:,:,0])
[[[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 ]]

2、randn()函数

b = np.random.randn(2,3)
print(b)
[[-1.32833451 -1.95133563 -0.02131307]
 [ 0.56779016 -0.65943071 -0.36162762]]

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)
[[1 3]
 [3 4]]

[0 2]

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形状
#均匀分布
u = np.random.uniform(0,10,(2,3))
print(u)
[[7.87524818 3.80536084 3.37206453]
 [1.03031085 5.08247466 4.88571465]]
#正态分布
n = np.random.normal(0,1,(2,3))
print(n)
[[-0.60138073  0.33080562 -0.33807055]
 [ 0.31031215 -0.28861869 -1.39513247]]
#泊松分布
p = np.random.poisson(2.0,(3,4))
print(p)
[[4 1 3 4]
 [3 3 0 1]
 [2 4 2 1]]

对生成的随机数组打乱和随机提取

函数 说明
shuffle(a) 根据数组a的第1轴(最外层的维度)进行随机排列,改变原数组a
permutation(a) 根据数组a的第1轴产生一个新的乱序数组,不改变数组a
choice(a[,size,replace,p]) 从一维数组a中以概率p抽取元素,形成size形状新数组replace表示是否可以重用元素,默认为False

1、shuffle函数

a = np.random.randint(100,200,(3,4))
print(a)
np.random.shuffle(a)  #不能赋值,不然返回None
print(a)
[[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函数

c = np.random.randint(100,200,(8,))
print(c)
c1 = np.random.choice(c,(3,2))
print(c1)   #默认可以出现重复值
c2 = np.random.choice(c,(3,2),replace=False)
print(c2)   #不可以出现重复值
c3 = np.random.choice(c,(3,2),p=c/sum(c))
print(c3)   #指定每个值出现的概率
[161 196 183 119 180 151 175 186]

[[196 196]
 [151 180]
 [119 183]]

[[196 183]
 [175 151]
 [186 180]]

[[196 183]
 [151 196]
 [161 196]]