import torch
import torch.nn as nn
from collections import OrderedDict
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10,10)
self.relu1 = nn.ReLU(inplace=True)
self.fc2 = nn.Linear(10,2)
def forward(self,x):
x = self.fc1(x)
x = self.relu1(x)
x = self.fc2(x)
return x


class Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        self.base = nn.ModuleList([nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2)])    def forward(self,x):        x = self.base(x)        return x


nn.ModuleList()接收的参数为一个List，这样就可以很方便的定义一个网络，比如

base = [nn.Linear(10,10) for i in range(5)]net = nn.ModuleList(base)


class Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        self.base = nn.Sequential(nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2))    def forward(self,x):        x = self.base(x)        return x


class MultiLayerNN5(nn.Module):    def __init__(self):        super(MultiLayerNN5, self).__init__()        self.base = nn.Sequential(OrderedDict([            ('0', BasicConv(1, 16, 5, 1, 2)),            ('1', BasicConv(16, 32, 5, 1, 2)),        ]))        self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):        x = self.base(x)        x = x.view(x.size(0), -1)        x = self.fc1(x)        return x


class MultiLayerNN4(nn.Module):    def __init__(self):        super(MultiLayerNN4, self).__init__()        self.base = nn.Sequential()        self.base.add_module('0', BasicConv(1, 16, 5, 1, 2))        self.base.add_module('1', BasicConv(16, 32, 5, 1, 2))        self.fc1 = nn.Linear(32 * 7 * 7, 10)
def forward(self, x):        x = self.base(x)        x = x.view(x.size(0),-1)        x = self.fc1(x)


tt = [nn.Linear(10,10), nn.Linear(10,2)]n_1 = nn.Sequential(*tt)n_2 = nn.ModuleList(tt)x = torch.rand([1,10,10])x = Variable(x)n_1(x)n_2(x)#会出现NotImplementedError


class DenseLayer(nn.Sequential):    def __init__(self):        super(DenseLayer, self).__init__()        self.add_module("conv1", nn.Conv2d(1, 1, 1, 1, 0))        self.add_module("conv2", nn.Conv2d(1, 1, 1, 1, 0))
def forward(self, x):        new_features = super(DenseLayer, self).forward(x)        return torch.cat([x, new_features], 1)#这个写法和下面的是一样的class DenLayer1(nn.Module):    def __init__(self):        super(DenLayer1, self).__init__()        convs = [nn.Conv2d(1, 1, 1, 1, 0), nn.Conv2d(1, 1, 1, 1, 0)]        self.conv = nn.Sequential(*convs)    def forward(self, x):        return torch.cat([x, self.conv(x)], 1)net = DenLayer1()x = torch.Tensor([[[[1, 2], [3, 4]]]])print(x)x = Variable(x)print(net(x))