Low-Resource and Endangered Languages › Code Implementation
Language AI HandbookAll chapters We now build the three pieces that are most useful to have working code for: a script converter, an active learning loop, and a confidence interval calculation. The examples use real scripts and a synthetic language, because the point is the machinery rather than the specific number.
Setup
Transliteration: Syllabics to Latin
Qaniujaaqpait is a syllabics convention used in Nunavut. The example uses a subset of its glyphs, including independent vowels, consonant-vowel syllables, and final consonant signs. Each listed glyph has a single Latin mapping in this table. The fixture uses the eastern s readings and Roman double vowels where the table lists long vowels. The full regional conventions require coverage beyond this subset. Inuit Tapiriit Kanatami, Inuit Cultural Institute chart.
PythonIn [7]Expand
SYLLABICS = {
# independent vowels
"ᐃ": "i",
"ᐅ": "u",
"ᐊ": "a",
"ᐄ": "ii",
"ᐆ": "uu",
"ᐋ": "aa",
# p, t, k series
"ᐱ": "pi",
"ᐳ": "pu",
"ᐸ": "pa",
"ᑎ": "ti",
"ᑐ": "tu",
"ᑕ": "ta",
"ᑭ": "ki",
"ᑯ": "ku",
"ᑲ": "ka",
# m, n, s series
"ᒥ": "mi",
"ᒧ": "mu",
"ᒪ": "ma",
"ᓂ": "ni",
"ᓄ": "nu",
"ᓇ": "na",
"ᓯ": "si",
"ᓱ": "su",
"ᓴ": "sa",
# l, v series
"ᓕ": "li",
"ᓗ": "lu",
"ᓚ": "la",
"ᕕ": "vi",
"ᕗ": "vu",
"ᕙ": "va",
# final consonants
"ᑦ": "t",
"ᒃ": "k",
"ᓐ": "n",
"ᒻ": "m",
"ᔅ": "s",
"ᓪ": "l",
}The converter walks the string one character at a time and appends the mapped value. Unknown characters are passed through unchanged so that punctuation and whitespace survive.
PythonIn [8]Expand
def to_latin(text, table=SYLLABICS):
"""Greedy left-to-right transliteration from syllabics to Latin."""
out = []
for ch in text:
out.append(table.get(ch, ch))
return "".join(out)We can check it against three words whose Latin forms are well established.
PythonIn [9]Expand
sample_words = ["ᓄᓇᕗᑦ", "ᐃᓄᒃᑎᑐᑦ", "ᑲᓇᑕ"]
transliterated = [(w, to_latin(w)) for w in sample_words]ConsoleOut [10]Expand
ᓄᓇᕗᑦ -> nunavut ᐃᓄᒃᑎᑐᑦ -> inuktitut ᑲᓇᑕ -> kanata
For the covered glyphs, the forward mapping assigns one Latin string to each glyph. A mechanical inverse can segment kanata as three consonant-vowel syllables or split one or more of those syllables into separate consonant and vowel signs. Under the example constraint that a consonant followed by its syllable vowel uses a consonant-vowel glyph, only ka-na-ta remains. An inverse converter should encode the target orthography's rules before treating multiple raw segmentations as equally likely.
Regional conventions differ across the syllabics block, so a real system must select the table for the variety it is reading rather than assuming one mapping.
Normalisation: Diacritics and Lost Information
Arabic generally writes consonants and long vowels. Short-vowel marks occur in sources such as dictionaries and learner texts and are often omitted in everyday text. This example removes a defined subset of Arabic marks and shows which readings collapse.
PythonIn [11]Expand
import re
ARABIC_DIACRITICS = re.compile(r"[\u064B-\u0652\u0670]")
def strip_diacritics(text):
return ARABIC_DIACRITICS.sub("", text)
vocalised = {
"كَتَبَ": ("kataba", "he wrote"),
"كُتِبَ": ("kutiba", "it was written"),
"كُتُب": ("kutub", "books"),
}
rows = [
(ar, strip_diacritics(ar), rom, gloss)
for ar, (rom, gloss) in vocalised.items()
]ConsoleOut [12]Expand
كَتَبَ skeleton=كتب romanisation=kataba (he wrote) كُتِبَ skeleton=كتب romanisation=kutiba (it was written) كُتُب skeleton=كتب romanisation=kutub (books) Distinct written forms after stripping: 1 (from 3 words)
Three words collapse into one written form. To recover a vocalised reading from the skeleton, a system needs information beyond a plain lookup. It can rank candidates using context or return multiple readings when context is insufficient. In this within-script normalization, removing marks gives one predictable skeleton. Recovery is ambiguous because the operation merges distinct inputs. A transliteration scheme that merges distinct inputs can have the same problem.
A Synthetic Low-Resource Classification Task
The active-learning example generates a synthetic corpus with three topics. The labels and generation settings are known, so the example can compare multiple seeds over the same data split without using community records.
PythonIn [13]Expand
TOPICS = ["fishing", "weather", "kinship"]
TOPIC_WORDS = {
"fishing": [
"zabu",
"kivo",
"druma",
"pelto",
"nagri",
"sumbo",
"tarik",
"vela",
"qosha",
"miren",
"baktu",
"lomi",
"feru",
"gantu",
"shavi",
"ondre",
],
"weather": [
"plumo",
"kesta",
"varun",
"dolzi",
"hepra",
"nisko",
"tulga",
"bresh",
"yonda",
"krimu",
"salvo",
"pentu",
"mokra",
"zefir",
"gusta",
"lanka",
],
"kinship": [
"nembo",
"sardi",
"kundo",
"talvi",
"oshka",
"virem",
"dunai",
"pasho",
"grela",
"mintu",
"korsa",
"zenda",
"tupai",
"vesna",
"hurda",
"amlen",
],
}
SHARED_WORDS = [
"pa",
"te",
"no",
"ki",
"sa",
"mu",
"lo",
"ro",
"hi",
"wa",
"ze",
"di",
"ka",
"po",
"ni",
"su",
"ma",
"ta",
"ke",
"vo",
"li",
"nu",
"se",
"to",
]Each sentence draws a mix of topic-specific and shared words. The shared words carry no signal, so the classifier has to find the topic words, which requires seeing enough examples to encounter them.
PythonIn [14]Expand
def make_sentence(topic, rng, min_len=4, max_len=7, topic_prob=0.4):
n = int(rng.integers(min_len, max_len + 1))
words = []
for _ in range(n):
if rng.random() < topic_prob:
pool = TOPIC_WORDS[topic]
else:
pool = SHARED_WORDS
words.append(pool[int(rng.integers(0, len(pool)))])
return " ".join(words)We generate 900 sentences and hold out the first 300 as a fixed test set. The remaining 600 form the unlabeled pool from which active learning draws.
PythonIn [15]Expand
label_encoder = {t: i for i, t in enumerate(TOPICS)}
gen = np.random.default_rng(7)
TEXTS, LABELS = [], []
for _ in range(900):
t = TOPICS[int(gen.integers(0, len(TOPICS)))]
TEXTS.append(make_sentence(t, gen))
LABELS.append(t)
TEST_IDX = list(range(300))
POOL_IDX = list(range(300, 900))PythonIn [16]Expand
from collections import Counter
counts = Counter(LABELS[i] for i in TEST_IDX)ConsoleOut [17]Expand
Example sentence: po tupai oshka vesna ki vo
Test set composition: {'kinship': 122, 'weather': 96, 'fishing': 82}Word-level TF-IDF with logistic regression is a lightweight baseline that lets us rerun the experiment across seeds. The uncertainty functions use its predicted probabilities. This example does not measure their calibration.
PythonIn [18]Expand
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
def train_model(texts, labels):
"""Word-level TF-IDF followed by a linear classifier."""
model = make_pipeline(
TfidfVectorizer(
token_pattern=r"\S+", lowercase=False, sublinear_tf=True
),
LogisticRegression(max_iter=1000),
)
model.fit(texts, labels)
return modelThe tokenizer uses token_pattern=r"\S+" to keep each whitespace-delimited token. The scikit-learn default already keeps all 24 shared tokens here because each has two letters. The default can discard single-character words and split at punctuation, which is worth testing when you replace the synthetic corpus.
Acquisition Functions
Two scoring functions are enough to see the difference between strategies. The least-confidence score and the entropy score correspond directly to the formulas given in the Acquisition Functions section above.
PythonIn [19]Expand
def least_confidence(model, texts):
"""1 minus the probability of the most likely class."""
proba = model.predict_proba(texts)
return 1.0 - proba.max(axis=1)
def entropy(model, texts):
"""Shannon entropy of the predicted class distribution."""
proba = model.predict_proba(texts)
log_proba = np.log(proba, out=np.zeros_like(proba), where=proba > 0)
return -(proba * log_proba).sum(axis=1)
SCORERS = {"least_confidence": least_confidence, "entropy": entropy}The Active Learning Loop
The loop trains, scores the pool, selects a batch, and repeats. Note the removal step: we sort selected indices in descending order before popping so that earlier removals do not shift later indices.
PythonIn [20]Expand
def run_active_learning(seed, strategy, rounds=10, batch=12, n_seed=24):
rng = np.random.default_rng(seed)
order = rng.permutation(len(POOL_IDX))
labeled = [POOL_IDX[i] for i in order[:n_seed]]
unlabeled = [POOL_IDX[i] for i in order[n_seed:]]
history = []
model = None
for r in range(rounds + 1):
model = train_model(
[TEXTS[i] for i in labeled], [LABELS[i] for i in labeled]
)
acc = model.score(
[TEXTS[i] for i in TEST_IDX], [LABELS[i] for i in TEST_IDX]
)
history.append((len(labeled), acc))
if r == rounds or not unlabeled:
break
batch_size = min(batch, len(unlabeled))
if strategy == "random":
chosen = rng.choice(len(unlabeled), size=batch_size, replace=False)
else:
scores = SCORERS[strategy](model, [TEXTS[i] for i in unlabeled])
chosen = np.argsort(-scores, kind="stable")[:batch_size]
for c in sorted(chosen.tolist(), reverse=True):
labeled.append(unlabeled.pop(c))
return history, modelWe run three strategies over five seeds. The same seed produces the same initial labeled set and the same pool ordering across strategies, so the comparison is paired.
PythonIn [21]Expand
STRATEGIES = ["random", "least_confidence", "entropy"]
SEEDS = [0, 1, 2, 3, 4]
results = {s: [] for s in STRATEGIES}
final_predictions = {}
for s in STRATEGIES:
for seed in SEEDS:
hist, mdl = run_active_learning(seed, s)
results[s].append(hist)
if seed == 0:
final_predictions[s] = mdl.predict([TEXTS[i] for i in TEST_IDX])
curve_stats = {}
areas_by_seed = {}
for strategy, histories in results.items():
runs = np.asarray(histories, dtype=float)
budgets = runs[0, :, 0]
accuracies = runs[:, :, 1]
curve_stats[strategy] = (
budgets,
accuracies.mean(axis=0),
accuracies.std(axis=0),
)
areas_by_seed[strategy] = np.trapezoid(accuracies, x=budgets, axis=1) / (
budgets[-1] - budgets[0]
)Learning Curves
First compare the average accuracy over the common observed budget range of 24 to 144 labels. The trapezoids are computed per seed before averaging.
ConsoleOut [22]Expand
random mean normalised area: 0.863
least_confidence mean normalised area: 0.892
entropy mean normalised area: 0.883Each number summarizes the shared budget range. The curves show where the strategies differ.
VisualizationOut [23]Expand

At a fixed budget, compare accuracies. For a budget comparison, choose an accuracy all the curves attain and find each strategy’s first measured round at or above that level. Here the final random mean, about 93.3%, gives one target. Random reaches it at 132 labels, while both active strategies reach it at 96. That is a difference of 36 labels at the measured rounds. Converting label savings to hours requires measuring annotation time.
These differences belong to the simulated data, fitted models and sampling procedures used here. A new task needs its own random baseline at matched budgets and an evaluation set that represents its intended use.
The shaded bands show how the scores vary across seeds. The paired comparison at the last budget estimates the entropy-versus-random difference on the same test items.
Evaluation With Uncertainty
Use a Wilson score interval for a binomial proportion and read it with its sample size and independence assumption. For example, small per-class denominators may produce proportions close to zero or one.
PythonIn [24]Expand
def wilson_interval(successes, n, z=1.96):
"""95% Wilson score interval for a binomial proportion."""
p = successes / n
denom = 1 + z**2 / n
centre = (p + z**2 / (2 * n)) / denom
half = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return centre - half, centre + half
test_sizes = np.array([25, 50, 100, 200, 400, 800, 1600])
ci_widths = []
for n in test_sizes:
lo, hi = wilson_interval(int(round(0.8 * n)), int(n))
ci_widths.append(hi - lo)
width_table = list(zip(test_sizes.tolist(), np.round(ci_widths, 3).tolist()))PythonIn [25]Expand
width_text = f"{'n':>6} {'95% CI width':>13}\n" + "\n".join(
f"{n:>6} {w:>13.3f}" for n, w in width_table
)ConsoleOut [26]Expand
n 95% CI width
25 0.303
50 0.218
100 0.155
200 0.110
400 0.078
800 0.055
1600 0.039At 80% observed accuracy and 100 independent items, the Wilson interval spans about 15.5 percentage points. The width approaches inverse-square-root scaling as the sample grows. Quadrupling the sample approximately halves the width. For a comparison on shared items, examine the paired differences instead of using this single-model width as a minimum effect size.
VisualizationOut [27]Expand

Finally, we can put this to work on the actual classifiers. The question "is entropy sampling better than random here?" is a question about a difference between two systems evaluated on the same 300 items, so the right tool is a paired bootstrap over test items rather than two independent intervals.
PythonIn [28]Expand
def paired_bootstrap(y_true, pred_a, pred_b, n_boot=2000, seed=0):
"""Resample accuracy_b - accuracy_a for nonempty item-aligned vectors."""
y_true, pred_a, pred_b = map(np.asarray, (y_true, pred_a, pred_b))
if (
y_true.ndim != 1
or not y_true.size
or pred_a.shape != y_true.shape
or pred_b.shape != y_true.shape
):
raise ValueError(
"Provide nonempty one-dimensional arrays for the same test items."
)
rng = np.random.default_rng(seed)
correct_a = (pred_a == y_true).astype(float)
correct_b = (pred_b == y_true).astype(float)
n = len(y_true)
diffs = np.empty(n_boot)
for i in range(n_boot):
idx = rng.integers(0, n, n)
diffs[i] = correct_b[idx].mean() - correct_a[idx].mean()
return diffs
y_test = [LABELS[i] for i in TEST_IDX]
diff_dist = paired_bootstrap(
y_test, final_predictions["random"], final_predictions["entropy"]
)
acc_random = float(
np.mean(np.asarray(final_predictions["random"]) == np.asarray(y_test))
)
acc_entropy = float(
np.mean(np.asarray(final_predictions["entropy"]) == np.asarray(y_test))
)
lo, hi = np.percentile(diff_dist, [2.5, 97.5])ConsoleOut [29]Expand
Random selection accuracy: 0.923 Entropy selection accuracy: 0.947 Paired difference: +0.023 95% bootstrap interval: [-0.010, +0.053] Interval excludes zero: False
The printed interval resamples 300 test items for the two models trained from seed 0. It includes zero in this run. It describes test-item uncertainty conditional on those trained models. The learning curves describe how accuracy varies across five starting sets on the same test set.
ConsoleOut [30]Expand
precision recall f1-score support
fishing 0.950 0.927 0.938 82
kinship 0.967 0.967 0.967 122
weather 0.918 0.938 0.928 96
accuracy 0.947 300
macro avg 0.945 0.944 0.944 300
weighted avg 0.947 0.947 0.947 300Each class has its own denominator. Suppose 40 test items truly belong to a class and the model correctly assigns 28 of them to that class. Its observed recall is 0.70, and a 95% Wilson interval is about 55% to 82%. Its full width is about 27 percentage points and its half-width about 14 points. Precision divides by the number of items the model predicts as that class.
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!