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

PyTorch torch.manual_seed function

PyTorch torch.manual_seed function


PyTorch torch reference manual PyTorch torch reference manual

torch.manual_seed is a function in PyTorch used to set the random number generator seed. Setting a seed ensures the reproducibility of results.

This is important when experimental results must be reproducible, such as in debugging and paper reproduction.

Function definition

torch.manual_seed(seed)

Parameters:

Return Value:


Usage examples

Example 1: Set a seed to ensure reproducibility

Example

import

torch

Set the random seed

torch.

manual_seed

(

42

)

The random numbers generated each time are the same

x

=

torch.

randn

(

3

)

print

(

"First time:"

,

x

)

Reset the same seed

torch.

manual_seed

(

42

)

y

=

torch.

randn

(

3

)

print

(

"Second time:"

,

y

)

print

(

"Results are the same:"

,

torch.

equal

(

x

,

y

)

)

The output is:

第一次: tensor([ 0.3367,  0.1288,  0.2345])

第二次: tensor([ 0.3367,  0.1288,  0.2345])

结果相同: True

Example 2: Fully reproducible training

Example

import

torch

import

random

import

numpy

as

np

def

set_seed

(

seed

=

42

)

:

   

Set the PyTorch seed

    torch.

manual_seed

(

seed

)

   

Set the NumPy seed

    np.

random

.

seed

(

seed

)

   

Set the Python random seed

   

random

.

seed

(

seed

)

   

Ensure CUDA determinism if used

    torch.

backends

.

cudnn

.

deterministic

=

True

    torch.

backends

.

cudnn

.

benchmark

=

False

Set the seed

set_seed

(

42

)

Generate random data

x

=

torch.

randn

(

3

,

4

)

print

(

x

)

The output is:

tensor([[ 0.3367,  0.1288,  0.2345,  0.2303],

        [-1.1229, -0.1863,  0.1735, -0.5524],

        [ 0.6351, -0.2582,  0.4602, -0.5270]])

To fully ensure reproducibility, you need to set the seeds for PyTorch, NumPy, and Python random at the same time.


PyTorch torch reference manual PyTorch torch reference manual