N-gram
A run of n consecutive words or characters; the unit behind fuzzy text search, BLEU and ROUGE scores and the language models before neural networks.
An n-gram is a sequence of n neighboring items: “data structure” is a word bigram (n = 2), and “dat”, “ata”, “ta ” are character trigrams (n = 3). Splitting text into n-grams turns fuzzy questions into counting: two strings that share many n-grams are probably similar, even with typos.
That is how Postgres pg_trgm finds “Jonh Smiht” when you search for “John Smith” and speeds up LIKE '%term%' with an inverted index of trigrams. BLEU and ROUGE score generated text by n-grams shared with a reference. Before neural networks, language models predicted the next word from counts of the previous few words, and n-gram counts still help detect benchmark data that leaked into training sets.
N-grams know nothing about meaning: “not good” and “good” share a word. For meaning, search uses embeddings; n-grams stay useful for names, codes and typos.
Sources
- PostgreSQL: pg_trgm, trigram similarity postgresql.org
Related terms
- BLEU and ROUGE: Older text metrics that score a generated text by its word overlap with a reference text: BLEU for translation, ROUGE for summaries.
- Inverted index: A map from each word to the list of documents that contain it; the structure behind keyword search engines and BM25.
- Byte-pair encoding (BPE tokenizer): The method most language models use to split text into tokens: start from bytes and repeatedly merge the most frequent pairs into new tokens.
- Tokens: The pieces of text models read and write, and the unit you pay for.
- Trie (prefix tree): A tree where each step down adds one character, so all words sharing a prefix share a path; the classic structure for autocomplete.
