liveBook · Manning

Embedding layer

As explained in Natural Language Processing in Action, Second Edition

nn.Embedding is a PyTorch module that maps integer token indices to trainable dense embedding vectors.

An embedding layer converts integer token IDs into dense vectors that carry more information than sparse one-hot encodings. In PyTorch, nn.Embedding can learn these vectors while the surrounding model learns its task. section 7.4.2

Configure an embedding layer by deciding:

  • Vocabulary capacity: set num_embeddings to the number of token IDs, including a padding token when one is used. section 7.4.2 section 7.5.1
  • Vector width: set embedding_dim to control how many learned values represent each token. section 7.4.2
  • Initialization: learn vectors from scratch or load pretrained GloVe vectors, retaining trainability when domain adaptation is needed. section 7.4.3
  • Convolution interface: transpose the embedding output when necessary so embedding dimensions become convolution channels rather than the sequence axis. section 7.4.2

Create a trainable embedding table

from torch import nn embedding = nn.Embedding( num_embeddings=2000, embedding_dim=64, padding_idx=0, ) This allocates a 2,000-token vocabulary with 64 values per token and reserves index 0 for padding.

Listing 7.24 Initializing your embedding layer with GloVe vectors
embed = torch.Tensor(embed)                  #1
print(f'embed.size(): {embed.size()}')
embed = nn.Embedding.from_pretrained(embed, freeze=False)    #2
print(embed)

Inspect the GloVe initialization workflow: align vectors with vocabulary order, convert them to a tensor, and load them with nn.Embedding.from_pretrained(..., freeze=False). section 7.4.3

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Explains vocabulary sizing, vector dimensions, padding, pretrained loading, and convolution reshaping, but defers embedding mathematics.
Examples
Uses 2,000-token 64-dimensional scratch embeddings, 4,000-token 50-dimensional GloVe alignment, and CNN layer-shape listings.
What it assumes
Assumes tokenization and integer vocabulary IDs while teaching embedding dimensions, padding configuration, and pretrained alignment.
What you can do after
Build and initialize trainable PyTorch embeddings from scratch or pretrained GloVe vectors, then connect them to convolutions.
How it connects
Connects one-hot encoding, word embeddings, vocabulary, padding tokens, convolution, transfer learning, and GloVe.

Also explained in

Compare how 4 books explain embedding layer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.