pytorch:如何从张量中采样张量中每个值的可能性不同的可能性?
给定张量 a = torch.tensor([[0.0316,0.2338,0.2338,0.2338,0.2338,0.0316,0.0316,0.0316,0.0860,0.0860,0.0316,0.0860]) 'll始终总和为1),我想从
a
中采样一个值,其中值本身是进行采样的可能性。例如,采样0.0316
来自a
是0.0316
的可能性。采样值的输出仍应是张量。
我尝试使用加权doseDrandomsAmpler
,但它不允许选择的值是张量,而是脱离了。
一个使这种棘手的警告是,我也想知道张量中出现的采样值的索引。也就是说,我示例0.2338
,我想知道它是否是索引1
,2
或3
tensor的3 a
。
Given tensorA = torch.tensor([0.0316, 0.2338, 0.2338, 0.2338, 0.0316, 0.0316, 0.0860, 0.0316, 0.0860])
containing probabilities which sum to 1 (I removed some decimals but it's safe to assume it'll always sum to 1), I want to sample a value from A
where the value itself is the likelihood of getting sampled. For instance, the likelihood of sampling 0.0316
from A
is 0.0316
. The output of the value sampled should still be a tensor.
I tried using WeightedRandomSampler
but it doesn't allow the value selected to be a tensor anymore, instead it detaches.
One caveat that makes this tricky is that I want to also know the index of the sampled value as it appears in the tensor. That is, say I sample 0.2338
, I want to know if it's index 1
, 2
or 3
of tensor A
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过累积权重并选择随机浮点的插入索引[0,1)来选择预期概率。示例数组 a 略微调整至总和1。
输出
比
a.multinomial(1)
。更常见的方法要快。
对10000次采样一个元素,以检查分布是否符合概率
输出
Selecting with the expected probabilities can be achieved by accumulating the weights and selecting the insertion index of a random float [0,1). The example array A is slightly adjusted to sum up to 1.
Output
This is faster than the more common approach with
A.multinomial(1)
.Sampling 10000 times one element to check that the distribution conforms to the probabilities
Output
怎么样?
How about this?
可以将接受的答案(由Michael Szczesny)扩展到具有概率的2D张量,例如模型输出的软键。只需相应地调整随机张量的尺寸即可。
the solution from the accepted answer (by Michael Szczesny) can be expanded to cover 2d tensors with probabilities, like softmax of model outputs. Just adjust the dimensions of the random tensor accordingly.
您可以通过这样的事情作弊:
You can cheat a little by doing something like this: