Algorithmcore
Cavnar-Trenkle n-gram text categorization
Also called out-of-place measure, character n-gram rank profiles.
Identify the language of a text by comparing the rank order of its most frequent character n-grams with stored profiles under the out-of-place distance.
- Solves
- Language identification
- Time
- O(k L) compareO(n + G log G) profile
- Space
- O(G + k L) extra
- Where
- G = the number of distinct n-grams of the input; L = the profile length; k = the number of languages; n = the number of characters of the input text
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William B. Cavnar, John M. Trenkle, 1994
The Cavnar-Trenkle method identifies the language of a text by its most frequent character n-grams. It builds a ranked list, a profile, of the most frequent n-grams of length 1 to 5 for each language and for the input, and it returns the language whose profile is closest under the out-of-place distance, a sum of rank differences. It is one algorithm for the language identification problem, which is the task of choosing the language of a text; the problem page lists other methods, such as naive Bayes over n-grams. The same procedure also sorts texts by subject, which is why the paper calls it text categorization.
In plain words
Each language has letter groups that it uses a lot. English has "th" and "the", German has "sch" and "en", French has "es" and "le". Count the short letter groups in a sample of each language, and keep a list of the most common ones, from the most common down. Do the same for the text you want to identify.
Then compare the lists. For each letter group in the list of the text, see how far its place is from its place in the list of a language. Add up these distances. A group that the language list does not have adds a fixed large amount. The language with the smallest total wins.
The method only looks at the order of the lists, not at the counts, so a short text and a long sample can be compared directly.
The problem
The input is a text and, for each of languages , a profile built from training text in that language. The output is one language. A token is a maximal run of letters and apostrophes; digits, punctuation and white space separate tokens (Section 3.1 of the paper). For , a token is padded with one blank in front and blanks after it, written , so the token TEXT gives the bigrams , TE, EX, XT, and the trigrams , TEX, EXT, , , as in Section 2.0 of the paper. A token of characters gives n-grams of each length . For this page uses the letters alone.
The profile is the list of the most frequent n-grams of , from the most frequent down, with ranks . The paper gives no rule for equal counts; this page breaks ties by the n-gram string in code point order, so that the profile is a function of the text. The out-of-place distance of a document profile from a category profile is
The paper says that a missing n-gram takes "some maximum out-of-place value" and gives no number. This page uses , which is at least as large as any rank difference between two profiles of length .
The algorithm
CT-CLASSIFY(x, C, L) ▷ C maps each language to a profile of length at most L- 1
P ← PROFILE(x, L) - 2
best ← none, d* ← ∞ - 3
for each language c of C, in sorted order do - 4
d ← 0 - 5
for r ← 0 to |P| - 1 do - 6
if P[r] has the rank r' in C[c] then d ← d + |r - r'| - 7
else d ← d + L ▷ the maximum out-of-place penalty - 8
if d < d* then best ← c, d* ← d - 9
return best PROFILE(x, L)- 10
count ← empty map - 11
for each token w of x do - 12
for n ← 1 to 5 do - 13
u ← w if n = 1, else "_" + w + "_" repeated n - 1 times - 14
for each window g of length n in u do count[g] ← count[g] + 1 - 15
sort the keys of count by decreasing count, and equal counts by the string - 16
return the first L keys
Training is PROFILE on the sample text of each language. Line L6 needs the rank of an n-gram in a category profile, so each category profile is stored with a hash map from n-gram to rank. Line L8 uses a strict comparison, so on equal distances the first language in sorted order wins.
Example
Three training texts of about 150 characters each, all lower case:
- en: "the cat and the dog are in the house. the children play with the ball in the garden. this is the end of the story and the start of the next one."
- fr: "le chat et le chien sont dans la maison. les enfants jouent avec la balle dans le jardin. ceci est la fin de l histoire et le debut de la suivante."
- de: "die katze und der hund sind in dem haus. die kinder spielen mit dem ball in dem garten. das ist das ende der geschichte und der anfang der naechsten."
With , the profiles are the following, with the counts in brackets:
- en: e (17), t (17), h (14), e_ (13), e__ (13), e___ (13)
- fr: e (19), a (13), l (12), n (11), _l (10), t (10)
- de: e (20), d (17), n (14), _d (11), i (10), a (9)
In the English profile, e and t have the same count and e comes first by the tie rule. The input "the house" has the profile e, e_, e__, e___, e____, h, each with count 2. The trailing blanks come from the padding: both words end in e, and both contain h. The table gives the cost of each n-gram for each language.
| n-gram | rank in en | cost en | cost fr | cost de | |
|---|---|---|---|---|---|
| 0 | e | 0 | 0 | 0 | 0 |
| 1 | e_ | 3 | 2 | 6 | 6 |
| 2 | e__ | 4 | 2 | 6 | 6 |
| 3 | e___ | 5 | 2 | 6 | 6 |
| 4 | e____ | missing | 6 | 6 | 6 |
| 5 | h | 2 | 3 | 6 | 6 |
| sum | 15 | 30 | 30 |
So CT-CLASSIFY returns en. With the default , the same three profiles also give the right language for "the end of the day", "in the garden", "la fin du jour", "dans la maison", "das ende des tages", "und der hund" and "in dem garten". The tests of the implementation check all these numbers.
Correctness
The proof in proofs/correctness.md shows that lines L10 to L14 count each padded n-gram once for each window, that lines L15 and L16 return the first n-grams in a strict total order, so the profile is well defined, and that lines L4 to L7 compute the sum in the definition. An induction over the loop of line L3 shows that best is the first language in sorted order with the least distance. This is a statement about the rule, not about the true language: the method is a heuristic classifier, and its accuracy is a measurement.
Proof: The Cavnar-Trenkle classifier returns the language with the least out-of-place distancefull
Fix the profile length and the largest n-gram length 5. A token is a maximal run of letters and apostrophes. For a token and , let if and otherwise, where is a symbol that is not a letter. The count of a string of length in a text is the number of pairs (token occurrence of , position ) with . Order strings by when , or and comes before in code point order. This is a strict total order on the strings with . The profile is the list of the first strings in this order, where is the number of strings with . For a list and a list without repeats, let be the 0-based position of in , and let
Lemma 1. After lines L10 to L14, count for every , and a missing key means .
Proof. The loops of lines L11, L12 and L14 visit each triple (token occurrence , length , start ) with exactly once, and line L14 adds 1 to the key . A string of length can only equal an n-gram of length , so count is the number of triples whose n-gram is , which is .
Lemma 2. For a token of characters and , has exactly n-grams. For it has .
Proof. , and a string of length has windows of length . For , has windows.
Lemma 3. Lines L15 and L16 return .
Proof. The sort key orders the keys first by decreasing count and then by the string. By Lemma 1 the keys are exactly the strings with and the counts are , so the sorted list is these strings in the order . Line L16 keeps the first of them, or all of them if there are fewer.
Lemma 4. For a document profile and a category profile , lines L4 to L7 compute .
Proof. The loop of line L5 visits once each. The profile has no repeats, so is well defined. Line L6 adds the first case of the sum when , and line L7 adds otherwise. After the last pass, is the full sum.
Theorem. CT-CLASSIFY stops and returns the language with the least . If several languages share the least distance, it returns the first of them in sorted order.
Proof. All loops run over finite lists, so the procedure stops. By Lemma 3, line L1 sets . Line L3 visits the languages in sorted order . We show by induction on that after the pass for , is and best is the first , , that reaches it. For , before the pass, so line L8 sets best to and to its distance, by Lemma 4. For , line L8 replaces best only when the new distance is strictly smaller than . If it is smaller, is the only language with that reaches the new minimum. If it is equal or larger, the minimum and the first language that reaches it do not change. After the pass for , line L9 returns the claimed language.
Remarks. The distance is not symmetric, and it is not a metric: holds exactly when is a prefix of , because each term is 0 only when . When and , each term is at most , because two ranks below differ by less than , so .
Complexity
- Profile. A token of characters gives at most windows, so lines L11 to L14 make map updates for a text of characters, and the map holds keys. The sort of line L15 takes comparisons; a selection of the top keys with a heap (top-k selection) takes .
- Comparison. With a rank map per language, each of the languages costs , so lines L3 to L8 take time.
- Space. for the counts of the input and for the stored profiles. With and 8 languages, the model is 2400 n-grams.
Properties
- Rank based. Only the order of the profile matters, not the counts. This makes a short input comparable with a long training text, but it throws away how much more frequent one n-gram is than the next.
- Not a metric. exactly when is a prefix of , and and can differ. Without missing n-grams, the sum of is Spearman's footrule between the two rankings, which is related to Spearman's rank correlation; Jauhiainen et al. (2019) make the same link.
- Bounded. With profiles of length , the distance lies between 0 and .
- Robust to small errors. A typing error changes a few n-grams of one word, so it moves a few terms of the sum. The paper names this tolerance as a design goal.
- Deterministic. With the tie rules of lines L8 and L15, the result is a function of the input and the training texts.
Variants and improvements
- Probabilistic models. A naive Bayes classifier or a character n-gram language model per language uses the counts, not only the ranks. Tools such as langid.py (Lui and Baldwin 2012) use a multinomial naive Bayes model over selected byte n-grams.
- Other distances. The survey of Jauhiainen et al. (2019) lists many other distances and classifiers that replace the out-of-place measure, for example the cosine similarity of n-gram count vectors.
- Profile length. Cavnar and Trenkle tested profiles of 100, 200, 300 and 400 n-grams. In their test the accuracy rose from 100 to 300 and changed little from 300 to 400. They write that the top 300 or so n-grams depend mostly on the language and that there is nothing special about rank 300 itself. So 300 is a rule of thumb from their data, not a derived constant.
- Case folding and normalization. The paper does not say whether it folds case. Folding both the training text and the input, and normalizing the Unicode form, removes differences that say nothing about the language.
When to use it
Use it as a small, transparent baseline: it needs a few kilobytes of training text per language, no tuning beyond , and its decision can be explained with a table like the one above. For short inputs, such as a tweet or a search query, the input has only a few dozen distinct n-grams, so the decision rests on little evidence. Baldwin and Lui (2010) study how the accuracy of several methods, this one included, changes with the length of the document and the number of languages. For a production system, compare it on your own data with a probabilistic model.
Pitfalls
- A profile that is too short. With the training texts of the example and , the input "the end of the day" gets the distances 46 (en), 40 (fr) and 52 (de), so line L9 returns fr. The test of the implementation shows that from 4 to 10 gives a wrong language, and from 11 to 20 gives en. The fix is a larger in lines L1 and L16, not a change of the penalty.
- A penalty that is too small. If line L7 adds less than the largest possible rank difference, a profile that shares few n-grams with the input can beat a profile that shares many n-grams at slightly different ranks. Use a penalty of at least .
- No tie rule. Many n-grams have the same count, as in the example, where all six n-grams of "the house" have count 2. Without the tie rule of line L15, the profile, and so the answer, depends on the order of a hash map.
- Different preprocessing for training and input. If line L11 tokenizes or folds case one way at training time and another way at test time, the profiles do not match. Use the same PROFILE for both.
- Closely related languages. Languages that share most frequent n-grams, such as Danish and Norwegian Bokmål, or Croatian and Serbian in Latin script, are hard for every method, because their profiles share most of their top ranks. Train on texts that show the differences, and check the confusion between such pairs on held-out data.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cavnar-trenkle-language-identification/. The authors are listed in prov/2S4GCR.jsonl.
"""Language identification by Cavnar-Trenkle n-gram rank profiles.
A profile is the list of the most frequent character n-grams of a text, for
n = 1 to 5, in decreasing order of count. Ties in the count go to the smaller
string (the paper gives no tie rule). Tokens are maximal runs of letters and
apostrophes; digits, punctuation and spaces separate tokens. For n >= 2 a token
w is padded as "_" + w + "_" * (n - 1), as in the paper, so a token of k
characters gives k + 1 n-grams of each length n >= 2. For n = 1 the letters
alone are used (k unigrams); this is a convention of this file. Case is kept.
The out-of-place distance adds |r - r'| for each n-gram at rank r in the
document profile and rank r' in the category profile, and a fixed maximum
penalty for an n-gram that is missing from the category profile. The paper
gives no value for the penalty; this file uses the profile length L.
"""
import re
from typing import Dict, List, Mapping, Optional, Sequence
TOKEN = re.compile(r"(?:[^\W\d_]|')+")
MAX_N = 5
def tokens(text: str) -> List[str]:
"""Return the maximal runs of letters and apostrophes in text."""
return TOKEN.findall(text)
def ngram_counts(text: str, max_n: int = MAX_N) -> Dict[str, int]:
"""Return the count of each padded character n-gram of text, for n = 1 to max_n.
Cost: O(max_n * len(text)) dictionary updates.
"""
count: Dict[str, int] = {} # @line L10
for w in tokens(text): # @line L11
for n in range(1, max_n + 1): # @line L12
u = w if n == 1 else "_" + w + "_" * (n - 1) # @line L13
for i in range(len(u) - n + 1): # @line L14
g = u[i : i + n]
count[g] = count.get(g, 0) + 1
return count
def profile(text: str, size: int = 300, max_n: int = MAX_N) -> List[str]:
"""Return the size most frequent n-grams of text, highest count first.
Ties in the count go to the smaller string. Cost: O(max_n * len(text))
for the counts and O(G log G) for the sort of the G distinct n-grams.
"""
count = ngram_counts(text, max_n)
ranked = sorted(count, key=lambda g: (-count[g], g)) # @line L15
return ranked[:size] # @line L16
def out_of_place(doc: Sequence[str], cat: Sequence[str], penalty: Optional[int] = None) -> int:
"""Return the out-of-place distance of the document profile doc from the category profile cat.
penalty is the cost of an n-gram of doc that is not in cat; the default
is len(cat). Cost: O(len(doc) + len(cat)) with a hash map of the ranks.
"""
if penalty is None:
penalty = len(cat)
rank = {g: r for r, g in enumerate(cat)}
d = 0 # @line L4
for r, g in enumerate(doc): # @line L5
if g in rank: # @line L6
d += abs(r - rank[g])
else: # @line L7
d += penalty
return d
def train(samples: Mapping[str, str], size: int = 300) -> Dict[str, List[str]]:
"""Return a profile of length at most size for each language from its training text."""
return {lang: profile(text, size) for lang, text in samples.items()}
def classify(text: str, profiles: Mapping[str, Sequence[str]], size: int = 300) -> str:
"""Return the language whose profile is closest to the profile of text.
The penalty for a missing n-gram is size. Ties in the distance go to the
language that comes first in sorted order. Cost: O(len(text)) plus
O(G log G) for the document profile and O(k size) for k languages.
"""
if not profiles:
raise ValueError("no language profiles")
p = profile(text, size) # @line L1
best, best_d = None, None # @line L2
for lang in sorted(profiles): # @line L3
d = out_of_place(p, profiles[lang], size)
if best_d is None or d < best_d: # @line L8
best, best_d = lang, d
return best # @line L9
def distances(text: str, profiles: Mapping[str, Sequence[str]], size: int = 300) -> Dict[str, int]:
"""Return the out-of-place distance of text from each language profile."""
p = profile(text, size)
return {lang: out_of_place(p, cat, size) for lang, cat in profiles.items()}
test_cavnar_trenkle_language_identification.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cavnar-trenkle-language-identification/. The authors are listed in prov/2S4GCR.jsonl.
import random
import pytest
from cavnar_trenkle_language_identification import (
classify,
distances,
ngram_counts,
out_of_place,
profile,
tokens,
train,
)
SAMPLES = {
"en": "the cat and the dog are in the house. the children play with the ball in the garden. "
"this is the end of the story and the start of the next one.",
"fr": "le chat et le chien sont dans la maison. les enfants jouent avec la balle dans le jardin. "
"ceci est la fin de l histoire et le debut de la suivante.",
"de": "die katze und der hund sind in dem haus. die kinder spielen mit dem ball in dem garten. "
"das ist das ende der geschichte und der anfang der naechsten.",
}
def slow_counts(text, max_n=5):
"""Count n-grams by scanning characters by hand, with the same token and padding rules."""
words, cur = [], ""
for ch in text + " ":
if ch.isalpha() or ch == "'":
cur += ch
else:
if cur:
words.append(cur)
cur = ""
out = {}
for w in words:
for n in range(1, max_n + 1):
u = w if n == 1 else "_" + w + "_" * (n - 1)
for i in range(len(u) - n + 1):
out[u[i : i + n]] = out.get(u[i : i + n], 0) + 1
return out
def slow_distance(doc, cat, penalty):
total = 0
for r, g in enumerate(doc):
total += abs(r - list(cat).index(g)) if g in cat else penalty
return total
def test_paper_padding_of_text():
c = ngram_counts("TEXT")
two = sorted(g for g in c if len(g) == 2)
three = sorted(g for g in c if len(g) == 3)
four = sorted(g for g in c if len(g) == 4)
assert two == sorted(["_T", "TE", "EX", "XT", "T_"])
assert three == sorted(["_TE", "TEX", "EXT", "XT_", "T__"])
assert four == sorted(["_TEX", "TEXT", "EXT_", "XT__", "T___"])
assert all(sum(v for g, v in c.items() if len(g) == n) == 5 for n in range(2, 6))
assert sum(v for g, v in c.items() if len(g) == 1) == 4
def test_paper_out_of_place_example():
doc = ["TH", "ER", "ING", "ON", "ED"]
cat = ["TH", "ER", "ON", "LE", "ED", "ING", "AND"]
contrib = [0, 0, 3, 1, 0]
assert out_of_place(doc, cat, penalty=7) == sum(contrib)
assert out_of_place(["XX"], cat, penalty=7) == 7
def test_tokens():
assert tokens("Don't stop: 42 times, ok?") == ["Don't", "stop", "times", "ok"]
assert tokens("12 3.4 ,,") == []
def test_page_example_profile_length_six():
p = train(SAMPLES, 6)
assert p["en"] == ["e", "t", "h", "e_", "e__", "e___"]
assert p["fr"] == ["e", "a", "l", "n", "_l", "t"]
assert p["de"] == ["e", "d", "n", "_d", "i", "a"]
assert profile("the house", 6) == ["e", "e_", "e__", "e___", "e____", "h"]
assert distances("the house", p, 6) == {"en": 15, "fr": 30, "de": 30}
assert classify("the house", p, 6) == "en"
def test_short_profiles_fail_long_profiles_work():
text = "the end of the day"
assert classify(text, train(SAMPLES, 8), 8) == "fr"
assert distances(text, train(SAMPLES, 8), 8) == {"en": 46, "fr": 40, "de": 52}
assert all(classify(text, train(SAMPLES, L), L) == "en" for L in range(11, 21))
def test_classify_with_default_size():
p = train(SAMPLES)
cases = {
"the end of the day": "en", "in the garden": "en", "the house": "en",
"la fin du jour": "fr", "dans la maison": "fr",
"das ende des tages": "de", "und der hund": "de", "in dem garten": "de",
}
for text, lang in cases.items():
assert classify(text, p) == lang
def test_edge_cases():
p = train(SAMPLES, 10)
assert profile("", 10) == []
assert distances("123 !!", p, 10) == {"en": 0, "fr": 0, "de": 0}
assert classify("123 !!", p, 10) == "de"
with pytest.raises(ValueError):
classify("abc", {})
assert out_of_place(p["en"], p["en"]) == 0
def test_random_against_slow_versions():
rng = random.Random(1994)
letters = "abcde'"
for _ in range(500):
text = "".join(rng.choice(letters + " .1") for _ in range(rng.randint(0, 30)))
size = rng.randint(1, 12)
c = ngram_counts(text)
assert c == slow_counts(text)
p = profile(text, size)
assert len(p) == min(size, len(c))
for a, b in zip(p, p[1:]):
assert c[a] > c[b] or (c[a] == c[b] and a < b)
if len(c) > size:
assert c[p[-1]] >= max(c[g] for g in c if g not in p)
cats = {
name: profile("".join(rng.choice(letters + " ") for _ in range(40)), size)
for name in ("x", "y", "z")
}
ds = {name: slow_distance(p, cat, size) for name, cat in cats.items()}
assert distances(text, cats, size) == ds
best = min(sorted(ds), key=lambda name: ds[name])
assert classify(text, cats, size) == best
assert all(0 <= d <= size * len(p) for d in ds.values())
History
Cavnar and Trenkle presented the method at the Third Annual Symposium on Document Analysis and Information Retrieval in 1994. Their language test used 3478 Usenet articles in 8 languages (English, Portuguese, French, German, Italian, Spanish, Dutch and Polish), with training samples of 20K to 120K bytes. With profiles of 300 n-grams, they report 98.6% correct classification for articles of at most 300 bytes and 99.8% for longer articles; with 100 n-grams, the numbers were 92.9% and 97.2% (Table 2). A second test sorted articles from computer newsgroups by subject, with up to 80% correct. Later work replaced the rank distance with probabilistic models, but the method remains a common reference point in language identification surveys.
References
- William B. Cavnar and John M. Trenkle, N-gram-based text categorization, SDAIR-94, Section 2.0 (the padded n-grams), Section 3.1 (the profiles and the remarks on rank 300), Section 3.2 and Figure 3 (the out-of-place measure), Section 4 and Table 2 (the language test on 3478 articles)
- Tommi Jauhiainen, Marco Lui, Marcos Zampieri, Timothy Baldwin and Krister Lindén, Automatic language identification in texts, a survey, Journal of Artificial Intelligence Research 65, 2019, pages 675 to 782 (the section on the out-of-place method and its relation to rank statistics)
- Timothy Baldwin and Marco Lui, Language identification, the long and the short of the matter, NAACL HLT 2010, the comparison of the out-of-place method with other classifiers on short and long documents
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2S4GCR Edit this page History Report an error Markdown