参考链接: Reproducibility
随机数种子用于复现随机的情形,相同的随机数种子可以产生相同的随机情形,直接贴出代码:
# 设置随机数种子
import numpy as np
import random
import torch
import os
seed = 20200910
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
np.random.seed(seed) # Numpy module.
random.seed(seed) # Python random module.
torch.manual_seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
# You need to set the init function of the worker(s) to be fed to the DataLoader:
def _init_fn(worker_id):
np.random.seed(seed)
r"""
trainloader = DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=num_workers,
pin_memory=True, worker_init_fn=_init_fn)
"""