I'm trying to learn how to use an LSTM to predict the next character based on the previous character. I've successfully created a function that batches a long string of text (after one-hot encoding) into shape (batch_size, seq_len, one_hot_features). one_hot_features is simply the number of unique characters in the text.
Since my batching function gives me both training sequences and 'ground truth' sequences, I need the output of the LSTM network to be the same shape as the 'ground truth' batches so that I can plug both output and labels into the loss function.
So my questions are:
- How do I correctly define my network architecture to meet the above requirements.
- How do I shape my data as it passes through the various layers in the
forwardfunction?
This is my attempt, and the code will run, but the output of the network is incorrectly shaped for comparison to the 'ground truth' sequence batches:
class charNN(nn.Module):
def __init__(self, vocab, hidden_size, n_layers, dropout=0.5):
super().__init__()
self.vocab_length = len(vocab)
self.hidden_size = hidden_size
self.lstm = nn.LSTM(self.vocab_length, hidden_size, n_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, self.vocab_length)
def forward(self, x, hidden=None):
x, hidden = self.lstm(x, hidden) # -> (n_batches, seq_len, hidden_size)
x = x.reshape(-1, self.hidden_size) # -> (n_batches * seq_len, hidden_size)
x = self.fc(x) # -> (n_batches * seq_len, vocab_length)
return x, hidden
Thank you in advance. I've been struggling with this one for a couple days. I will also happily provide the code for training the network, if it is required. It does not throw any errors except to tell me that the output size and the true label sizes do not match.