In tensorflow/keras, we can simply set return_sequences = False
for the last LSTM layer before the classification/fully connected/activation (softmax/sigmoid) layer to get rid of the temporal dimension.
In PyTorch, I don't find anything similar. For the classification task, I don't need a sequence to sequence model but many to one architecture like this:
Here's my simple bi-LSTM model.
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()
If I observe the shapes after each layer,
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])
What can I do so that the last LSTM returns a tensor with shape (1, 16)
instead of (1, 512, 16)
?
x = x[:, -1, :]
wherex
is the LSTM output. – xdurch0return_sequences = False
? – Zabir Al Nazi