【问题标题】:LSTMCell parameters is not shown PytorchLSTMCell 参数未显示 Pytorch
【发布时间】:2019-03-15 15:49:41
【问题描述】:

我有以下代码:

class myLSTM(nn.Module):
def __init__(self, input_size, output_size, hidden_size, num_layers):
    super(myLSTM, self).__init__()
    self.input_size = input_size + 1 
    self.output_size = output_size
    self.hidden_size = hidden_size
    self.num_layers = num_layers
    self.layers = []
    new_input_size = self.input_size
    for i in xrange(num_layers):
        self.layers.append(LSTMCell(new_input_size, hidden_size))
        new_input_size = hidden_size
    self.linear = nn.Linear(hidden_size, output_size)
    self.softmax = nn.Softmax()

def forwardLayers(self, input, hns, cns, layers):
    new_hns = []
    new_cns = []
    (hn, cn) = layers[0](input, (hns[0], cns[0]))
    new_hns.append(hn)
    new_cns.append(cn)
    for i in xrange(1, len(layers)):
        (hn, cn) = layers[i](hn, (hns[i], cns[i]))
        new_hns.append(hn)
        new_cns.append(cn)
    return hn, (new_hns, new_cns)

def forward(self, input, hx):
    actions = []
    hns, cns = hx
    action = torch.Tensor([[0.0]])
    for i in range(len(input)):
        new_input = input[i]
        new_input = new_input.view(1, -1)
        output, (hns, cns) = self.forwardLayers(new_input, hns, cns, self.layers)
        output = self.softmax(self.linear(output))

    return output

现在当我调用以下代码查看我的网络参数时:

for name, param in myLSTM_object.named_parameters():
        if param.requires_grad:
            print name, param.data

我得到的是:

linear.weight tensor([[ 0.5042, -0.6984],
    [ 0.0721, -0.4060]])
linear.bias tensor([ 0.6968, -0.4649])

所以,它完全错过了 LSTMCell 的参数。这是否意味着 LSTMCell 的参数没有经过训练。怎么看LSTMCell参数?

【问题讨论】:

    标签: deep-learning lstm pytorch backpropagation


    【解决方案1】:

    这是意料之中的 - 将模块存储在 listdictset 或其他 python 容器中不会将它们注册到拥有上述 list 等的模块中。要使您的代码正常工作,请使用 @ 987654321@ 代替。就像修改你的 __init__ 代码一样简单

    layers = []
    new_input_size = self.input_size
    for i in xrange(num_layers):
        layers.append(LSTMCell(new_input_size, hidden_size))
        new_input_size = hidden_size
    self.layers = nn.ModuleList(layers)
    

    【讨论】:

    • 感谢您的评论。这是否意味着在我的代码中,LSTMCeell 的参数没有更新?
    • 如果您能回答我之前的评论,我将不胜感激。这对我来说非常重要。
    • 基本上唯一的区别是你找到的那个:named_parameters()(和parameters())不会返回你LSTMCells的参数。这具有至关重要的后果,如果您通过传递 model.parameters() 来构造优化器,优化器将不会意识到 LSTMCell 参数并且不会在训练期间更新参数。使用ModuleList 可以解决这个问题。
    • 你也可以回答这个问题stackoverflow.com/questions/55188698/…吗?非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    相关资源
    最近更新 更多