pytorch RNN 的输出是什么?

What is the output of pytorch RNN?

下面我有一个简单的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的objective只计算隐藏状态,谁能告诉我如何得到输出?

Shouldn’t the hidden_states get multiplied with output weights to get the output

是和否。这取决于您的问题表述。假设您正在处理一个案例,其中最后一个时间步长的输出很重要。在那种情况下,将隐藏状态乘以每个单元的输出权重真的没有意义。 这就是为什么 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])