Code-Switching: Processing Mixed-Language Text
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Name the three classical switching types and the matrix language of an utterance
- 2Compute a code-mixing index and a switch-point rate from a token language sequence
- 3Build a token-level language identifier and evaluate it with F1
- 4Use GLUECoS and LinCE to size the labeled data available per task
Code-switching is the alternation of two or more languages inside one conversation, sentence, or word. For NLP it creates a pipeline problem rather than a curiosity: language identification must run per token, and every downstream model inherits its errors.
Types of Switching
Poplack (1980) distinguished three patterns that still organize the literature. Alternation switches languages at a clause boundary with no shared morphology. Insertion embeds a single lexical item from language B inside a sentence framed by language A, the classic tag switch. Congruent lexicalization fills one shared grammatical template with material from both languages, which is common when the languages are closely related.
Myers-Scotton's matrix language frame adds a prediction: one language supplies the morphosyntactic frame while the other supplies content words. The frame is usually the language of the surrounding clause, and knowing it lets a model predict which slots accept insertions.
The index and the switch rate answer different questions: a sentence can be half non-dominant and switch once, or mix at every word while switching twice as often.
Sequence Labeling View
Token-level language identification is a structured prediction problem, because neighbouring labels are strongly dependent: runs of one language dominate, so a model that smooths across neighbours beats independent per-token classification.
with emission scores from a contextual encoder and transition scores that reward staying in the same language. Synthetic data is built by drawing tokens from a mixture of two unigram distributions:
Benchmarks
GLUECoS (Khanuja et al., 2020) is the standard suite for English-Hindi and English-Spanish, and its sizes show how thin supervision is outside sentiment.
| GLUECoS pair and task | Train size | Notes |
|---|---|---|
| En-Hi Fire language ID | 3,537 | token labels for the LID task |
| En-Hi UD and FG POS | 1,814 and 2,631 | two annotation schemes |
| En-Hi IIITH NER | 3,084 | mixed-script entities |
| En-Hi SAIL sentiment | 12,601 | largest labeled set |
| En-Hi QA and NLI | 313 and 1,300 | reasoning sets |
| En-Es CALCS NER | 34,208 | largest overall |
| En-Es EMNLP and Bangor POS | 14,413 and 2,758 | Spanish side |
LinCE (Aguilar et al., 2020) organizes 11 corpora across four language pairs under one harness, and reports that multilingual BERT reaches 92.75 accuracy on POS tagging of code-switched text, edging the 91.9 accuracy of the pre-transformer state of the art on the same data. Because the dominant language is always the majority of tokens, evaluation is reported per language rather than overall:
Worked Code
import re
def tokenize(text):
return re.findall(r"[a-z']+", text.lower())
HINDI = {"kya", "hai", "nahi", "acha", "kaise", "bahut", "mera", "tum"} # demo lexicon
ENGLISH = {"the", "movie", "was", "great", "very", "good", "i", "think",
"story", "boring", "not", "but", "is"}
def tag_tokens(words):
return ["hi" if w in HINDI else ("en" if w in ENGLISH else "unk") for w in words]
def code_mixing_index(tags):
known = [t for t in tags if t != "unk"]
if not known:
return 0.0
counts = {lang: known.count(lang) for lang in set(known)}
u = len(tags) - len(known)
return (len(known) - max(counts.values())) / max(len(tags) - u, 1)
def switch_points(tags):
return sum(1 for a, b in zip(tags, tags[1:]) if a != b)
samples = ["kya movie acha hai", "the story is not good", "mera movie not boring hai"]
for s in samples:
tags = tag_tokens(tokenize(s))
sp = switch_points(tags)
rate = sp / max(len(tags) - 1, 1)
print(f"{tags} CMI={code_mixing_index(tags):.3f} SP={sp} rate={rate:.3f}")
The second program generates synthetic mixed text the way random code-mixing baselines do, then reports the mixing statistics of what it produced.
import random
LEX_A = ["the", "movie", "was", "great", "story", "boring", "very", "good"]
LEX_B = ["kya", "acha", "nahi", "hai", "bahut", "kaise", "mera"]
def sample_sentence(lam=0.6, length=8, seed=7):
rng = random.Random(seed)
words = []
for _ in range(length):
lex = LEX_A if rng.random() < lam else LEX_B
words.append(rng.choice(lex))
return words
def mixing_report(tags, dominant):
non_dom = sum(1 for t in tags if t != dominant)
sp = sum(1 for a, b in zip(tags, tags[1:]) if a != b)
return {
"dominant_share": round(1 - non_dom / len(tags), 3),
"switches": sp,
"rate": round(sp / (len(tags) - 1), 3),
}
for lam, seed in ((0.7, 7), (0.4, 2)):
words = sample_sentence(lam=lam, seed=seed)
tags = ["A" if w in LEX_A else "B" for w in words]
dominant = max(set(tags), key=tags.count)
print(f"lam={lam}", " ".join(words), mixing_report(tags, dominant))
Real-World Applications
- Social media analytics: token-level language ID tags multilingual posts before sentiment or topic models run on them.
- Search and ranking: queries such as mixed English-Hindi phrases need both lexicons, since neither alone covers the intent.
- Speech technology: code-switched ASR requires per-token language decisions to select acoustic and pronunciation models.
- Conversational assistants: the 313-example GLUECoS QA set shows how little supervised data exists for mixed-language reasoning.
đĄLabel per token, not per post
Common Mistakes
Classifying the whole message as one language
Fix: Predict a label per token and smooth with a transition model
Building synthetic data by independent coin flips
Fix: Match observed run lengths, since random mixing overproduces single-word switches
Quoting accuracy on an unbalanced mixed test set
Fix: Report F1 per language so the dominant language does not hide failures
Best Practices
- Keep token language labels as an input feature to every downstream model
- Report both a mixing index and a switch rate when describing a corpus
- Compare against multilingual BERT before building task-specific models
Key Takeaways
- Poplack's three types are alternation, insertion, and congruent lexicalization
- CMI measures share of non-dominant tokens while switch-point rate measures boundaries
- GLUECoS En-Hi sentiment has 12,601 examples but only 313 for question answering
- Multilingual BERT reaches 92.75 accuracy on LinCE POS tagging, above the 91.9 earlier system
Frequently Asked Questions
What is a matrix language?
The language that supplies the morphosyntactic frame of an utterance, while the other language contributes inserted content words. Identifying it first makes insertion points predictable for a tagger.
Is synthetic code-switching useful?
Yes, when the mixing statistics match real data. Random mixing with a fixed probability draws tokens independently, which produces far too many single-word alternations, so grammar-based generation or corpus-matched sampling is preferred.
Why does token language ID matter for sentiment?
Because a wrong label changes the input that the sentiment model sees, and because many sentiment lexicons are language specific. On GLUECoS, LID is the first task in the chain and its errors propagate to sentiment, NER, QA, and NLI.
Interview Questions
Q1: How do you measure how mixed a corpus is?
Report the code-mixing index, share of non-dominant tokens, alongside the switch-point rate
Q2: What makes token LID hard?
Short runs, borrowed words, and shared cognates, plus very little labeled data outside the Fire corpus
Q3: Why prefer a structured model over per-token classification?
Labels are strongly autocorrelated, so transition scores remove most isolated-token errors