首页 > 解决方案 > 当 n 是函数的参数时,如何在 pytorch 中创建 n 个线性层

问题描述

我有以下模型:

class model(nn.Module):
     def __init__(self,y_dim,x_dim):
         super(model,self).__init__()
         self.x_dim = x_dim
         self.y_dim = y_dim
         self.kern = 3
         self.conv1 = nn.Conv1d(y_dim,2,self.kern,padding=1)
         self.conv2 = nn.Conv1d(2,4,self.kern,padding=1)
         self.conv3 = nn.Conv1d(4,4,self.kern,padding=1)
         self.conv4 = nn.Conv1d(4,y_dim,self.kern,padding=1)
         #these are the layers I want to automate
         self.lina = nn.Linear(28,28)
         self.linb = nn.Linear(28,28)
     def forward(self,x):
         x = F.relu(self.conv1(x))
         x = F.relu(self.conv2(x))
         x = F.relu(self.conv3(x))
         x = F.relu(self.conv4(x))
         xa = self.lina(x[:,0,:]).reshape(z.shape[0],1,z.shape[2])
         xb = self.linb(x[:,1,:]).reshape(z.shape[0],1,z.shape[2])
         return torch.cat((xa,xb),1)

model = model(2,28)

因此, 的输出通道self.conv4始终为y_dim。我希望有y_dim不同的线性层(它们是独立的)来获取self.conv4. 到目前为止,我不知道比明确编写图层更好的方法,就像我在上面的示例中所做的那样。但是,是否有一种方法可以自动执行此操作,即生成线性图层对象,然后在forward函数中适当地使用它?

标签: pythonneural-networkpytorch

解决方案


推荐阅读