ValueError:优化器得到一个空的参数列表 [英] ValueError: optimizer got an empty parameter list

查看:18
本文介绍了ValueError:优化器得到一个空的参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下简单的线性类:

I create the following simple linear class:

class Decoder(nn.Module):
    def __init__(self, K, h=()):
        super().__init__()
        h = (K,)+h+(K,)
        self.layers = [nn.Linear(h1,h2) for h1,h2 in zip(h, h[1:])]

    def forward(self, x):
        for layer in self.layers[:-1]:
            x = F.relu(layer(x))
        return self.layers[-1](x)

但是,当我尝试将参数放入优化器类时,我收到错误ValueError: optimizer got a empty parameter list.

However, when I try to put the parameters in a optimizer class I get the error ValueError: optimizer got an empty parameter list.

decoder = Decoder(4)
LR = 1e-3
opt = optim.Adam(decoder.parameters(), lr=LR)

我的类定义有什么明显错误吗?

Is there something I'm doing obviously wrong with the class definition?

推荐答案

由于您将图层存储在 Decoder 内的常规 pythonic 列表中,Pytorch 无法告诉这些成员 self.list 实际上是子模块.将此列表转换为 pytorch 的 nn.ModuleList 和你的问题会得到解决

Since you store your layers in a regular pythonic list inside your Decoder, Pytorch has no way of telling these members of the self.list are actually sub modules. Convert this list into pytorch's nn.ModuleList and your problem will be solved

class Decoder(nn.Module):
    def __init__(self, K, h=()):
        super().__init__()
        h = (K,)+h+(K,)
        self.layers = nn.ModuleList(nn.Linear(h1,h2) for h1,h2 in zip(h, h[1:]))

这篇关于ValueError:优化器得到一个空的参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆