PyTorch torch.bernoulli function
PyTorch torch reference manual
torch.bernoulli is a function in PyTorch used to generate random numbers from a Bernoulli distribution.
Function definition
torch.bernoulli(input, *, generator=None, out=None)
torch.bernoulli(p, size, *, generator=None, out=None)
Parameter Description
input- A probability value or a tensor of probabilities (each element represents the probability of being 1 at the corresponding position)p- A probability value (used when input is not a tensor)size- The shape of the output tensorgenerator- Random number generator (optional)out- Output tensor (optional)
Usage examples
Example
import
torch
Generate Bernoulli-distributed random numbers using a probability tensor
probs
=
torch.
tensor
(
[
0.1
,
0.5
,
0.9
]
)
result
=
torch.
bernoulli
(
probs
)
(
"Probability tensor:"
,
probs
)
(
"Bernoulli sampling result:"
,
result
)
Generate a random tensor using a fixed probability
result2
=
torch.
bernoulli
(
0.5
,
(
3
,
3
)
)
(
"3x3 random tensor generated with fixed probability 0.5:"
)
(
result2
)