Python: Numpy 随机数生成及Numpy 1.1.7版本后 随机数生成新方法
目录
Random sampling
从Numpy 1.17开始,Generator代替RandomState,官方文档: https://numpy.org/doc/stable/reference/random/index.html
Random Generator
https://numpy.org/doc/stable/reference/random/generator.html#random-generator
创建
随机数的产生需要先创建一个随机数生成器(Random Number Generator)
然后可以使用生成器(Generator)的函数方法创建。
使用random()函数返回一个在0~1的随机浮点值:
import numpy as np rng = np.random.default_rng(123)# 创建一个种子为123的生成器,可以为空,空时会随机分配一个种子。 print(rng) Out: Generator(PCG64) rfloat = rng.random() print(rfloat) Out: 0.6823518632481435
使用
在使用时创建好上述的rng
1、创建指定维度数组
想创建指定维度的数组,可以向random()函数传入元组,其值等于你想要的shape。返回的值依旧是0~1的浮点值,
ndarr=rng.random((3,2)) ndarr Out: array([[0.68235186, 0.05382102], [0.22035987, 0.18437181], [0.1759059 , 0.81209451]]) ndarr.shape Out: (3, 2)
2、创建随机一维整数
rints = rng.integers(low=0, high=10, size=3) print(rints) Out: array([6, 2, 7])
integers(low[, high, size, dtype, endpoint])
返回从low(包括)到high(不包括)的随机整数,或者如果endpoint=True,则返回low(包括)到high(包括)的随机整数。
3、随机选择
rng.choice([[0, 1, 2], [3, 4, 5], [6, 7, 8]], 2) Out: array([[3, 4, 5], [0, 1, 2]])
choice(a[, size, replace, p, axis, shuffle])
从给定数组生成随机样本
注意a可以为整型,也可以是ndarray,list,tuple
4、随机排列
想打乱数组,numpy有两个函数可以做到,一个是shuffle(),另一个是permutation()
shuffle()和permutation()的区别:
shuffle()会改变输入的数组;输入的参数可以是array,list等序列,但是不能是int。
permutation()不会改变输入的数组,会返回一个数组的copy;输入的参数可以是int,numpy会自动将int用arange()转换。
arr = np.arange(10) rng.shuffle(arr) arr Out: [5, 3, 4, 1, 9, 8, 2, 7, 0, 6] # random rng.permutation(10) Out: array([5, 3, 4, 1, 9, 8, 2, 7, 0, 6])
shuffle(x[, axis])
通过变换数组或序列的内容修改原有数组或序列。
permutation(x[, axis])
随机置换一个序列,或者返回一个置换后的范围。
分布
函数 | 解释 |
---|---|
beta(a, b[, size]) | 从 Beta 分布中抽取样本。 |
binomial(n, p[, size]) | 从二项分布中抽取样本。 |
exponential([scale, size]) | 从指数分布中抽取样本。 |
geometric(p[, size]) | 从几何分布中抽取样本 |
logistic([loc, scale, size]) | 从逻辑分布中抽取样本。 |
normal([loc, scale, size]) | 从正态(高斯)分布中抽取随机样本。 |
standard_normal([size, dtype, out]) | 从标准正态分布(平均值=0,标准差=1)中抽取样本。 |
Legacy Random Generation
https://numpy.org/doc/stable/reference/random/legacy.html#legacy-random-generation
random.RandomState
Simple random data
rand (d0, d1, ..., dn) |
以给定的形状创建一个数组,并在数组中加入在[0,1]之间均匀分布的随机样本。 |
randn (d0, d1, ..., dn) |
以给定的形状创建一个数组,数组元素来符合标准正态分布N(0,1) |
randint (low[, high, size, dtype]) |
生成在半开半闭区间[low,high)上离散均匀分布的整数值;若high=None,则取值区间变为[0,low) |
random_integers (low[, high, size]) |
生成闭区间[low,high]上离散均匀分布的整数值;若high=None,则取值区间变为[1,low] |
random_sample ([size]) |
以给定形状返回[0,1)之间的随机浮点数 |
choice (a[, size, replace, p]) |
若a为数组,则从a中选取元素;若a为单个int类型数,则选取range(a)中的数 replace是bool类型,为True,则选取的元素会出现重复;反之不会出现重复 p为数组,里面存放选到每个数的可能性,即概率 |
bytes (length) |
Return random bytes. |