顺序
传递一个实例集合.OrderedDict https://docs.python.org/3/library/collections.html#collections.OrderedDict。下面的代码给出conv1.weights
, conv1.bias
, conv2.weight
, conv2.bias
(注意缺少torch.nn.ReLU()
,请参阅此答案的末尾)。
import collections
import torch
model = torch.nn.Sequential(
collections.OrderedDict(
[
("conv1", torch.nn.Conv2d(1, 20, 5)),
("relu1", torch.nn.ReLU()),
("conv2", torch.nn.Conv2d(20, 64, 5)),
("relu2", torch.nn.ReLU()),
]
)
)
for name, param in model.named_parameters():
print(name)
Dynamic
Use ModuleDict https://pytorch.org/docs/stable/generated/torch.nn.ModuleDict.html代替ModuleList
:
class MyModule(torch.nn.Module):
def __init__(self):
super().__init__()
self.whatever = torch.nn.ModuleDict(
{f"my_name{i}": torch.nn.Conv2d(10, 10, 3) for i in range(5)}
)
会给我们whatever.my_name{i}.weight
(or bias
)对于每个动态创建的模块。
Direct
只要你想怎么命名就可以了,这就是它的命名方式
self.my_name_or_whatever = nn.Linear(7, 8)
你没有想过
- 如果你想绘制权重、偏差及其梯度,你可以沿着这条路线走
-
您无法绘制激活图这样(或激活的输出)。使用PyTorch 挂钩 https://pytorch.org/tutorials/beginner/former_torchies/nnft_tutorial.html#forward-and-backward-function-hooks相反(如果你想要每层梯度通过网络时也使用这个)
对于最后一个任务,您可以使用第三方库火炬函数 https://github.com/szymonmaszke/torchfunc(免责声明:我是作者)或者直接去写你自己的钩子。