为 PyTorch 层指定自定义名称

参考这个问答,有两种方法。

第一种,在定义 nn.Sequential 时传入 OrderedDict 类型变量。

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)

第二种,使用 nn.ModuleDict 定义层。

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)}
        )
posted @ 2024-03-18 21:26  倒地  阅读(52)  评论(0编辑  收藏  举报