np.random
numpy
本文字数:868 字 | 阅读时长 ≈ 4 min

np.random

numpy
本文字数:868 字 | 阅读时长 ≈ 4 min

1. np.random.rand

np.random.rand(d0, d1, ... , dn)

返回一个随机 array,形状为给定参数的形状

array 中的元素从均匀的 [0, 1) 分布中采样得到

Random values in a given shape.

Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).

x = np.random.rand(3,2)
print(x)
'''
输出:三行两列的array
[[4.17022005e-01 7.20324493e-01]
 [1.14374817e-04 3.02332573e-01]
 [1.46755891e-01 9.23385948e-02]]
'''

注意:np.random.random 与 np.random.rand 作用完全一致,只有输入的参数不同,如果要生成一个(3, 2)的 array

2. np.random.randn

np.random.randn(d0, d1, ... , dn)

返回一个随机 array,形状为给定参数的形状

array 中的元素从标准正态分布 N~(0, 1) 中采样

Return a sample (or samples) from the “standard normal” distribution.

注意:如果要从$N(\mu, \sigma^2)$中采样,使用sigma * np.random.randn(...) + mu

np.random.randn()
'''
1.6243453636632417
'''


np.random.randn(2, 2)
'''
array([[ 1.62434536, -0.61175641],
       [-0.52817175, -1.07296862]])
'''


3 + 2.5 * np.random.randn(2, 4)
'''
从高斯分布N~(3, 6.25)中采样
Two-by-four array of samples from N(3, 6.25)
array([[ 7.06086341,  1.47060897,  1.67957062,  0.31757844],
       [ 5.16351907, -2.75384674,  7.36202941,  1.09698275]])
'''

3. np.random.randint

np.random.randint(low, high=None, size=None, dtype=int)

返回一个随机整型 array,形状为给定参数的形状

array 中的元素从 [low, high) 中采样整数

Return random integers from low (inclusive) to high (exclusive).

Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

np.random.seed(1)
x = np.random.randint(2, size=10)
x = np.random.randint(1, size=10)
x = np.random.randint(6, size=10)
'''
[1 1 0 0 1 1 1 1 1 0]
[0 0 0 0 0 0 0 0 0 0]
[0 1 4 5 4 1 2 4 5 2]
'''


np.random.randint(5, size=(2, 4))
'''
array([[3, 4, 0, 1],
       [3, 0, 0, 1]])
'''


np.random.randint(1, [3, 5, 10])
np.random.randint([1, 5, 7], 10)
'''
产生一个三个数字,上限分别为3,5,10
array([2, 4, 9])
产生一个三个数字,下限分别为1,5,7
array([6, 8, 7])
'''


np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
'''
使用broadcast机制产生(2, 4)的array
上下限分别为
([1, 10), [3, 10), [5, 10), [7, 10)
 [1, 20), [3, 20), [5, 20), [7, 20))
array([[ 6,  6,  9,  7],
       [10, 14, 10,  7]])
'''

4. np.random.choice

np.random.choice(a, size=None, replace=True, p=None)

从给定的一维数组中采样一个随机样本

Generates a random sample from a given 1-D array

x = np.random.choice(5, 3)
print(x)
'''size=3
[1 0 4]
'''


x = np.random.choice(5, 10, p=[0.1, 0, 0.3, 0.6, 0])
print(x)
'''size=10
[3 3 3 2 3 0 2 3 3 3]
'''


x = np.random.choice(5, 5, replace=False)
print(x)
'''replace=False不重复采样
[1 0 3 4 2]
'''


x = np.random.choice(6, size=(3, 2), replace=False)
print(x)
'''size(3, 2)
[[3 5]
 [1 0]
 [4 2]]
'''


aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
x = np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
print(x)
'''list
['pooh' 'pooh' 'Christopher' 'piglet' 'pooh']
'''

9月 09, 2024