Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Choice with Pytorch?

I have a tensor of pictures, and would like to randomly select from it. I'm looking for the equivalent of np.random.choice().

import torch

pictures = torch.randint(0, 256, (1000, 28, 28, 3))

Let's say I want 10 of these pictures.

like image 505
Nicolas Gervais Avatar asked Dec 23 '19 22:12

Nicolas Gervais


People also ask

How does PyTorch generate random numbers?

For initializing random number in PyTorch we have to use torch. rand() function in which the output will be a tensor with random numbers in it from a uniform distribution on the interval and the tensor shape is defined by the variable argument.

How do you make a random tensor in PyTorch?

To create a random tensor with specific shape, use torch. rand() function with shape passed as argument to the function. torch. rand() function returns tensor with random values generated in the specified shape.

How do you make a torch tensor?

To create a tensor with pre-existing data, use torch.tensor() . To create a tensor with specific size, use torch.* tensor creation ops (see Creation Ops). To create a tensor with the same size (and similar types) as another tensor, use torch.*_like tensor creation ops (see Creation Ops).


1 Answers

torch has no equivalent implementation of np.random.choice(), see the discussion here. The alternative is indexing with a shuffled index or random integers.

To do it with replacement:

  1. Generate n random indices
  2. Index your original tensor with these indices
pictures[torch.randint(len(pictures), (10,))]  

To do it without replacement:

  1. Shuffle the index
  2. Take the n first elements
indices = torch.randperm(len(pictures))[:10]

pictures[indices]

Read more about torch.randint and torch.randperm. Second code snippet is inspired by this post in PyTorch Forums.

like image 163
Nicolas Gervais Avatar answered Sep 20 '22 10:09

Nicolas Gervais