Bag of Words Counts Tokens and Throws Away Word Order
Bag of words represents a document by how many times each token appears in it, and it discards the order the words came in. Jurafsky and Martin put it this way in their chapter on naive Bayes: "We represent a text document as if it were a bag-of-words, that is, an unordered set of words with their position ignored, keeping only their frequency in the document." To use it you need a fixed vocabulary and a tokenizer that splits text into tokens, and then each document becomes a vector with one count per vocabulary entry.
Try it by hand. In both examples below I lowercase the text and drop the punctuation before splitting it into words, so "To" and "to" count as the same token. Start with the sentence "To be or not to be" and the vocabulary (be, not, or, to). Count each entry: be 2, not 1, or 1, to 2, so the vector is (2, 1, 1, 2). The counts remember that "to" and "be" repeated, and nothing else. Now take two sentences and the vocabulary (bad, good, movie, not, the, was): "The movie was good, not bad" and "The movie was bad, not good". Each contains the six tokens once, so both become (1, 1, 1, 1, 1, 1). The two sentences say opposite things about the movie, and the vectors cannot tell them apart. That is exactly what the authors mean by position ignored: "I love this movie" and "I would recommend it" are reduced to counts, such as the word "I" appearing 5 times in their example review.
Why would anyone throw the order away? Because counting is simple and it works well enough for many tasks. The authors' sentiment classifier uses these counts as its features, and the counts say a lot about topic and tone: a review full of "love", "fun", and "great" is probably positive without any grammar. The price is everything order carries, like negation scope, who did what to whom, and any phrase that means more than its words.
Variants keep the idea and change the numbers. A binary bag of words records only whether a token occurs. Weighted versions, such as TF-IDF, scale each count by how rare the token is across documents. (Those two variants are standard practice; the passage above is the one I read in the chapter.) All of them rely on a fixed vocabulary and a tokenizer, so a new word that was not in the vocabulary has nowhere to go.
The trap: assuming a bag-of-words vector keeps grammar or word order. It keeps neither. Two different sentences, even opposite ones, can share the same vector.
Prof Rod's rule: before you rely on counts, check what the model cannot see, and ask whether the question you care about depends on order.
The sentences and vocabularies are invented for the example.