import random
import torch
import numpy as np
import os
def seed_torch(seed=2018):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
每次构建模型或者涉及到随机数的函数调用前先执行一次该函数就可以。