使用Torch进行数值优化,得到一个空的参数列表,

2024-04-29 13:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一些计算,并希望通过使用Pytorch优化这个参数。我没有定义神经网络,所以没有层次之类的东西。只是一个简单的计算序列。我使用torch.nn.模块能够使用Pytork的优化器。你知道吗

我的课看起来像这样:

class XTransformer(torch.nn.Module):

    def __init__(self, x):
        super(ReLUTransformer, self).__init__()
        self.x = x

    def funky_function(self, m, c):

        # do some computations
        m = self.x * 2 - m + c

        return m, c

    def forward(self, m, c):
        m, c = self.funky_function(m, c)
        return m, c

稍后,我定义并尝试优化这个参数x,如下所示:

x = torch.autograd.Variable(x, requires_grad=True)
model = XTransformer(x)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
m, c = smt
loss = loss_func()


for t in range(100):
    m , c = model(m, c)
    l = loss(m, true)
    optimizer.zero_grad()
    l.backward()
    optimizer.step()

我不知道该怎么办。我得到了“ValueError:optimizer得到了一个空参数列表”错误。当我把[x]作为参数给优化器时,它不会为我更新和更改x。我该怎么办?你知道吗


Tags: self参数modelreturn定义initdeffunction
1条回答
网友
1楼 · 发布于 2024-04-29 13:26:36

您需要将x注册为一个参数,让PyTorch知道这应该是一个可训练的参数。这可以通过在init期间将其定义为nn.Parameter来实现

    def __init__(self, x):
        super(ReLUTransformer, self).__init__()
        self.x = torch.nn.Parameter(x)

相关问题 更多 >