Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

can somebody help me with this? Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Torch makes this easy. 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.

Because you have 1s and 0s already, your available tensor naturally gives the correct weights for the multinomial function.

If you are going to draw more than 3 samples, this will error unless you change replacement to True.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading