Skip to main content
N-gram models capture the likelihood of word sequences, enabling detection of “real-word errors” where a correctly spelled word is used incorrectly in context.

Overview

N-gram models capture the likelihood of word sequences, enabling detection of “real-word errors”: correctly spelled words used incorrectly in context.

How It Works

Bigram Model (2-gram)

Calculates the probability of word pairs:

Trigram Model (3-gram)

Extends to word triplets for richer context:

4-gram and 5-gram Models

Higher-order N-grams provide deeper context for detecting errors in longer phrases:
These are stored in fourgrams and fivegrams database tables and configured via fourgram_threshold and fivegram_threshold in NgramContextConfig (both default to 0.0001). The context checker uses backoff: if a 5-gram probability is available it takes precedence, falling back to 4-gram, trigram, then bigram.

Smoothing Strategies

The library supports multiple smoothing strategies for handling unseen N-grams:

Stupid Backoff (Default)

Fast and effective for most use cases:

Add-K (Laplace) Smoothing

Adds constant k to all counts:

No Smoothing

Returns raw probabilities (for pre-smoothed data):

Configuration

When using SpellCheckerConfig (recommended), NgramContextConfig is created automatically from your config and passed to the checker. The values shown above are the defaults. Individual threshold parameters are not accepted as constructor kwargs; they must go through NgramContextConfig.

Error Detection

The checker uses a two-path detection strategy based on raw trigram availability:
  1. Trigram path: When a raw trigram probability exists in the corpus (P_raw(w3|w1,w2) > 0), the checker uses the trigram-specific threshold (trigram_threshold, default 0.0001) to determine if the word is an error. This avoids false positives from smoothed backoff values.
  2. Bigram fallback path: When no raw trigram is found, the checker falls back to bigram probabilities with bidirectional context checking, unigram backoff for common words, and typo neighbor detection via SymSpell.
This design ensures that smoothed backoff values (which are always > 0) do not gate the checker into the trigram path, keeping the bigram heuristics reachable.

Suggestion Generation

Suggestions are generated by:
  1. Finding words with higher conditional probability
  2. Filtering by edit distance (max 2)
  3. Ranking by combined probability and distance score

Performance

Database Schema

N-gram data is stored in SQLite using INTEGER foreign keys referencing the words table (not TEXT columns):
To query bigrams for a specific word, use a JOIN:

NgramContextChecker Methods

See Also