【发布时间】:2019-08-03 17:15:00
【问题描述】:
我在 PyTorch 中实现了一个 LSTM,如下所示。
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class LSTM(nn.Module):
"""
Defines an LSTM.
"""
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super(LSTM, self).__init__()
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
def forward(self, input_data):
lstm_out_pre, _ = self.lstm(input_data)
return lstm_out_pre
model = LSTM(input_dim=2, hidden_dim=2, output_dim=1, num_layers=8)
random_data1 = torch.Tensor(np.random.standard_normal(size=(1, 5, 2)))
random_data2 = torch.Tensor(np.random.standard_normal(size=(1, 5, 2)))
out1 = model(random_data1).detach().numpy()
out2 = model(random_data2).detach().numpy()
print(out1)
print(out2)
我只是创建一个 LSTM 网络并将两个随机输入传递给它。输出没有意义,因为无论 random_data1 和 random_data2 是什么,out1 和 out2 总是相同的。这对我来说没有任何意义,因为随机输入乘以随机权重应该给出不同的输出。
如果我使用较少数量的隐藏层,情况似乎并非如此。使用num_layers=2,这种效果似乎为零。当你增加它时,out1 和out2 会越来越近。这对我来说没有意义,因为随着更多层的 LSTM 堆叠在一起,我们将输入与更多数量的随机权重相乘,这应该会放大输入的差异并给出非常不同的输出。
有人可以解释一下这种行为吗?我的实现有问题吗?
在一次特定的运行中,random_data1 是
tensor([[[-2.1247, -0.1857],
[ 0.0633, -0.1089],
[-0.6460, -0.1079],
[-0.2451, 0.9908],
[ 0.4027, 0.3619]]])
random_data2是
tensor([[[-0.9725, 1.2400],
[-0.4309, -0.7264],
[ 0.5053, -0.9404],
[-0.6050, 0.9021],
[ 1.4355, 0.5596]]])
out1 是
[[[0.12221643 0.11449362]
[0.18342148 0.1620608 ]
[0.2154751 0.18075559]
[0.23373817 0.18768947]
[0.24482158 0.18987371]]]
out2是
[[[0.12221643 0.11449362]
[0.18342148 0.1620608 ]
[0.2154751 0.18075559]
[0.23373817 0.18768945]
[0.24482158 0.18987371]]]
编辑: 我在以下配置上运行 -
PyTorch - 1.0.1.post2
Python - 3.6.8 with GCC 7.3.0
OS - Pop!_OS 18.04 (Ubuntu 18.04, more-or-less)
CUDA - 9.1.85
Nvidia driver - 410.78
【问题讨论】:
-
我无法重现此行为。当我在 PyTorch 1.0.0 上测试你的代码时,我得到两个不同的输出。我建议在具有其他 PyTorch 版本的不同系统上尝试它。
-
谢谢。我会尝试使用不同的版本并更新。
标签: python lstm pytorch recurrent-neural-network