python - 当 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
函数中适当地使用它?
解决方案
推荐阅读
- sql - SSIS 将值保存为参数
- docker - 是否可以重定向 Kubernetes 中的日志记录?
- reactjs - 如何将获取的结果作为路由器通量中组件的参数传递?
- android - Xamarin Forms - Android Splashscreen 也显示在主应用程序中
- c# - 将 FIlestream 复制到提供空文件的新流
- scala - 在 Monix 任务中为空
- nativescript - 如何在 nativescript 角度应用程序上分析导航滞后和内存不足问题?
- cucumber - 在场景和功能中重用 dataTable
- google-apps-script - 输入数据后锁定谷歌表格单元格
- c# - 我如何从模板子级创建一个 DependencyProperty 以从父级访问?