固定随机数种子
只需在import 后,主代码前添加:
def setup_seed(seed=0):
os.environ[‘PYTHONHASHSEED’] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
setup_seed(0)
即可
注意
如果不固定随机数种子,要在代码添加 torch.backends.cudnn.benchmark = True,能提升运行速度。