PyTorch torch.rand function
PyTorch torch reference manual
torch.rand is a function in PyTorch used to create a random tensor from a uniform distribution [0, 1).
This is commonly used in deep learning for initialization, generating random masks, and similar scenarios.
Function definition
torch.rand(*size, dtype=None, device=None, requires_grad=False)
Parameters:
*size(int): The shape of the tensor.dtype(torch.dtype, optional): Data type.device(torch.device, optional): Device.requires_grad(bool, optional): Whether gradients need to be computed.
Return Value:
torch.Tensor: Returns a tensor containing random numbers in the range [0, 1).
Usage examples
Example 1: Create a random tensor
Example
import
torch
Create a 3x4 random tensor
x
=
torch.
rand
(
3
,
4
)
(
x
)
(
"Range: [{:.4f}, {:.4f})"
.
format
(
x.
min
(
)
.
item
(
)
,
x.
max
(
)
.
item
(
)
)
)
The output is:
tensor([[0.6272, 0.1802, 0.8336, 0.3900],
[0.2188, 0.6593, 0.3598, 0.4021],
[0.9247, 0.0144, 0.2587, 0.6634]])
范围: [0.0144, 0.9247)
Example 2: Create a random mask
Example
import
torch
Create a random mask with 50% probability
mask
=
torch.
rand
(
10
)
>
;
0.5
(
"Mask:"
,
mask
)
(
"Number of True values:"
,
mask.
sum
(
)
.
item
(
)
)