liveBook · Manning

Embedding

As explained in Deep Learning with R, Third Edition

An embedding is a learned numerical vector representation of an object, token, or other data item.

An embedding is a learned numerical representation of an item, such as a word, image, or prompt. For words, it turns token IDs into dense vectors that a model can use instead of large, sparse one-hot vectors. section 14.5.2 section 11.4.2

Classifying movie reviews

A movie review can be represented as a sequence of integer word IDs. A Keras Embedding layer maps each ID to a 64-number vector; a bidirectional LSTM then processes the sequence to predict sentiment. In one evaluation, this model achieved about 83% test accuracy, compared with about 70% for the one-hot LSTM baseline. section 14.5.3 section 14.5.1

Listing 14.22 Building an LSTM sequence model with an Embedding layer
hidden_dim <- 64L
inputs <- keras_input(shape = c(max_length), dtype = "int32")
outputs <- inputs |>
  layer_embedding(input_dim = max_tokens,
                  output_dim = hidden_dim,
                  mask_zero = TRUE) |>
  layer_bidirectional(layer_lstm(units = hidden_dim)) |>
  layer_dropout(0.5) |>
  layer_dense(1, activation = "sigmoid")

model <- keras_model(inputs, outputs, name = "lstm_with_embedding")
model |> compile(optimizer = "adam",
                 loss = "binary_crossentropy",
                 metrics = "accuracy")

This R/Keras model places an Embedding layer before a bidirectional LSTM. The layer uses 64 dimensions and masks zero-valued padding. section 14.5.3

An Embedding layer acts like a lookup table: each integer index selects a vector. Its input has shape (batch_size, sequence_length), and its output has shape (batch_size, sequence_length, embedding_size). The vectors start as random weights and are adjusted by backpropagation as the model trains. section 14.5.3

A useful word-embedding space can place related words close together: for example, “movie” and “film” should have similar vectors. Unlike one-hot vectors, embeddings are dense and relatively low-dimensional. Their structure is learned from data, and the relationships most useful for one task may differ from those useful for another. section 14.5.2 section 14.5.3

Embeddings can also be pretrained on unlabeled text. In continuous bag of words (CBOW), a model predicts a missing word from its surrounding words. Its learned embedding weights can initialize a classifier, which is then trained on the labeled task. In the movie-review example, this raised test accuracy to about 89%. section 14.5.4 section 14.5.5

Listing 14.26 Building a CBOW model
hidden_dim <- 64

cbow_embedding <- layer_embedding(
  input_dim = max_tokens,
  output_dim = hidden_dim
)

inputs <- keras_input(shape = c(2 * context_size), dtype = "int32")

outputs <- inputs |>
  cbow_embedding() |>
  layer_global_average_pooling_1d() |>
  layer_dense(max_tokens, activation = "softmax")

cbow_model <- keras_model(inputs, outputs)
cbow_model |> compile(
  optimizer = "adam",
  loss = "sparse_categorical_crossentropy",
  metrics = "sparse_categorical_accuracy"
)cbow_model

Model: "functional"

┌─────────────────────────────────┬────────────────────────┬───────────────┐

│ Layer (type)                    │ Output Shape           │       Param # │

├─────────────────────────────────┼────────────────────────┼───────────────┤

│ input_layer_4 (InputLayer)      │ (None, 8)              │             0 │

├─────────────────────────────────┼────────────────────────┼───────────────┤

│ embedding_1 (Embedding)         │ (None, 8, 64)          │     1,920,000 │

├─────────────────────────────────┼────────────────────────┼───────────────┤

│ global_average_pooling1d        │ (None, 64)             │             0 │

│ (GlobalAveragePooling1D)        │                        │               │

├─────────────────────────────────┼────────────────────────┼───────────────┤

│ dense_4 (Dense)                 │ (None, 30000)          │     1,950,000 │

└─────────────────────────────────┴────────────────────────┴───────────────┘

 Total params: 3,870,000 (14.76 MB)

 Trainable params: 3,870,000 (14.76 MB)

 Non-trainable params: 0 (0.00 B)

This CBOW model embeds surrounding word IDs, averages their vectors, and predicts the missing word. section 14.5.4

Embeddings also serve other roles:

  • Position embeddings are added to word embeddings to give a Transformer access to word order. section 15.3.5
  • In retrieval-augmented generation, document and query embeddings let a vector database find nearby document vectors and return their text as context. section 16.4.3
  • In image segmentation, an image encoder and prompt encoder produce embeddings that a mask decoder uses to predict masks. section 11.4.2

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains vector geometry, lookup shapes, training, and CBOW pretraining, while leaving image prompt-encoder and mask-decoder details unexplained.
Examples
Uses movie-review sentiment classification and missing-word prediction to demonstrate learned and pretrained word vectors.
What you can do after
Apply embeddings via Keras to sequence classification and initialize a classifier with pretrained CBOW weights.
How it connects
Connects embeddings to one-hot encoding, backpropagation, positional embeddings, and retrieval-augmented generation.

Also explained in

Compare how 51 books explain embedding →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.