zl程序教程

您现在的位置是:首页 >  其他

当前栏目

numpy基础--random模块:随机数生成

2023-03-15 22:51:14 时间

以下代码的前提:import numpy as np

numpy.random模块对python内置的random进行了补充,增加了一些高效生成多种概率分布的样本值的函数。例如可以用normal来得到一个正态分布的样本数组。

1 >>> samples = np.random.normal(size=(4, 4))
2 >>> samples
3 array([[-1.45057151,  0.80108401,  1.3671828 ,  0.34067137],
4        [-0.351859  ,  1.24758539, -0.26833999, -1.59481081],
5        [-0.81700215,  0.62729444, -0.34062153, -1.38731507],
6        [-0.07054579,  0.48847421,  0.66410904,  0.75402961]])
7 >>>

下表是部分numpy.random函数。

函数 说明
seed 确定随机数生成器的种子,使用MT19937算法生成随级数
permutation 返回一个序列的随机排列或返回一个随机排列的范围
shuffle 对一个序列就地随机排序
rand 产生均匀分布的样本值
randint 从给定的上下限范围内随机选取整数
randn 产生正态分布(平均值为0,标准差为1)的样本值
binomial 产生二项分布的样本值
normal 产生正态(高斯)分布的样本值
beta 产生beta分布的样本值
chisquare 产生卡方分布的样本值
gamma 产生gamma分布的样本值
uniform 产生在[0, 1)中均匀分布的样本值

numpy.random.permutation — NumPy v1.21 Manual

>>> np.random.permutation(10)
array([4, 1, 9, 5, 7, 6, 2, 3, 8, 0])
>>> np.random.permutation(10)
array([5, 8, 0, 4, 2, 9, 7, 3, 1, 6])
>>> np.random.permutation([1, 4, 9, 12, 15])
array([15, 12,  4,  9,  1])
>>> np.random.permutation([1, 4, 9, 12, 15])
array([12,  1,  4,  9, 15])

numpy.random.Generator.shuffle — NumPy v1.21 Manual

>>> arr = np.arange(10)
>>> np.random.shuffle(arr)     
>>> arr
array([3, 1, 0, 9, 4, 7, 2, 5, 6, 8])

numpy.random.rand — NumPy v1.21 Manual

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1). 创建的是[0, 1)之间均匀分布的随级数。

>>> np.random.rand(3, 2) 
array([[0.07018308, 0.90561818],
       [0.99432171, 0.26787643],
       [0.28020959, 0.56367748]])

numpy.random.randint — NumPy v1.21 Manual

>>> np.random.randint(2, size=10)
array([0, 0, 1, 1, 0, 0, 0, 0, 1, 0])
>>> np.random.randint(2, 10, size=10)
array([6, 5, 3, 3, 2, 8, 3, 6, 7, 5])

numpy.random.randn — NumPy v1.21 Manual

Return a sample (or samples) from the “standard normal” distribution. 返回的是标准正态分布的样本值。

>>> np.random.randn()
0.08980201445589159
>>> 3 + 2.5 * np.random.randn(2, 4)
array([[-0.54181508,  1.91274669, -0.03481992,  4.13696276],
       [ 2.5478997 ,  5.99354068, -2.22818567,  1.80841191]])

numpy.random.binomial — NumPy v1.21 Manual

Draw samples from a binomial distribution. 返回的是二项分布的值。

方法:random.binomial(n, p, size=None)

概率密度函数:image-20211107182059975

>>> n, p = 10, .5
>>> np.random.binomial(n, p, 12)
array([3, 2, 6, 3, 6, 7, 6, 3, 6, 3, 5, 4])

numpy.random.uniform — NumPy v1.21 Manual

产生在[0, 1)中均匀分布的样本值。

random.uniform(low=0.0, high=1.0, size=None)

>>> np.random.uniform(-1, 0, 10)
array([-0.20440931, -0.45307924, -0.3799625 , -0.24008107, -0.45289709,
       -0.2535697 , -0.21966943, -0.13334651, -0.53719732, -0.62820317])
>>> np.random.uniform(0, 1, 10)   
array([0.79207298, 0.90605515, 0.31572444, 0.25714457, 0.05195628,
       0.85805555, 0.29675482, 0.37778799, 0.20570759, 0.75019984])