Examples · PyTorch
LSTM for sentiment analysis in PyTorch
A recurrent network that reads a text as a sequence of 128 token ids and decides whether it is positive or negative: an embedding gives every token a vector, a bidirectional LSTM reads the sequence forwards and backwards, and a Linear layer makes the decision.
Open in the editor See the code
- Code
- PyTorch
- Task
- Text classification
- Input
- 128
- Bricks
- 5
- Trainable parameters
- 2,824,706
What the network does
The Input holds 128 whole numbers (data type long), the ids of the tokens of a text from a vocabulary of 20,000. Embedding turns each id into a vector of 128 numbers; with 20,000 × 128 = 2,560,000 weights it is by far the largest part of the network’s 2,824,706 parameters.
The LSTM with 128 hidden units runs over the 128 vectors in both directions. Only its last hidden states are passed on (return_sequences off), and those of the two directions are joined: a vector of 256 numbers that summarises the text. After Dropout with p = 0.3, a Linear layer gives two scores, negative and positive.
When to use it
- For short texts with one label: reviews, support tickets, short messages, where the word order matters.
- To learn how sequence models handle shapes: the Embedding adds a dimension, the LSTM removes it again.
- For long texts or large datasets a Transformer encoder often works better; pretrained language models better still.
Layers, shapes and parameters
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
tokens | Input | shape=128 dtype=long | 128 | 0 |
embed | Embedding | num_embeddings=20000 embedding_dim=128 | 128 × 128 | 2,560,000 |
lstm | LSTM | hidden_size=128 bidirectional=true | 256 | 264,192 |
drop | Dropout | p=0.3 | 256 | 0 |
fc | Linear | out_features=2 | 2 | 514 |
| Total | 2,824,706 | |||
Training it in Brick DNN
In Brick DNN, text models train on demo data so far: random token sequences with a hidden rule, which shows that the network learns. For real texts, export the script: it contains the nn.Module and a check with a random batch of token ids; tokenise your texts into ids up to 20,000 and padded to 128, and train it with your own loop.
The generated code
This is the PyTorch script that the editor’s code dialog generates from the graph above (lstm_sentiment.py): an nn.Module with one attribute per layer and a forward method, plus a check that runs a random batch through it. It needs nothing but PyTorch.
# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""NeuralNetwork: generated with Brick DNN.
Input: (batch, 128) (integer token ids)
Output: (batch, 2)
Trainable parameters: 2,824,706
Print the model and run it on a random batch:
python this_file.py
"""
import torch
import torch.nn as nn
class NeuralNetwork(nn.Module):
def __init__(self) -> None:
super().__init__()
self.embedding_1 = nn.Embedding(20000, 128)
self.lstm_1 = nn.LSTM(128, 128, batch_first=True, bidirectional=True)
self.dropout_1 = nn.Dropout(p=0.3)
self.linear_1 = nn.Linear(256, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.embedding_1(x)
_, (hidden, _) = self.lstm_1(x)
x = torch.cat([hidden[-2], hidden[-1]], dim=-1)
x = self.dropout_1(x)
x = self.linear_1(x)
return x
def count_parameters(model: nn.Module) -> int:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def main() -> None:
model = NeuralNetwork()
print(model)
print(f"Trainable parameters: {count_parameters(model):,}")
# Check the model with a random batch of 2 samples.
model.eval()
x = torch.randint(0, 20000, (2, 128,))
with torch.no_grad():
out = model(x)
print("Output shape:", tuple(out.shape)) # expected (2, 2)
if __name__ == "__main__":
main()