1. 核心代码
def setup_seed(seed):
th.manual_seed(seed)
th.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
th.backends.cudnn.deterministic = True
setup_seed(20)
2.测试代码
import torch as th
from torch import nn
import numpy as np
import random
th.set_printoptions(precision=5) // 设置精度
def setup_seed(seed):
th.manual_seed(seed)
th.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
th.backends.cudnn.deterministic = True
setup_seed(20)
net = th.nn.Sequential(
nn.Linear(5,3)
)
data = th.randn([2,3,5])
print(data)
print(net(data))
多次运行 结果一致
本文介绍如何在PyTorch中通过设置随机种子确保实验结果的可复现性,并提供了一个示例代码来演示这一过程。代码展示了如何定义一个函数来设置随机种子,并在神经网络训练中使用这个函数。
3222

被折叠的 条评论
为什么被折叠?



