Skip to content

Instantly share code, notes, and snippets.

@binshengliu
Created June 8, 2020 05:44
Show Gist options
  • Select an option

  • Save binshengliu/be4ddca30101ff3879cb2dbfe9ff937a to your computer and use it in GitHub Desktop.

Select an option

Save binshengliu/be4ddca30101ff3879cb2dbfe9ff937a to your computer and use it in GitHub Desktop.
Random choice unique along axis
# https://stackoverflow.com/a/45438143/955952
def random_choice_noreplace(m, n, axis=-1):
# m, n are the number of rows, cols of output
return np.random.rand(m, n).argsort(axis=axis)
@binshengliu

Copy link
Copy Markdown
Author

Use torch.multinomial for multiple independent sampling with probabilities.

num_trials = 5
num_samples = 2
probs = torch.tensor([0.5, 0.3, 0.2]).expand(num_trials, -1)
torch.multinomial(probs, num_samples, replacement=probs.size(1)<num_samples)

Output:

tensor([[1, 0],
        [0, 1],
        [1, 2],
        [0, 1],
        [0, 1]])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment