Code-Switching and Mixed-Language Text › Language Identification on Mixed Text

Michael BrenndoerferNovember 26, 202615 min read
Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 188Code-Switching and Mixed-Language Text › Language Identification on Mixed Text
Reading section 4 of 13 · Language Identification on Mixed Text · 15 minSection 4 of 13 · 15 min

Section 4 of 13 · 15 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Language identification means assigning a label to a specified unit of text. Check the unit supported by the identifier and the unit required by the consumer. A whole-text label and a token sequence answer different questions.

A high whole-text score identifies a preferred class among that model’s labels. Check the token or span output separately before inferring where a boundary occurs.

The examples run in the locked book environment. The language identification calculations use Python and small offline fixtures. The tokenizer experiment later trains two miniature vocabularies with the installed tokenizers package.

We will work with hand-written mixed-language examples to exercise the pipeline choices. They are illustrative fixtures, with no estimate of how often these constructions occur.

PythonIn [3]
CollapseExpand
examples = [
    ("Hinglish", "Yaar I am not coming to the party tonight, mujhe kaam hai."),
    (
        "Spanglish",
        "Voy al grocery store para comprar leche y huevos, pero no tengo cash.",
    ),
    (
        "Franglais",
        "J'ai envoyé le email à mon boss hier, mais il n'a pas répondu.",
    ),
    (
        "Taglish",
        "I'll go to the mall later, pero kailangan ko muna magpaalam kay nanay.",
    ),
    ("Mandarin-English", "我明天有 meeting at 3pm, 然后 we can grab dinner."),
    (
        "Arabic-English",
        "Ana going to the meeting at 3pm, بس الملف لسه مش جاهز.",
    ),
]

Comparing whole-string language labels

The langdetect Python package and Lui and Baldwin's langid.py illustrate off-the-shelf single-label interfaces.

A list of alternate language hypotheses for a whole input does not identify which words belong to which language. Their scores also require checking the API conventions before interpreting them, and a normalized score alone does not establish calibration.

The executable comparison uses two small baselines to expose this design choice without model downloads. They share a fixed language inventory and use separate monolingual profile sentences. The first counts exact matches to a profile's words. The second compares within-word character trigrams by cosine similarity, which permits partial matches. Their scores have different units, so we compare their labels and plot the number of examples assigned to each language. This fixture case-folds words and maps the typographic apostrophe U+2019 to ASCII U+0027 for matching. An apostrophe is kept inside a word when letters appear on both sides.

PythonIn [4]
CollapseExpand
profile_texts = {
    "en": "I will call the team this evening and ask them to share a report.",
    "hi": "Yaar mujhe kal bazaar jaana hai aur kaam khatam karna hai.",
    "es": "Voy a la tienda para comprar pan y queso, pero no tengo dinero.",
    "fr": "J'ai envoyé un message à mon collègue, mais il n'a pas répondu.",
    "tl": "Mamaya ako pupunta sa palengke pero kailangan ko munang magpaalam sa nanay.",
    "zh": "我明天要出门,然后我们一起吃晚饭。",
    "ar": "بس الاجتماع خلص والملف لسه مش مكتوب.",
}


def words(text):
    normalized = text.casefold().replace("’", "'")
    return regex.findall(
        r"\p{L}[\p{L}\p{M}]*(?:'\p{L}[\p{L}\p{M}]*)*", normalized
    )


assert words("J'ai") == words("J’ai") == ["j'ai"]
assert words("’bonjour’ l’été") == ["bonjour", "l'été"]


def trigrams(word_list):
    counts = Counter()
    for word in word_list:
        padded = f"^{word}$"
        counts.update(padded[i : i + 3] for i in range(len(padded) - 2))
    return counts


word_profiles = {lang: set(words(text)) for lang, text in profile_texts.items()}
trigram_profiles = {
    lang: trigrams(words(text)) for lang, text in profile_texts.items()
}


def pick_language(scores):
    top = max(scores.values())
    winners = [lang for lang, score in scores.items() if score == top]
    return winners[0] if top > 0 and len(winners) == 1 else "unk"


def word_lid(text):
    return pick_language(
        {
            lang: sum(word in profile for word in words(text))
            for lang, profile in word_profiles.items()
        }
    )


def trigram_lid(text):
    query = trigrams(words(text))
    query_norm = math.sqrt(sum(count**2 for count in query.values()))
    scores = {}
    for lang, profile in trigram_profiles.items():
        profile_norm = math.sqrt(sum(count**2 for count in profile.values()))
        numerator = sum(count * profile[tri] for tri, count in query.items())
        denominator = query_norm * profile_norm
        scores[lang] = numerator / denominator if denominator else 0.0
    return pick_language(scores)


rows = [(name, word_lid(text), trigram_lid(text)) for name, text in examples]
predicted_languages = sorted({label for _, a, b in rows for label in (a, b)})
language_positions = np.arange(len(predicted_languages))
word_assignments = Counter(a for _, a, _ in rows)
trigram_assignments = Counter(b for _, _, b in rows)
word_counts = [word_assignments[lang] for lang in predicted_languages]
trigram_counts = [trigram_assignments[lang] for lang in predicted_languages]
ConsoleOut [5]
CollapseExpand
Hinglish           exact words:  hi  trigrams:  hi
Spanglish          exact words:  es  trigrams:  es
Franglais          exact words:  fr  trigrams:  fr
Taglish            exact words:  tl  trigrams:  tl
Mandarin-English   exact words: unk  trigrams:  zh
Arabic-English     exact words:  ar  trigrams:  ar

The two baselines agree on five of the six examples. On the Mandarin–English example, the exact-word baseline abstains (unk), and the trigram baseline returns zh.

The table reports whole-string labels, which you can use to compare the baselines' decisions on these fixtures.

VisualizationOut [6]
CollapseExpand
Grouped bars show matching counts for five language labels. The exact-word baseline has one `unk` result, and the trigram baseline has one `zh` result.
Counts of whole-string labels for six hand-written examples. The exact-word baseline abstains on one input, shown as `unk`, and the trigram baseline labels that input `zh`.

An English-only index can mishandle the non-English content if routing commits to a whole-string English label. Log the evidence used to make that routing decision.

If a classifier produces scores, test how they behave on monolingual and mixed inputs separately before using a threshold.

Confidence is not calibration

A single-label model scores only the labels it can return. A large score for one label does not show that the input contains only that language. Calibration is a separate property evaluated using labeled examples from the target setting.

What modern LID looks like

When you choose a language identifier, check its label inventory and the units it can label.

  • Language coverage. GlotLID-M reports 1,665 languages. OpenLID-v2 lists 200 language varieties with script-aware labels. The generic fastText lid.176 release lists 176 languages and a 917 kB compressed model. The separate IndicLID study evaluated Bhasha-Abhijnaanam on 22 Indic languages in native scripts and 21 in Latin script. Table 1 and §2.2 exclude Santali from the Latin-script test set. The paper separately reports that its romanized checkpoint does not support Dogri. Its test data are predominantly clean sentences, so use naturally mixed text from the target domain to evaluate boundaries.
  • Token-level or span-level output. A dedicated sequence labeler can return a label per token. The exercise below runs a span classifier over sliding windows and assigns its label to each window's center token. Compare both approaches on your annotated boundaries if both are available.

Choose your LID granularity based on what the downstream task needs.

Possible resolutions for language identification decisions.
Downstream taskUseful granularity
Choosing a translation directionDocument or segment
Routing to a monolingual modelSegment, with a mixed label
NER over code-switched textToken
Filtering training dataDocument, plus a mixed-tag
ASR language modelingFrame or word
Search indexingPer-field, plus script detection

Choose the granularity for each downstream decision. If a document labeled English contains substantial Devanagari text, inspect the relevant spans before routing it to an English-only index. Script composition can flag the discrepancy. It cannot identify the language of a span by itself.

Sliding-window token-level LID

Classify overlapping windows of whitespace-delimited tokens and assign each window's label to the center token. Here we reuse the exact-word baseline, shorten windows at the ends, and leave an unknown label when the word evidence is tied or absent.

PythonIn [7]
CollapseExpand
def sliding_window_lid(text, k=5):
    if k < 1 or k % 2 == 0:
        raise ValueError("Window length must be a positive odd number.")
    tokens = text.split()
    radius = k // 2
    labels = [
        word_lid(" ".join(tokens[max(0, i - radius) : i + radius + 1]))
        for i in range(len(tokens))
    ]
    return tokens, labels


tokens, pred = sliding_window_lid(examples[0][1], k=5)
ConsoleOut [8]
CollapseExpand
 0  Yaar         unk
 1  I            unk
 2  am           unk
 3  not          en
 4  coming       en
 5  to           en
 6  the          en
 7  party        en
 8  tonight,     hi
 9  mujhe        hi
10  kaam         hi
11  hai.         hi

Compare the switch-point sets below. The five-word baseline misses both gold boundaries and predicts one boundary outside the gold set.

This one sentence illustrates smoothing across boundaries, not the expected accuracy of a real classifier.

Romanized Hindi and English both use Latin characters. Check lexical and contextual evidence on held-out examples representative of the intended writing conventions.

Tag romanized text explicitly

In a catalog that tracks writing systems, language tags such as hi-Latn, ur-Latn, and ar-Latn use the Latn script subtag to record Latin-script forms explicitly. Preserve both the original text and the tagging provenance so routing decisions can be revisited.

The code-mixing index

The code-mixing index (CMI) in Das and Gambäck (2014) measures the fraction of language-assigned tokens outside the largest language category. This counts tokens by label and ignores their order.

CMI=100(1−max⁡iwin),n>0\mathrm{CMI} = 100 \left(1 - \frac{\max_i w_i}{n}\right),\qquad n>0

Here nn is the number of tokens assigned a language from the declared inventory LL. The count wiw_i is the number of those tokens in language ii. Both score helpers accept labels from LL plus the reserved labels unk and other. The latter two are excluded from the count. Fix an unrecognized label at input or explicitly map it to unk under the annotation policy before scoring. When n=0n=0, we return zero and report label coverage separately.

For two languages, an even split gives 50 and a monolingual sequence gives zero. When the majority count is fixed, growing the span adds minority-language tokens and raises CMI.

The plot shows only valid combinations for two languages, where the majority count is at least half of the span.

PythonIn [9]
CollapseExpand
hinglish_languages = frozenset({"hi", "en"})
excluded_labels = frozenset({"unk", "other"})


def check_language_labels(labels, languages):
    if not languages or languages & excluded_labels:
        raise ValueError(
            "Choose a nonempty language inventory without reserved labels."
        )
    invalid = set(labels) - languages - excluded_labels
    if invalid:
        raise ValueError(f"Unknown labels: {sorted(invalid)}")


def code_mixing_index(labels, languages):
    check_language_labels(labels, languages)
    counts = Counter(label for label in labels if label in languages)
    total = sum(counts.values())
    return 100.0 * (1 - max(counts.values()) / total) if total else 0.0


gold_hinglish = [
    "hi",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "hi",
    "hi",
    "hi",
]
assert len(tokens) == len(gold_hinglish)
cmi_curves = {}
for majority in (2, 4, 8):
    lengths = np.arange(majority, 2 * majority + 1)
    cmi_curves[majority] = (lengths, 100 * (1 - majority / lengths))
VisualizationOut [10]
CollapseExpand
Three curves rise from zero at a monolingual span to 50 at an even two-language split.
CMI at valid span lengths for three fixed majority-language counts in a two-language example. Each line ends where the two language counts are equal and CMI is 50.
ConsoleOut [11]
CollapseExpand
Gold distribution: Counter({'en': 8, 'hi': 4})
Gold CMI: 33.33
Windowed distribution: Counter({'en': 5, 'hi': 4, 'unk': 3})
Windowed CMI: 44.44
Windowed label coverage: 9/12

The gold annotation has four Hindi and eight English tokens, giving a CMI of 33.33. The window baseline assigns four Hindi and five English labels, with three unknowns. Its CMI is 44.44 at 9/12 label coverage.

Even when the two scores agree, the labels can differ at individual positions.

Switch-point detection

If you want to know where a system gets mixed-language wrong, the switch points are the right unit of analysis.

Define the set of switch points in a label sequence as

S(ℓ)={ t:2≤t≤T, ℓt,ℓt−1∈L, ℓt≠ℓt−1 }S(\ell) = \{\, t : 2 \le t \le T,\ \ell_t,\ell_{t-1} \in L,\ \ell_t \neq \ell_{t-1} \,\}

where:

  • ℓ=(ℓ1,…,ℓT)\ell = (\ell_1, \ldots, \ell_T): the sequence of language labels over TT tokens
  • ℓt\ell_t: the label assigned to token tt
  • tt: a token position from 2 through TT (position 1 has no predecessor)
  • LL: the set of language labels, excluding unknown and language-independent labels

The set contains a boundary only when both neighboring tokens carry different language labels. Unknown and language-independent labels prevent either neighboring pair from counting as a switch. Align gold and predicted labels to the same ordered token spans before comparing them. Equal lengths alone cannot verify this alignment.

P=∣Spred∩Sgold∣∣Spred∣,R=∣Spred∩Sgold∣∣Sgold∣,F1=2PRP+RP = \frac{|S_{\text{pred}} \cap S_{\text{gold}}|}{|S_{\text{pred}}|}, \quad R = \frac{|S_{\text{pred}} \cap S_{\text{gold}}|}{|S_{\text{gold}}|}, \quad F_1 = \frac{2PR}{P+R}

where:

  • SpredS_{\text{pred}}: the set of switch points detected in the predicted label sequence
  • SgoldS_{\text{gold}}: the set of switch points in the gold label sequence
  • PP: precision, the fraction of predicted switch points that are correct
  • RR: recall, the fraction of gold switch points that were predicted
  • F1F_1: the harmonic mean of precision and recall

A predicted boundary outside the gold set is a false positive, and a missed gold boundary is a false negative. The implementation uses zero for each undefined rate and prints both boundary sets so empty-boundary cases remain visible.

The equations use one-based positions and the code reports zero-based positions.

PythonIn [12]
CollapseExpand
def switch_points(labels, languages):
    check_language_labels(labels, languages)
    return {
        i
        for i, (left, right) in enumerate(zip(labels, labels[1:]), start=1)
        if left != right and left in languages and right in languages
    }


def switch_point_f1(gold, pred, languages):
    """Score label sequences already aligned to the same ordered token spans."""
    if len(gold) != len(pred):
        raise ValueError(
            "Gold and predicted labels must align to the same tokens."
        )
    g, p = switch_points(gold, languages), switch_points(pred, languages)
    tp = len(g & p)
    prec = tp / len(p) if p else 0.0
    rec = tp / len(g) if g else 0.0
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0
    return prec, rec, f1, g, p


prec, rec, f1, g_pts, p_pts = switch_point_f1(
    gold_hinglish, pred, hinglish_languages
)
for score in (code_mixing_index, switch_points):
    try:
        score(["en", "eng"], hinglish_languages)
    except ValueError as exc:
        assert str(exc) == "Unknown labels: ['eng']"
    else:
        raise AssertionError("An out-of-inventory label was accepted.")
ConsoleOut [13]
CollapseExpand
gold switch points:      [1, 9]
predicted switch points: [8]
precision=0.00  recall=0.00  F1=0.00

Switch-point F1F_1 is a much better diagnostic than sentence accuracy for code-switched LID, because it directly measures the thing you care about: does the system know where the language changes? Sentence accuracy can be at 95% on a corpus where only 5% of sentences are mixed, while the system is useless on exactly those sentences.

The gold switch points are {1, 9} and the window baseline predicts {8}, using zero-based indices. The sets do not intersect, so precision, recall, and F1F_1 are each zero. More generally, if the gold set is nonempty and every gold boundary is missed, exact switch-point F1F_1 is zero under this convention.

Let's visualize gold versus predicted labels for this sentence. The rendering is separated from the label computation so that the figure depends only on precomputed values.

VisualizationOut [14]
CollapseExpand
Two-row grid of gold and predicted per-token language labels for a Hinglish sentence.
Gold and sliding-window labels for one Hinglish sentence. Gray cells indicate that the window classifier abstained. A correct boundary requires the language change to occur at the same token index.

The two rows make the metric interpretable. The prediction at position 8 is a false positive here because 8 is outside the gold set. The missed gold boundaries at 1 and 9 are false negatives. Where either adjacent prediction is unknown, the baseline emits no boundary.

Token coverage, token-level errors, and boundary errors answer different questions, so keep all three in the evaluation report.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy