在手动创建模型类之后,每次实例化都会随机生成一组参数值
class logisticR(nn.Module):
def __init__(self, in_features=2, out_features=1): # 定义模型的点线结构
super(logisticR, self).__init__()
self.linear = nn.Linear(in_features, out_features)
def forward(self, x): # 定义模型的正向传播规则
out = self.linear(x)
return out
list(logisticR().parameters())
list(logisticR().parameters())
输出结果
[Parameter containing:
tensor([[ 0.4318, -0.4256]], requires_grad=True),
Parameter containing:
tensor([0.6730], requires_grad=True)]
[Parameter containing:
tensor([[-0.5617, -0.2157]], requires_grad=True),
Parameter containing:
tensor([-0.4873], requires_grad=True)]
若需要完全复现模型训练过程,则需要在实例化之前设置随机数种子,或者在上一个随机数种子之前规定有限次的随机次数。
- 随机数种子可以在全域发挥作用
torch.manual_seed(420)
list(logisticR().parameters())
list(logisticR().parameters())
torch.manual_seed(420)
list(logisticR().parameters())
list(logisticR().parameters())
输出结果:
<torch._C.Generator at 0x257c273ef90>
[Parameter containing:
tensor([[ 0.4318, -0.4256]], requires_grad=True),
Parameter containing:
tensor([0.6730], requires_grad=True)]
[Parameter containing:
tensor([[-0.5617, -0.2157]], requires_grad=True),
Parameter containing:
tensor([-0.4873], requires_grad=True)]
<torch._C.Generator at 0x257c273ef90>
[Parameter containing:
tensor([[ 0.4318, -0.4256]], requires_grad=True),
Parameter containing:
tensor([0.6730], requires_grad=True)]
[Parameter containing:
tensor([[-0.5617, -0.2157]], requires_grad=True),
Parameter containing:
tensor([-0.4873], requires_grad=True)]
torch.manual_seed
不会对random中的随机过程造成影响
# - torch.manual_seed不会对random中的随机过程造成影响
l = list(range(5))
l
random.shuffle(l)
l
torch.manual_seed(420)
l = list(range(5))
l
random.shuffle(l)
l
torch.manual_seed(420)
l = list(range(5))
l
random.shuffle(l)
l
输出结果:
[0, 1, 2, 3, 4]
[2, 1, 3, 4, 0]
<torch._C.Generator at 0x257c273ef90>
[0, 1, 2, 3, 4]
[1, 4, 2, 0, 3]
<torch._C.Generator at 0x257c273ef90>
[0, 1, 2, 3, 4]
[0, 3, 1, 2, 4]
- random中可以通过设置
random.seed
来控制随机过程
# - random中可以通过设置`random.seed`来控制随机过程
random.seed(420)
l = list(range(5))
l
random.shuffle(l)
l
random.seed(420)
l = list(range(5))
l
random.shuffle(l)
l
输出结果:
[0, 1, 2, 3, 4]
[4, 3, 1, 2, 0]
[0, 1, 2, 3, 4]
[4, 3, 1, 2, 0]