参考这个问答,有两种方法。
第一种,在定义 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)}
)
标签:__,nn,自定义,torch,指定,PyTorch,Conv2d,name
From: https://www.cnblogs.com/chirp/p/18081471