描述
設置CPU生成隨機數的種子,方便下次復現實驗結果。
語法
torch.manual_seed(seed) → torch._C.Generator
參數
seed (int) – CPU生成隨機數的種子。取值范圍為[-0x8000000000000000, 0xffffffffffffffff]
,十進制是[-9223372036854775808, 18446744073709551615]
,超出該范圍將觸發RuntimeError
報錯。
返回
返回一個torch.Generator
對象。
示例
設置隨機種子
# test.py
import torch
torch.manual_seed(0)
print(torch.rand(1)) # 返回一個張量,包含了從區間[0, 1)的均勻分布中抽取的一組隨機數
每次運行test.py
的輸出結果都是一樣:
tensor([0.4963])
沒有隨機種子
# test.py
import torch
print(torch.rand(1)) # 返回一個張量,包含了從區間[0, 1)的均勻分布中抽取的一組隨機數
每次運行test.py
的輸出結果都不相同:
tensor([0.2079])
----------------------------------
tensor([0.6536])
----------------------------------
tensor([0.2735])
注意
設置隨機種子后,是每次運行test.py
文件的輸出結果都一樣,而不是每次隨機函數生成的結果一樣:
# test.py
import torch
torch.manual_seed(0)
print(torch.rand(1))
print(torch.rand(1))
輸出:
tensor([0.4963])
tensor([0.7682])
可以看到兩次打印torch.rand(1)
函數生成的結果是不一樣的,但如果你再運行test.py
,還是會打印:
tensor([0.4963])
tensor([0.7682])
但是,如果你就是想要每次運行隨機函數生成的結果都一樣,那你可以在每個隨機函數前都設置一模一樣的隨機種子:
# test.py
import torch
torch.manual_seed(0)
print(torch.rand(1))
torch.manual_seed(0)
print(torch.rand(1))
輸出:
tensor([0.4963])
tensor([0.4963])
引用
https://pytorch.org/docs/stable/generated/torch.manual_seed.html