我有y = Y(x;theta)
和theta = M(t;omega)
,其中x
和t
是输入变量(从数据集获得),以及theta
和omega
可训练参数。我需要具有theta
作为omega
的功能。然后,我在y
上有一个损失函数,需要通过M
向后传播该梯度,直到Y
。如何在pytorch中创建这样的结构?
当前,我的网络构建如下(sizes
是整数列表,定义为sizes = [input_size, hidden1_size, hidden2_size, ..., output_size]
)
class M(nn.Module):
def __init__(self, sizes):
super(Y, self).__init__()
self.layers = nn.ModuleList()
for i in range(0, len(sizes) - 1):
self.layers.append(nn.Linear(sizes[i], sizes[i+1]))
def forward(self, x):
for l in self.layers[:-1]:
x = F.relu(l(x))
x = self.layers[-1](x)
return x
我认为这很简单,或者我没有正确获得您的查询。
[x
,t
是您的输入变量。
现在让我们定义一个网络M
,它将接受输入t并输出theta
。
M = nn.Sequential(....) # declare network here
接下来,我们定义网络Y
。当您想使用theta作为参数时,这可能很棘手。使用在nn
中声明的模块的功能对应项可能更容易和直观(请参见https://pytorch.org/docs/stable/nn.functional.html)。我将尝试给出一个示例,假设theta是线性模块的参数。
class Y(nn.Module):
def __init__(self):
# declare any modules here
def forward(self, theta, x):
return nn.functional.linear(input=x, weight=theta, bias=None)
整体向前通过将是>
def forward(t, x, M, Y):
theta = M(t)
output = Y(theta, x)
return output