Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.Embedding function

PyTorch torch.nn.Embedding function

PyTorch torch.nn Reference Manual 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:

property through the following steps:


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

)

print

(

"Input index shape:"

,

input_indices.

shape

)

print

(

"Output embedding shape:"

,

output.

shape

)

 

(2, 3, 256)

Check the shape of the embedding matrix

print

(

"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

)

print

(

"Input shape:"

,

input_indices.

shape

)

print

(

"Output shape:"

,

output.

shape

)

print

(

"Embedding vector for padding:"

,

output

[

1

,

1

]

.

tolist

(

)

)

 

All 0

print

(

"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

print

(

"Embedding layer trainable:"

,

embedding.

weight

.

requires_grad

)

print

(

"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

]

print

(

"Original weight norm:"

,

original_norm.

tolist

(

)

)

Vector norm after lookup

output

=

embedding

(

input_indices

)

output_norm

=

output.

norm

(

dim

=

1

)

print

(

"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

)

print

(

"Model structure:"

)

print

(

model

)

print

(

"nInput shape:"

,

input_ids.

shape

)

print

(

"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?

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:

Note: embedding.weight is a learnable parameter and can be trained directly in the optimizer.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual