Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.multinomial function

PyTorch torch.multinomial function


PyTorch torch reference manual PyTorch torch reference manual

torch.multinomial is a function in PyTorch used for multinomial sampling, drawing samples from each row of the input tensor according to a probability distribution.

Function definition

torch.multinomial(input, num_samples, replacement=False, generator=None)

Parameter Description


Usage examples

Example

import

torch

Define the probability distribution

weights

=

torch.

tensor

(

[

[

0.0

,

1.0

]

,

 

The second category has probability 1

                       

[

0.5

,

0.5

]

,

 

Two categories with equal probabilities

                       

[

0.2

,

0.3

,

0.5

]

]

)

 

Three categories

Sampling without replacement

result

=

torch.

multinomial

(

weights

,

num_samples

=

2

,

replacement

=

False

)

print

(

"Probability distribution:"

)

print

(

weights

)

print

(

"Samples without replacement (2 per row):"

)

print

(

result

)

Sampling with replacement

result_with_replacement

=

torch.

multinomial

(

weights

,

num_samples

=

5

,

replacement

=

True

)

print

(

"Samples with replacement (5 per row):"

)

print

(

result_with_replacement

)


PyTorch torch reference manual PyTorch torch reference manual