mindspore.ops.multinomial

查看源文件
mindspore.ops.multinomial(input, num_samples, replacement=True, seed=None)[源代码]

根据输入生成一个多项式分布的Tensor。

多项式分布是一种概率分布,把二项分布公式推广至多种状态,就得到了多项式分布。在多项式分布中,每个事件都有一个固定的概率,这些概率的和为1。

mindspore.ops.multinomial 接口的作用是对输入 input 进行 num_samples 次抽样,输出的Tensor则为每一次抽样时输入Tensor的索引,其中 input 中的值为每次抽样取到对应索引的概率。

这里我们给一个相对极端的用例方便理解,我们给定一个输入概率值Tensor,值为 Tensor([90 / 100, 10 / 100, 0], mindspore.float32) ,代表我们一共可以对三个索引进行抽样,分别为索引0,索引1,索引2,它们被抽中的概率分别为90%,10%,0%,我们对其进行n次抽样,抽样的结果序列则为多项式分布的计算结果,计算结果长度与抽样次数一致。

在样例代码case 1中,我们对其进行两次不放回抽样(replacementFalse),那我们的计算结果则大概率为 [0, 1] ,小概率为 [1, 0], 由于每次抽样抽到索引0的概率为90%,因此抽到的结果序列中,第一次大概率是抽到索引0,由于抽到索引2的概率为0,因此抽样两次结果不可能出现索引2,那第二次结果一定是索引1,因此结果序列为 [0, 1]

在样例代码case 2中,我们对其进行10次放回抽样(replacementTrue),可以看到计算结果中大概有90%的抽样结果为抽到索引0,符合预期。

在样例代码case 3中,我们将输入扩展为2维,可以看到抽样结果在每一个维度中结果也符合我们抽样预期。

说明

输入的行不需要求和为1(当使用值作为权重的情况下),但必须是非负的、有限的,并且和不能为0。在使用值作为权重的情况下,可以理解为对输入沿最后一维进行了归一化操作,以此保证概率和为1。

参数:
  • input (Tensor) - 输入的概率值Tensor,必须是一维或二维,数据类型为float32。

  • num_samples (int) - 采样的次数。

  • replacement (bool, 可选) - 是否是可放回的采样,默认值: True

  • seed (int, 可选) - 随机数种子,用于生成随机数(伪随机数),必须是非负数。默认值: None

返回:

Tensor,与输入有相同的行数。每行的采样索引数为 num_samples 。数据类型为float32。

异常:
  • TypeError - 如果 input 不是数据类型不是float32的Tensor。

  • TypeError - 如果 num_samples 不是int。

  • TypeError - 如果 seed 既不是int也不是None。

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore
>>> from mindspore import Tensor, ops
>>> from mindspore import dtype as mstype
>>> # case 1: The output is random, and the length of the output is the same as num_sample.
>>> # replacement is False.
>>> input1 = Tensor([90 / 100, 10 / 100, 0], mindspore.float32)
>>> input2 = Tensor([90, 10, 0], mindspore.float32)
>>> # input1 and input2 have the same meaning.
>>> output1 = ops.multinomial(input1, 2, replacement=False)
>>> output2 = ops.multinomial(input2, 2, replacement=False)
>>> # print(output1)
>>> # [0 1]
>>> # print(output2)
>>> # [0 1]
>>> print(len(output1))
2
>>> print(len(output2))
2
>>> # case 2: The output is random, and the length of the output is the same as num_sample.
>>> # replacement is True.
>>> output3 = ops.multinomial(input1, 10)
>>> # print(output3)
>>> # [0 0 1 0 0 0 0 0 0 0]
>>> print(len(output3))
10
>>> # case 3: The output is random, and the length of the output is the same as num_sample.
>>> # replacement is True.
>>> # rank is 2
>>> input4 = Tensor([[90, 10, 0], [10, 90, 0]], mstype.float32)
>>> output4 = ops.multinomial(input4, 10)
>>> # print(output4)
>>> # [[0 0 0 0 0 0 0 0 1 0]
>>> #  [1 1 1 1 1 0 1 1 1 1]]