在神經網絡中,參數默認是進行隨機初始化的。如果不設置的話每次訓練時的初始化都是隨機的,導致結果不確定。如果設置初始化,則每次初始化都是固定的。
def same_seeds(seed):
torch.manual_seed(seed)
if torch.cuda.is_available():
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.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True