使用原因 :
在需要生成随机数据的实验中,每次实验都需要生成数据。设置随机种子是为了确保每次生成固定的随机数,这就使得每次实验结果显示一致了,有利于实验的比较和改进。使得每次运行该 .py 文件时生成的随机数相同。
使用 :
#为CPU中设置种子,生成随机数:
torch.manual_seed(number)
#为特定GPU设置种子,生成随机数:
torch.cuda.manual_seed(number)
#为所有GPU设置种子,生成随机数:
torch.cuda.manual_seed_all(number)
# 需要注意不要在终端中单行敲入运行如下代码,要将如下代码先拷贝到 *.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))
def set_random_seed(seed, deterministic=False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
# manual_seed_all 是为所有 GPU 都设置随机数种子。
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False