Hacker News new | ask | show | jobs
by mlthoughts2018 2931 days ago
Bag of words is an encoding method for converting some sequence of words into a long, sparse vector of word counts. The vector has one component for each possible word of the vocabulary, and if the count of word i is N, then you store N in conponent i of the bag of words vector.

If you think of these as sparse row vectors (the columns correspond to all vocabulary entries), then you store them as a matrix where you stack on another row for each “document” in your data set.

Later on when you get a new “document” at query time, you transform it into the same bag of words vector format, and then an inner product between the matrix and the query vector corresponds to a type of relevance / similarity useful for sorting into a ranked order of results.

In practical situations you have to work harder, because you need more units of text than just words (such as n-grams), and the raw term counts usually need to be weighted (e.g. matching a 3-gram probably means more than matching a single word) or normalized (e.g. longer documents happen to have more words, but that doesn’t mean they are more similar), and you need to account for results that are historically more popular or results that are newer.

It’s a very simple approach to document search, but it works well and there are extensions that utilize word embeddings or models that predict rankings of results.

Once you get a system running with the term-document matrix, it is a nice platform for more advanced experimentation and machine learning feature development.