maxframe.tensor.random.choice#

maxframe.tensor.random.choice(a, size=None, replace=True, p=None, chunk_size=None, gpu=None)[源代码]#

从给定的 1 维数组中生成随机样本

参数:
  • a (1-D array-like or int) -- 如果是一个张量,则从其元素中生成随机样本。如果是一个整数,则生成的随机样本如同 a 是 mt.arange(a) 一样

  • size (int or tuple of ints, optional) -- 输出形状。如果给定的形状例如为 (m, n, k),则抽取 m * n * k 个样本。默认为 None,此时返回单个值。

  • replace (boolean, optional) -- 样本是否有放回

  • p (1-D array-like, optional) -- 与 a 中每个条目关联的概率。如果未提供,则样本在 a 的所有条目上服从均匀分布。

  • chunk_size (int or tuple of int or tuple of ints, optional) -- 每个维度上期望的块大小

  • gpu (bool, optional) -- 如果为 True,则在 GPU 上分配张量,默认为 False

返回:

samples -- 生成的随机样本

返回类型:

single item or tensor

抛出:

ValueError -- 如果 a 是一个负整数,或者 a 或 p 不是一维的,或者 a 是长度为 0 的类数组对象,或者 p 不是概率向量,或者 a 和 p 长度不同,或者 replace=False 但样本数量大于总体数量

参见

randint, shuffle, permutation

示例

从 mt.arange(5) 中生成大小为 3 的均匀随机样本:

>>> import maxframe.tensor as mt
>>> mt.random.choice(5, 3).execute()
array([0, 3, 4])
>>> #This is equivalent to mt.random.randint(0,5,3)

从 np.arange(5) 中生成大小为 3 的非均匀随机样本:

>>> mt.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]).execute()
array([3, 3, 0])

从 mt.arange(5) 中生成大小为 3 的无放回均匀随机样本:

>>> mt.random.choice(5, 3, replace=False).execute()
array([3,1,0])
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]

从 mt.arange(5) 中生成大小为 3 的无放回非均匀随机样本:

>>> mt.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]).execute()
array([2, 3, 0])

上面的任何操作都可以使用任意类数组对象代替整数进行重复。例如:

>>> 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')