Sampling from a tensor in Torch - PyTorch Forums
discuss.pytorch.org › t › sampling-from-a-tensor-inSep 22, 2020 · I wanted to know whether we could sample elements of a tensor given a probability distribution of the tensor. In numpy we would do something like this: a = np.array([1,2,3,4]) b = np.random.choice(a, p=np.array([0.1, 0.1, 0.1, 0.7])) In torch I would like to have the array a and p to be of torch.tensor. The numpy function works well with CPU torch tensors translated to numpy arrays, but ...
Sample a tensor of probability distributions in pytorch ...
stackoverflow.com › questions › 67592748May 18, 2021 · There was no single function to sample that I saw, but I was able to sample the tensor in several steps by computing the cumulative probabilities, sampling each point independently, and then picking the first point that sampled a 1 in the distribution dimension: reverse_cumulative = torch.flip(torch.cumsum(torch.flip(probabilities, [1]), dim=1), [1])cumulative = probabilities / reverse_cumulativesampled = (torch.rand(cumulative.shape, device=device()) <= cumulative)idxs = sampled * ...