[Random Note] np.random.choice() function

np.random.choice()is a random sampling function in NumPy that is used to randomly select a specified number or specified probability of elements from a given one-dimensional array. This function can be used in application scenarios such as building simulation experiments, generating random data sets, and data sampling.

np.random.choice(a, size=None, replace=True, p=None)The parameters are as follows:

  • a: One-dimensional array or integer, indicating the data source that needs to be extracted. When it is an integer, it is equivalent to np.arange(n).
  • size: Integer or tuple, indicating the size of the output array.
  • replace: Boolean value, indicating whether to allow repeated sampling. The default is True (repeated sampling is allowed).
  • p: One-dimensional array, indicating the probability of each element being drawn. If not specified, it defaults to uniform distribution.

For example:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(np.random.choice(a))   # 随机抽取一个元素
# 输出:1 或 2 或 3 或 4 或 5,具体结果根据随机结果而定

print(np.random.choice(a, size=3))   # 随机抽取三个元素
# 输出:[2, 5, 1] 或 [3, 4, 1] 或 ...,具体结果根据随机结果而定

print(np.random.choice(a, size=3, replace=False))   # 无放回地随机抽取三个元素
# 输出:[5, 3, 1] 或 [4, 2, 1] 或 ...,具体结果根据随机结果而定

print(np.random.choice(a, size=3, p=[0.1, 0.1, 0.2, 0.3, 0.3]))   # 按照概率分布随机抽取三个元素
# 输出:[4, 5, 4] 或 [3, 3, 5] 或 ...,具体结果根据随机结果而定

Ifa is a constant, the np.random.choice() function is equivalent to randomly sampling elements from the set of integers [0, a) . This is because in Python, both range(a) and np.arange(a) can represent the integer set of [0, a), so when is equivalent to . anp.random.choice(a)np.random.choice(np.arange(a))

For example:

import numpy as np

print(np.random.choice(5))   # 等价于 np.random.choice(np.arange(5))
# 输出:0 或 1 或 2 或 3 或 4,具体结果根据随机结果而定

It should be noted that np.random.choice() function returns a new array and does not change the original array. If you need to modify the original array, you can use the np.random.shuffle() function to disrupt the order of the elements in the original array, and then take out some elements as needed.

Guess you like

Origin blog.csdn.net/weixin_44624036/article/details/134193467