numpy学习笔记之随机采样函数

mac2024-10-13  45

numpy的随机采样函数

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

功能:Generates a random sample from a given 1-D array

常见的随机采样用法如下:

import random # 从0到99的列表中随机生成10个样本 out1 = random.sample(range(100),10) # 方法1 # If a is an int, the random sample is generated as if a was np.arange(n) out2 = np.random.choice(100,10) # 方法2 # 结果可能会出现相同的数,通过set()进行去重, out = set(out2) # 从input数组或者列表中随机生成一个样本 input = [1,3,6,8] output = np.random.choice(input) # 从input数组或列表中以一定的概率生成样本 # 选择元素8的概率最大为0.4 input = [1,3,6,8] output = np.random.choice(input,p=[0.1,0.2,0.3,0.4]) aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher'] np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3]) #array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], dtype='|S11')

np.random.choice的API 如下:

choice(a, size=None, replace=True, p=None) Parameters ----------- a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) size : int or tuple of ints, optional Output shape. If the given shape is, e.g., ``(m, n, k)``, then ``m * n * k`` samples are drawn. Default is None, in which case a single value is returned. replace : boolean, optional Whether the sample is with or without replacement p : 1-D array-like, optional The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a. Returns samples : 1-D ndarray, shape (size,) The generated random samples

See Also

randint, shuffle, permutation

np.random.randint(0,10)

功能:随机从0到10之间选取一个数

randint(low, high=None, size=None, dtype='l')

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

np.random.shuffle (array)

功能:随机对给定数组或者列表乱序,默认是axis=0返回的结果就是给定数组本身,只不过顺序被打乱

np.random.permutation(array)

功能:重新对给定数组或者列表排序,如何是多维数组,则沿着first axis重新排列,返回的重新排列后的数组
最新回复(0)