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.
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.
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.
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).
torch
has no equivalent implementation of np.random.choice()
, see the discussion here. The alternative is indexing with a shuffled index or random integers.
pictures[torch.randint(len(pictures), (10,))]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With