将网络输出作为另一个网络参数

问题描述 投票:0回答:1

我有y = Y(x;theta)theta = M(t;omega),其中xt是输入变量(从数据集获得),以及thetaomega可训练参数。我需要具有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
neural-network pytorch parameter-passing gradient-descent backpropagation
1个回答
0
投票

我认为这很简单,或者我没有正确获得您的查询。

[xt是您的输入变量。

现在让我们定义一个网络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
© www.soinside.com 2019 - 2024. All rights reserved.