知识点1、以循环的方式给layer初始化
知识点2、nn.Module中.children()与.modules()的区别
知识点1(重点)
以循环的方式给layer初始化,重点是一下代码,记住
for layer in net1()
if isinstance(layer, nn.Linear):
layer.weight.data = torch.from_numpy(np.random.uniform(3, 4, size=layer.weight.shape))
对于Sequential定义的网络
import torch
from torch import nn
import numpy as np
# 初始化网络
net1 = nn.Sequential(
nn.Linear(3, 4),
nn.ReLU(),
nn.Linear(4, 5),
nn.ReLU(),
nn.Linear(5, 1)
)
# 通过net1[0].weight访问第一层的w(variable)然后.data 以tensor的形式访问w
print(net1[0].weight.data)
# 给net中参数赋值
net1[0].weight.data = torch.from_numpy(np.random.uniform(3, 4, size=(3, 4)))
# 赋值模板
for layer in net1:
if isinstance(layer, nn.Linear):
layer.weight.data = torch.from_numpy(np.random.uniform(3, 4, size=layer.weight.data.shape))
print(net1[0].weight.data)
print(net1[2].weight.data)