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

PyTorch torch.rand function

PyTorch torch.rand function


PyTorch torch reference manual 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:

Return Value:


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 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

(

"Number of True values:"

,

mask.

sum

(

)

.

item

(

)

)


PyTorch torch reference manual PyTorch torch reference manual