[英]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.因为您已经有了
1
和0
,所以您的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.