torch.manual_seed(int seed)
使用原因:
在需要生成隨機數的實驗中,確保每次運行.py文件時,生成的隨機數都是固定的,這樣每次實驗結果顯示也就一致了。
代碼演示
torch.manual_seed(1)
torch.rand(1,2)
無論執行多少次,(注意是一起執行這兩行代碼),輸出的結果都是一樣的
若去掉 torch.manual_seed(1) 直接torch.rand(1,2) 則生成的結果是不一樣的
參數 seed 的理解
可以理解為一個rand 的index,index相同,則rand的結果是相同的
torch.manual_seed(2)
print(torch.rand(2))
torch.manual_seed(1)
print(torch.rand(2))
torch.manual_seed(2)
print(torch.rand(2))
torch.manual_seed(1)
print(torch.rand(2))
輸出結果:
tensor([0.6147, 0.3810])
tensor([0.7576, 0.2793])
tensor([0.6147, 0.3810])
tensor([0.7576, 0.2793])
理解: seed=1 rand產生的是 tensor([0.7576, 0.2793]); seed=2 rand產生的是 tensor([0.6147, 0.3810]);
GPU
torch.cuda.manual_seed(int.seed):為當前GPU設置隨機種子
torch.cuda.manual_seed_all(int.seed):為所有的GPU設置種子
