我有一个自定义的双向LSTM模型,其中自定义部分是
- extract the forward and backward last hidden state
- concat those states
- create a fully connected layer and pass it through softmax layer.
代码如下所示:
class customModel(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(customModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.bilstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=False, bidirectional=True)
self.fcl = nn.Linear(hidden_size, num_classes)
def forward(self, x):
# Set initial hidden and cell states
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
# Forward propagate LSTM
out, hidden = self.bilstm(x, (h0, c0)) # out: tensor of shape (batch_size, seq_length, hidden_size)
#concat hidden state of forward and backword
fw_bilstm = out[-1, :, :self.hidden_size]
bk_bilstm = out[0, :, :self.hidden_size]
concat_fw_bw = torch.cat((fw_bilstm, bk_bilstm), dim = 1)
fc = nn.Linear(concat_fw_bw, num_classes)
x = F.relu(fc(x))
return F.softmax(x)
我使用以下参数和输入
input_size = 2
hidden_size = 32
num_layers = 1
num_classes = 2
input_embedding = [
torch.FloatTensor([[-0.8264], [0.2524]]),
torch.FloatTensor([[-0.3259], [0.3564]])
]
然后我创建一个模型对象
model = customModel(input_size, hidden_size, num_layers, num_classes)
然后我使用如下:
for item in input_embedding:
print(item.size())
for epoch in range(1):
pred = model(item)
print (pred)
当我运行它时,我看到了这条线
out, hidden = self.bilstm(x, (h0, c0))
,显示错误
RuntimeError: input must have 3 dimensions, got 2
我不知道为什么当我显式指定输入时,模型认为输入必须具有3维
input_size=2
我错过了什么?