【问题标题】:What is the output of pytorch RNN?pytorch RNN 的输出是什么?
【发布时间】:2021-07-02 05:48:51
【问题描述】:

我下面有一个简单的rnn代码。

rnn = nn.RNN(1, 1, 1, bias = False, batch_first = True)
t = torch.ones(size = (1, 2, 1))
output, hidden = rnn(t)
print(rnn.weight_ih_l0)
print(rnn.weight_hh_l0)
print(output)
print(hidden)

# Outputs
Parameter containing:
tensor([[0.7199]], requires_grad=True)

Parameter containing:
tensor([[0.4698]], requires_grad=True)

tensor([[[0.6168],
     [0.7656]]], grad_fn=<TransposeBackward1>)
tensor([[[0.7656]]], grad_fn=<StackBackward>)

tensor([[[0.7656]]], grad_fn=<StackBackward>)

我对 PyTorch 文档的理解是,上面的输出是隐藏状态。

所以,我尝试使用以下手动计算输出

hidden_state1 = torch.tanh(t[0][0] * rnn.weight_ih_l0)
print(hidden_state1)
hidden_state2 = torch.tanh(t[0][1] * rnn.weight_ih_l0 + hidden_state1 * rnn.weight_hh_l0)
print(hidden_state2)

tensor([[0.6168]], grad_fn=<TanhBackward>)
tensor([[0.7656]], grad_fn=<TanhBackward>)

结果是正确的。 hidden_​​state1 和 hidden_​​state2 匹配输出。

难道不应该将 hidden_​​states 与输出权重相乘得到输出吗?

我检查了从隐藏状态连接到输出的权重。但根本没有权重。

如果 rnn 的目标是只计算隐藏状态,谁能告诉我如何得到输出?

【问题讨论】:

  • 最后的隐藏状态不可以算“输出”吗?

标签: pytorch recurrent-neural-network


【解决方案1】:

不应该将 hidden_​​states 与输出权重相乘以得到 输出

是和否。这取决于您的问题表述。假设您正在处理最后一个时间步的输出只重要的情况。在这种情况下,将隐藏状态乘以每个单元的输出权重确实没有意义。 这就是为什么 pytorch 只给你隐藏输出作为一个抽象值,之后你就可以真正疯狂地根据你的问题对隐藏状态做任何你想做的事情。

在您的特定情况下,假设您想在每个时间步将另一个线性层应用于输出。只需定义一个线性层并传播隐藏单元的输出即可。

#Linear Layer
##hidden_feature_size = 1 in your case
lin_layer = nn.Linear(hidden_feature_size, output_feature_size) 
#output from first timestep
linear_layer(output[0])
#output from second timestep
linear_layer(output[1])

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 2018-08-13
    • 1970-01-01
    • 2020-09-30
    • 2020-09-21
    • 2018-09-15
    • 2021-01-16
    • 1970-01-01
    • 2019-12-29
    相关资源
    最近更新 更多