PyTorch torch.rand Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.randIt is a function in PyTorch used to create random tensors from a uniform distribution [0, 1).

This is commonly used in deep learning for scenarios such as initialization, generating random masks, and so on.

Function Definition

torch.rand(*size, dtype=None, device=None, requires_grad=False)

Parameters:

  • *size(int): Shape of the tensor.
  • dtype(torch.dtype, optional): Data type.
  • device(torch.device, optional): Device.
  • requires_grad(bool, optional): Whether gradient computation is needed.

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)

print(x)
print("Range: [{:.4f}, {:.4f})".format(x.min().item(), x.max().item()))

The output result 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

print("Mask:", mask)
print("True count:", mask.sum().item())

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions