mindspore.ops.multinomial
- mindspore.ops.multinomial(input, num_samples, replacement=True, seed=None)[源代码]
生成一个多项式分布的tensor。
多项式分布是一种概率分布,把二项分布公式推广至多种状态,就得到了多项式分布。在多项式分布中,每个事件都有一个固定的概率,这些概率的和为1。
本接口的作用是对输入 input 进行 num_samples 次抽样,输出的tensor则为每一次抽样时输入tensor的索引,其中 input 中的值为每次抽样取到对应索引的概率。
这里我们给一个相对极端的用例方便理解,我们给定一个输入概率值tensor,值为 [90 / 100, 10 / 100, 0] ,代表我们一共可以对三个索引进行抽样,分别为索引0、索引1和索引2,它们被抽中的概率分别为90%、10%和0%,我们对其进行n次抽样,抽样的结果则为多项式分布的计算结果,计算结果长度与抽样次数一致。
在样例代码case 1中,我们对其进行两次不放回抽样(replacement 为
False
),由于每次抽样抽到索引0的概率为90%,因此抽到的结果第一次大概率是抽到索引0,由于抽到索引2的概率为0,因此抽样两次结果不可能出现索引2,那第二次结果一定是索引1,因此结果序列为 [0, 1]。在样例代码case 2中,我们对其进行10次放回抽样(replacement 为
True
),可以看到计算结果中大概有90%的抽样结果为抽到索引0,符合预期。在样例代码case 3中,我们将输入扩展为二维,可以看到抽样结果在每一个维度中的结果也符合抽样预期。
说明
输入的行不需要求和为1(当使用值作为权重的情况下),但必须是非负的、有限的,并且和不能为0。在使用值作为权重的情况下,可以理解为对输入沿最后一维进行了归一化操作,以此保证概率和为1。
警告
Ascend后端不支持随机数重现功能, seed 参数不起作用。
- 参数:
input (Tensor) - 包含概率值的tensor。
num_samples (int) - 采样的次数。
replacement (bool,可选) - 是否放回,默认
True
。seed (int,可选) - 随机种子,默认
None
。
- 返回:
Tensor
- 支持平台:
Ascend
GPU
CPU
样例:
>>> import mindspore >>> # case 1: The output is random, and the length of the output is the same as num_sample. >>> # replacement is False. >>> input1 = mindspore.tensor([90 / 100, 10 / 100, 0]) >>> input2 = mindspore.tensor([90, 10, 0]) >>> # input1 and input2 have the same meaning. >>> mindspore.ops.multinomial(input1, 2, replacement=False) Tensor(shape=[2], dtype=Int32, value= [0, 1]) >>> mindspore.ops.multinomial(input2, 2, replacement=False) Tensor(shape=[2], dtype=Int32, value= [1, 0]) >>> >>> # case 2: The output is random, and the length of the output is the same as num_sample. >>> # replacement is True. >>> mindspore.ops.multinomial(input1, 10) Tensor(shape=[10], dtype=Int32, value= [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]) >>> >>> # case 3: The output is random, and the length of the output is the same as num_sample. >>> # replacement is True. >>> # rank is 2 >>> input3 = mindspore.tensor([[90, 10, 0], [10, 90, 0]], mindspore.float32) >>> output = mindspore.ops.multinomial(input3, 10) >>> print(output) [[0 0 0 0 0 0 0 0 0 0] [1 0 1 1 1 1 1 1 1 1]]