【发布时间】:2020-09-23 23:56:04
【问题描述】:
在 tensorflow/keras 中,我们可以简单地为分类/全连接/激活(softmax/sigmoid)层之前的最后一个 LSTM 层设置return_sequences = False,以摆脱时间维度。
在 PyTorch 中,我找不到类似的东西。对于分类任务,我不需要序列到序列模型,而是像这样的多对一架构:
这是我的简单双 LSTM 模型。
import torch
from torch import nn
class BiLSTMClassifier(nn.Module):
def __init__(self):
super(BiLSTMClassifier, self).__init__()
self.embedding = torch.nn.Embedding(num_embeddings = 65000, embedding_dim = 64)
self.bilstm = torch.nn.LSTM(input_size = 64, hidden_size = 8, num_layers = 2,
batch_first = True, dropout = 0.2, bidirectional = True)
# as we have 5 classes
self.linear = nn.Linear(8*2*512, 5) # last dimension
def forward(self, x):
x = self.embedding(x)
print(x.shape)
x, _ = self.bilstm(x)
print(x.shape)
x = self.linear(x.reshape(x.shape[0], -1))
print(x.shape)
# create our model
bilstmclassifier = BiLSTMClassifier()
如果我观察每一层之后的形状,
xx = torch.tensor(X_encoded[0]).reshape(1,512)
print(xx.shape)
# torch.Size([1, 512])
bilstmclassifier(xx)
#torch.Size([1, 512, 64])
#torch.Size([1, 512, 16])
#torch.Size([1, 5])
我该怎么做才能让最后一个 LSTM 返回形状为 (1, 16) 而不是 (1, 512, 16) 的张量?
【问题讨论】:
-
只取那个维度的最后一个元素?
x = x[:, -1, :]其中x是 LSTM 输出。 -
谢谢,@xdurch0 似乎是一个简单的解决方案。和tensorflow
return_sequences = False一样吗? -
我决定做一点挖掘并发布一个正确的答案。 tl;博士:是的。
标签: python-3.x tensorflow nlp pytorch lstm