torch.manual_seed() 和 torch.cuda.manual_seed() 功能及實例

功能

  • 設置固定生成隨機數的種子,使得每次運行該 .py 文件時生成的隨機數相同

設置方法

  • CPU:torch.manual_seed(整數)
    • 官方文檔:https://pytorch.org/docs/stable/torch.html?highlight=manual_seed#torch.manual_seed
  • GPU:torch.cuda.manual_seed(整數)
    • 官方文檔:https://pytorch.org/docs/stable/cuda.html?highlight=manual_seed#torch.cuda.manual_seed

實例

# 需要注意不要在終端中單行敲入運行如下代碼,要將如下代碼先拷貝到 *.py 文件中,再在終端命令中通過 python *.py 運行

import torch

if torch.cuda.is_available():
    print("gpu cuda is available!")
    torch.cuda.manual_seed(1000)
else:
    print("cuda is not available! cpu is available!")
    torch.manual_seed(1000)

print(torch.rand(1, 2))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章