PyTorch torch.nn.Embedding function
PyTorch torch.nn Reference Manual
torch.nn.Embedding is a module in PyTorch for word embeddings.
It maps discrete vocabulary indices to a continuous vector space and is one of the most fundamental operations in natural language processing.
Function definition
torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False)
Parameter Description:
num_embeddings(int): vocabulary size, i.e. the number of rows in the embedding matrix.embedding_dim(int): the dimension of each embedding vector.padding_idx(int): specifies the padding index, whose embedding vector is a zero vector. Default is None.max_norm(float): if not None, embedding vectors are normalized to this norm. Default is None.norm_type(float): the order of the norm to compute. Default is 2.0.scale_grad_by_freq(bool): whether to scale gradients by word frequency. Default is False.sparse(bool): whether the weight matrix is sparse. Default is False.
property through the following steps:
weight(Tensor): learnable weights of shape (num_embeddings, embedding_dim).
Usage examples
Example 1: Basic usage
Creating and using word embeddings:
Example
import
torch
import
torch.
nn
as
nn
Create an embedding layer: vocabulary 10000, embedding dimension 256
embedding
=
nn.
Embedding
(
num_embeddings
=
10000
,
embedding_dim
=
256
)
Word indices (starting from 0)
Shape: (batch, seq_len)
input_indices
=
torch.
tensor
(
[
[
12
,
45
,
678
]
,
[
901
,
23
,
56
]
]
)
Look up the table to get embedding vectors
output
=
embedding
(
input_indices
)
(
"Input index shape:"
,
input_indices.
shape
)
(
"Output embedding shape:"
,
output.
shape
)
(2, 3, 256)
Check the shape of the embedding matrix
(
"Embedding matrix shape:"
,
embedding.
weight
.
shape
)
Example 2: Using padding_idx
Specify the padding index:
Example
import
torch
import
torch.
nn
as
nn
Create an embedding layer with padding
embedding
=
nn.
Embedding
(
num_embeddings
=
1000
,
embedding_dim
=
64
,
padding_idx
=
0
)
0 is used as padding
input_indices
=
torch.
tensor
(
[
[
1
,
2
,
3
]
,
[
4
,
0
,
0
]
]
)
The second sentence has padding
output
=
embedding
(
input_indices
)
(
"Input shape:"
,
input_indices.
shape
)
(
"Output shape:"
,
output.
shape
)
(
"Embedding vector for padding:"
,
output
[
1
,
1
]
.
tolist
(
)
)
All 0
(
"Embedding vector for non-padding:"
,
output
[
0
,
0
]
.
tolist
(
)
[
:
5
]
)
non-zero
Example 3: Pretrained word vectors
Loading pretrained word vectors:
Example
import
torch
import
torch.
nn
as
nn
import
numpy
as
np
Simulate pretrained word vectors (in practice you can use GloVe, Word2Vec, etc.)
vocab_size
=
1000
embedding_dim
=
300
Random initialization (in practice you should load pretrained vectors)
pretrained_weights
=
np.
random
.
randn
(
vocab_size
,
embedding_dim
)
.
astype
(
'float32'
)
Create an embedding layer
embedding
=
nn.
Embedding
(
vocab_size
,
embedding_dim
)
Load pretrained weights
embedding.
weight
.
data
=
torch.
from_numpy
(
pretrained_weights
)
Freeze the embedding layer (not involved in training)
embedding.
weight
.
requires_grad
=
False
(
"Embedding layer trainable:"
,
embedding.
weight
.
requires_grad
)
(
"Embedding matrix shape:"
,
embedding.
weight
.
shape
)
Example 4: Limiting embedding vector norms
Using max_norm to limit vector norms:
h2 class="example">Example
import
torch
import
torch.
nn
as
nn
Limit the maximum embedding vector norm to 1.0
embedding
=
nn.
Embedding
(
1000
,
64
,
max_norm
=
1.0
)
Input
input_indices
=
torch.
tensor
(
[
1
,
2
,
3
]
)
Original weight norm
original_norm
=
embedding.
weight
.
data
.
norm
(
dim
=
1
)
[
:
3
]
(
"Original weight norm:"
,
original_norm.
tolist
(
)
)
Vector norm after lookup
output
=
embedding
(
input_indices
)
output_norm
=
output.
norm
(
dim
=
1
)
(
"Output vector norm:"
,
output_norm.
tolist
(
)
)
Example 5: A complete text classification model
Text classification using an embedding layer:
Example
import
torch
import
torch.
nn
as
nn
class
TextClassifier
(
nn.
Module
)
:
def
init
(
self
,
vocab_size
,
embed_dim
,
hidden_dim
,
num_classes
=
2
)
:
super
(
TextClassifier
,
self
)
.
init
(
)
Word embedding layer
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
0
)
LSTM
self
.
lstm
=
nn.
LSTM
(
embed_dim
,
hidden_dim
,
batch_first
=
True
)
Classifier
self
.
classifier
=
nn.
Linear
(
hidden_dim
,
num_classes
)
def
forward
(
self
,
x
)
:
x: (batch, seq_len)
embedded
=
self
.
embedding
(
x
)
(batch, seq_len, embed_dim)
LSTM takes the last output
_
,
(
hidden
,
_
)
=
self
.
lstm
(
embedded
)
hidden
=
hidden
[
1
]
Hidden state of the last layer
Classification
logits
=
self
.
classifier
(
hidden
)
return
logits
Parameters
VOCAB_SIZE
=
10000
EMBED_DIM
=
128
HIDDEN_DIM
=
256
model
=
TextClassifier
(
VOCAB_SIZE
,
EMBED_DIM
,
HIDDEN_DIM
)
Input: batch=4, sequence length=50
input_ids
=
torch.
randint
(
1
,
VOCAB_SIZE
,
(
4
,
50
)
)
output
=
model
(
input_ids
)
(
"Model structure:"
)
(
model
)
(
"nInput shape:"
,
input_ids.
shape
)
(
"Output shape:"
,
output.
shape
)
Difference between Embedding and EmbeddingBag
| Type | Input | Output | Applicable scenarios |
|---|---|---|---|
nn.Embedding |
Word indices | Sequence of word vectors | Sequence models, LSTM, Transformer |
nn.EmbeddingBag |
Word indices + offsets | Aggregated vector | Text classification, fast processing |
Common questions
Q1: How to choose the embedding dimension?
- Small datasets: 50-100 dimensions
- Medium datasets: 100-300 dimensions
- Large datasets: 300-500 dimensions
Q2: What is the role of padding_idx?
Set the embedding vector of the specified index to a zero vector and do not compute its gradient during backpropagation.
Q3: When to freeze the embedding layer?
When using pretrained word vectors, it is common to freeze them for a period of training before fine-tuning.
Use Cases
nn.Embedding Main application scenarios include:
- Word Vector Representation: converts words into dense vectors
- Text classification: serves as the input layer of NLP models
- Sequence models: input to LSTM and GRU
- Recommendation systems: embedding representations of users and items
Note: embedding.weight is a learnable parameter and can be trained directly in the optimizer.