liveBook · Manning

Bag-of-words model

As explained in Deep Learning with R, Third Edition

A bag-of-words model represents text as an unordered collection of tokens and assigns learned weights to token presence indicators.

A bag-of-words model discards word order, represents a review as an unordered set of tokens, and learns a weight for each token. Token presence can then serve as input for text classification. section 14.3 section 14.4

From a review to a feature vector

For “this movie made me cry,” tokenization produces token IDs such as [0, 1, 3, 0, 5]. Removing order gives {0, 1, 3, 5}; multi-hot encoding turns that set into [1, 1, 0, 1, 0, 1]. The resulting fixed-size vector records which vocabulary items are present, such as “cry,” but not their positions. section 14.4

Use the representation as a simple baseline for text classification:

  • Assign learned weights to words whose presence suggests a class, such as “terrible” for negative sentiment or “riveting” for positive sentiment. section 14.4
  • Prefer sequence models when meaning depends on word order; recurrent models and Transformers preserve or inject positional information. section 14.3
"this movie made me cry"

c("[UNK]" = 0, "movie" = 1, "film" = 2, "made" = 3, "laugh" = 4, "cry" = 5)

Inspect the toy sentence and vocabulary used to build the bag-of-words representation. section 14.4

c(1, 1, 0, 1, 0, 1)

Inspect the final multi-hot vector that records token presence and absence. section 14.4

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains tokenization, set conversion, multi-hot encoding, and learned word weights, but stops short of detailed model architecture.
Examples
Uses a toy review about crying, vocabulary IDs, an unordered token set, and a six-position multi-hot vector.
What it assumes
Assumes familiarity with tokenization and vocabulary IDs while demonstrating how to convert them into sets and indicators.
What you can do after
Apply it via tokenization and multi-hot encoding to create fixed-size inputs for a text-classification model.
How it connects
Contrasts with sequence models, recurrent models, and Transformer architecture through their different treatments of word order.

Also explained in

Compare how 5 books explain bag-of-words model →

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.