Notes

N-gram

A bag-of-words vector records which words a document contains and forgets the order they came in, which is why “not good at all” and “good, not at all bad” look nearly identical to it. Counting short runs of adjacent words instead of single words is the cheapest repair, and an n-gram is exactly such a run.

What the unit is
An n-gram is a contiguous sequence of n items drawn from text, usually words and often characters. “Turn the heating down” gives the bigrams “turn the”, “the heating”, “heating down”; one item is a unigram, two a bigram, three a trigram. Each distinct n-gram becomes a column of the document-term matrix, so the feature space grows steeply — a 20,000-word vocabulary admits 400 million possible bigrams, of which a real corpus contains a tiny, very sparse fraction.

Where you meet them
n-gram features are a one-line change in most text pipelines:

  • The ngram_range setting of scikit-learn's CountVectorizer and TfidfVectorizer, which adds phrases alongside single words.
  • A spam filter that only sharpens once “click here” and “wire transfer” are single clues rather than four loose words.
  • Character n-grams for language identification, fuzzy name matching and authorship attribution, where they survive misspellings that word features do not.
  • Keyword search, where indexing bigrams keeps “New York” distinct from a page mentioning both words paragraphs apart.

Why it matters
n-grams are how local word order reaches a model that has no notion of sequence, and they also show where counting runs out. Raising n captures more context and simultaneously guarantees that most of what you capture never occurred in training — the pressure that leads to frequency pruning, hashed features, or abandoning counts for embeddings.

An n-gram is a contiguous sequence of n items — usually words, sometimes characters — drawn from a text: “heating down” is a bigram. Used as features, n-grams let a count- or frequency-based representation keep some of the local word order that a plain bag of words discards, so “not good” stays distinguishable from “good”. The cost is a feature space that grows sharply with n and becomes extremely sparse, which is why most systems stop at bigrams or trigrams.

Imagine describing a song by listing the notes it contains, with nothing about the order. You would struggle to tell two very different tunes apart. Counting single words in a sentence has the same blind spot: “not happy” and “happy” end up looking much alike.

An n-gram is just a short run of words taken side by side — two or three at a time instead of one. Counting those little runs lets software notice “not happy” or “click here” as single clues. It is a small trick, and it is much of the reason a spam filter built on word counting works as well as it does.