简体   繁体   English

Pytorch 随机选择有条件的索引

[英]Pytorch random choose an index with condition

I have a tensor that stores whether or not an index in available我有一个张量存储索引是否可用

available = torch.Tensor([1,1,0,0,1,0])

and I want to return an index of either 0, 1, or 4 given that available[0] , available[1] , available[4] all equal to 1 with the same possibility.并且我想返回一个 0、1 或 4 的索引,因为available[0]available[1]available[4]都等于 1 且具有相同的可能性。

can somebody help me with this?有人可以帮我吗? Thanks谢谢

Torch makes this easy. Torch 让这一切变得简单。 You can use multinomial as per this answer :您可以根据此答案使用多项式

num_samples = 1
available.multinomial(num_samples, replacement=False)

Here, num_samples indicates how many samples you'd like to draw.在这里, num_samples表示您要抽取多少个样本。

Because you have 1 s and 0 s already, your available tensor naturally gives the correct weights for the multinomial function.因为您已经有了10 ,所以您的available张量自然会为多项式 function 提供正确的权重。

If you are going to draw more than 3 samples, this will error unless you change replacement to True .如果您要绘制 3 个以上的样本,除非您将replacement更改为True ,否则这将出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM