Parallel Data Mining and Quality Control › Worked Example: Mining and Filtering a Tiny Corpus

Michael BrenndoerferNovember 26, 202610 min read
Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 192Parallel Data Mining and Quality Control › Worked Example: Mining and Filtering a Tiny Corpus
Reading section 7 of 14 · Worked Example: Mining and Filtering a Tiny Corpus · 10 minSection 7 of 14 · 10 min

Section 7 of 14 · 10 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

The ten English sentences and twelve German candidates below give each score an inspectable label. Their unit vectors are a constructed fixture. It represents cosine patterns to test filtering logic offline, not measured behavior of a language encoder or a claim about any language pair.

Each row shows which candidate would win under cosine retrieval. Two rows are constructed to test the cutoffs independently: one has a weak but distinctive wrong match, and one has a wrong match with close competitors.

Setup

The executable cells use NumPy, pandas, and Matplotlib. They use authored examples and require no pretrained weights, network requests, or model download.

We start with a small English sentence set, the corresponding German translations, and two deliberate noise sentences.

PythonIn [7]
CollapseExpand
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Ten English sentences and their correct German translations.
en_sents = [
    "The cat sat on the mat.",
    "Where is the train station?",
    "I would like a cup of coffee, please.",
    "The weather is beautiful today.",
    "She reads books every evening.",
    "Thank you very much for your help.",
    "This is a very good restaurant.",
    "The meeting starts at nine o'clock.",
    "He works as a software engineer.",
    "We need to buy some groceries.",
]
de_gold = [
    "Die Katze saß auf der Matte.",
    "Wo ist der Bahnhof?",
    "Ich hätte gerne eine Tasse Kaffee, bitte.",
    "Das Wetter ist heute wunderschön.",
    "Sie liest jeden Abend Bücher.",
    "Vielen Dank für Ihre Hilfe.",
    "Das ist ein sehr gutes Restaurant.",
    "Die Besprechung beginnt um neun Uhr.",
    "Er arbeitet als Softwareentwickler.",
    "Wir müssen einige Lebensmittel einkaufen.",
]

# Two noise sentences: one unrelated, one generic.
de_noise = [
    "Die Regierung kündigte heute neue Maßnahmen an.",
    "Vielen Dank.",
]
de_cands = de_gold + de_noise

assert len(de_cands) == len(en_sents) + len(de_noise)

The candidates include the ten labeled translations and two distractors. The fixture uses the generic German phrase to illustrate a weak absolute match that still ranks first in its row.

Build the cosine fixture with one orthogonal coordinate per German candidate. Each English vector uses its desired candidate cosines along those coordinates. An extra coordinate, unused by all German vectors, makes each English vector unit length. The full product therefore has shape 10 by 12.

PythonIn [8]
CollapseExpand
n_sources, n_targets = len(en_sents), len(de_cands)
desired_cosine = np.full((n_sources, n_targets), 0.02)
for i in range(n_sources):
    desired_cosine[i, i] = 0.76
    desired_cosine[i, (i + 1) % n_sources] = 0.32
    desired_cosine[i, (i + 2) % n_sources] = 0.25
    desired_cosine[i, n_sources] = 0.12

# A weak but distinctive wrong match.
desired_cosine[5] = 0.02
desired_cosine[5, [5, 6, 10, 11]] = [0.40, 0.04, 0.04, 0.42]
# A stronger wrong match with several nearly tied alternatives.
desired_cosine[7] = 0.02
desired_cosine[7, [3, 7, 8, 9]] = [0.48, 0.50, 0.51, 0.49]

tgt_vectors = np.eye(n_targets, n_targets + 1)
remaining_sq_norm = 1.0 - np.sum(desired_cosine**2, axis=1)
assert np.all(remaining_sq_norm >= 0)
src_vectors = np.column_stack((desired_cosine, np.sqrt(remaining_sq_norm)))
assert np.allclose(np.linalg.norm(src_vectors, axis=1), 1.0)
assert np.allclose(np.linalg.norm(tgt_vectors, axis=1), 1.0)
sim = src_vectors @ tgt_vectors.T

For every pair, take exactly three alternatives after excluding that pair's target. Division is defined only when their mean cosine is positive.

PythonIn [9]
CollapseExpand
def margin_matrix(sim: np.ndarray, k: int = 3) -> np.ndarray:
    n_sources, n_targets = sim.shape
    if not 1 <= k < n_targets:
        raise ValueError("k must be positive and smaller than the target count")
    margins = np.full(sim.shape, np.nan, dtype=float)
    for i, row in enumerate(sim):
        for j in range(n_targets):
            competitors = np.delete(row, j)
            background = np.sort(competitors)[-k:].mean()
            if background > 0:
                margins[i, j] = row[j] / background
    return margins


margin_mat = margin_matrix(sim)
cosine_cutoff, margin_cutoff = 0.5, 1.05

Retrieve the best target per source by cosine. The target with the same index as the source is its labeled translation. Here ranking uses cosine and margin is used only as a gate. The raw scores are kept for every comparison.

PythonIn [10]
CollapseExpand
source_indices = np.arange(n_sources)
best_j = sim.argmax(axis=1)
best_cos = sim[source_indices, best_j]
best_margin = margin_mat[source_indices, best_j]
main_df = pd.DataFrame(
    {
        "source_id": [f"S{i + 1}" for i in source_indices],
        "english": en_sents,
        "best_german": [de_cands[j] for j in best_j],
        "cosine": best_cos,
        "margin": best_margin,
        "is_correct": best_j == source_indices,
    }
)
Out[11]:
source_id english best_german cosine margin is_correct
0 S1 The cat sat on the mat. Die Katze saß auf der Matte. 0.76 3.304 True
1 S2 Where is the train station? Wo ist der Bahnhof? 0.76 3.304 True
2 S3 I would like a cup of coffee, please. Ich hätte gerne eine Tasse Kaffee, bitte. 0.76 3.304 True
3 S4 The weather is beautiful today. Das Wetter ist heute wunderschön. 0.76 3.304 True
4 S5 She reads books every evening. Sie liest jeden Abend Bücher. 0.76 3.304 True
5 S6 Thank you very much for your help. Vielen Dank. 0.42 2.625 False
6 S7 This is a very good restaurant. Das ist ein sehr gutes Restaurant. 0.76 3.304 True
7 S8 The meeting starts at nine o'clock. Er arbeitet als Softwareentwickler. 0.51 1.041 False
8 S9 He works as a software engineer. Er arbeitet als Softwareentwickler. 0.76 3.304 True
9 S10 We need to buy some groceries. Wir müssen einige Lebensmittel einkaufen. 0.76 3.304 True

The table includes one incorrect winner below the cosine threshold and a different incorrect winner below the margin threshold. The scatter plots up to three target candidates per source. The bar chart shows the cosine winner's margin and keeps each source identifier attached as the bars are sorted.

PythonIn [12]
CollapseExpand
records = []
for i in source_indices:
    for j in np.argsort(-sim[i], kind="stable")[:3]:
        records.append(
            {
                "cosine": sim[i, j],
                "margin": margin_mat[i, j],
                "is_correct": j == i,
            }
        )
scatter_df = pd.DataFrame(records)
correct_points = scatter_df.loc[scatter_df["is_correct"]]
other_points = scatter_df.loc[~scatter_df["is_correct"]]
bar_df = main_df.sort_values("margin", ascending=False)
VisualizationsOut [13]
CollapseExpand
Candidate cosines and margins, colored by translation label, with two threshold lines.
Top-three cosine candidates per source in the constructed fixture. The dashed lines show the cosine and margin cutoffs.
Ten sorted margin bars. The two amber bars mark incorrect top cosine candidates.
Margin of each source's top cosine candidate. The amber bars are the two incorrect winners. S6 clears the margin cutoff but fails the cosine cutoff in the scatter.

Apply the two cutoffs and a separate target/source length-ratio band. This example counts whitespace-delimited words on both sides.

PythonIn [14]
CollapseExpand
main_df["length_ratio"] = [
    len(de_cands[j].split()) / len(en_sents[i].split())
    for i, j in enumerate(best_j)
]
main_df["pass_margin"] = main_df["margin"].ge(margin_cutoff)
main_df["pass_cosine"] = main_df["cosine"].ge(cosine_cutoff)
main_df["pass_length"] = main_df["length_ratio"].between(0.5, 2.0)
main_df["keep"] = main_df[["pass_margin", "pass_cosine", "pass_length"]].all(
    axis=1
)

filter_masks = {
    "Margin": main_df["pass_margin"],
    "Cosine": main_df["pass_cosine"],
    "Length ratio": main_df["pass_length"],
    "All three": main_df["keep"],
}
summary = pd.DataFrame(
    [
        {
            "filter": name,
            "survivors": int(passes.sum()),
            "correct among survivors": int(
                (passes & main_df["is_correct"]).sum()
            ),
        }
        for name, passes in filter_masks.items()
    ]
)
Out[15]:
filter survivors correct among survivors
0 Margin 9 8
1 Cosine 9 8
2 Length ratio 9 8
3 All three 8 8

The margin filter alone keeps the weak match for S6. The cosine floor alone keeps the crowded match for S8. Applying all three filters retains the eight correct winners. That result follows from the constructed score patterns. Estimate real filter precision and recall on independently labeled pairs.

Aligning a document

Mining gives candidate document pairs. To see how sentence alignment works on one, we use a five-sentence English paragraph paired with a six-sentence German translation in which one English sentence was split into two German sentences. The example uses a length-only dynamic program inspired by Gale–Church.

PythonIn [16]
CollapseExpand
en_para = [
    "The committee met on Tuesday to discuss the budget.",
    "Several members raised concerns about the proposed cuts.",
    "In the end, they agreed to postpone the decision.",
    "The chair thanked everyone.",
    "The next meeting will be held in May.",
]
de_para = [
    "Der Ausschuss traf sich am Dienstag, um den Haushalt zu besprechen.",
    "Mehrere Mitglieder äußerten Bedenken.",
    "Es ging dabei um die vorgeschlagenen Kürzungen.",
    "Am Ende einigten sie sich darauf, die Entscheidung zu verschieben.",
    "Die Vorsitzende dankte allen.",
    "Das nächste Treffen findet im Mai statt.",
]
en_lens = [len(s) for s in en_para]
de_lens = [len(s) for s in de_para]

The paragraph is constructed so that a naive index-based pairing would fail:

  • English sentence 1 corresponds to German sentence 1.
  • English sentence 2 corresponds to German sentences 2 and 3 together.
  • From that point on, every index is off by one.

A pipeline that assumed sentence ii aligns to sentence ii would produce four wrong pairs out of five, which is exactly the kind of silent corruption that ruins a mined corpus.

This length-only dynamic program shares the prefix-alignment idea of Gale-Church and uses the conditional Gaussian teaching score above.

PythonIn [17]
CollapseExpand
MOVES = [(1, 1), (1, 0), (0, 1), (2, 1), (1, 2), (2, 2)]
MOVE_LOG_PRIOR = {
    (1, 1): 0.0,
    (1, 0): -6.0,
    (0, 1): -6.0,
    (2, 1): -2.0,
    (1, 2): -2.0,
    (2, 2): -5.0,
}


def gc_logprob(l1, l2, c, s2):
    if l1 == 0 or l2 == 0:
        return 0.0
    return -0.5 * np.log(2 * np.pi * s2 * l1) - ((l2 - c * l1) ** 2) / (
        2 * s2 * l1
    )


def align_gc(src_lens, tgt_lens, c=1.0, s2=7.5, merge_22_log_weight=-5.0):
    move_log_weights = {**MOVE_LOG_PRIOR, (2, 2): merge_22_log_weight}
    n, m = len(src_lens), len(tgt_lens)
    dp = np.full((n + 1, m + 1), -np.inf)
    back = -np.ones((n + 1, m + 1), dtype=int)
    dp[0, 0] = 0.0
    for i in range(n + 1):
        for j in range(m + 1):
            if not np.isfinite(dp[i, j]):
                continue
            for mi, (di, dj) in enumerate(MOVES):
                ni, nj = i + di, j + dj
                if ni > n or nj > m:
                    continue
                l1 = sum(src_lens[i:ni])
                l2 = sum(tgt_lens[j:nj])
                if l1 == 0 and l2 == 0:
                    continue
                score = (
                    dp[i, j]
                    + gc_logprob(l1, l2, c, s2)
                    + move_log_weights[(di, dj)]
                )
                if score > dp[ni, nj]:
                    dp[ni, nj] = score
                    back[ni, nj] = mi
    pairs = []
    i, j = n, m
    while i > 0 or j > 0:
        mi = back[i, j]
        di, dj = MOVES[mi]
        pairs.append((list(range(i - di, i)), list(range(j - dj, j))))
        i, j = i - di, j - dj
    pairs.reverse()
    return pairs, dp[n, m]

The back array stores the move that produced each best score, so the function can recover the path from the final cell. The example assumes positive character lengths and s2>0s^2>0. The additive values in MOVE_LOG_PRIOR penalize splits, merges, and gaps relative to a one-to-one move. They are illustrative weights, with (2,2) optionally overridden for the comparison below.

We estimate the length ratio cc from the data and run the aligner.

PythonIn [18]
CollapseExpand
c_hat = sum(de_lens) / sum(en_lens)
pairs, score = align_gc(en_lens, de_lens, c=c_hat, s2=7.5)
loose_pairs, _ = align_gc(
    en_lens, de_lens, c=c_hat, s2=7.5, merge_22_log_weight=-3.0
)

gc_rows = []
for src_idx, tgt_idx in pairs:
    gc_rows.append(
        {
            "english": " ".join(en_para[k] for k in src_idx),
            "german": " ".join(de_para[k] for k in tgt_idx),
            "shape": f"{len(src_idx)}-{len(tgt_idx)}",
        }
    )
gc_df = pd.DataFrame(gc_rows)
Out[19]:
Estimated length ratio c = 1.300
Move shapes with a weaker 2-to-2 penalty: [(1, 1), (1, 2), (2, 2), (1, 1)]
english german shape
0 The committee met on Tuesday to discuss the bu... Der Ausschuss traf sich am Dienstag, um den Ha... 1-1
1 Several members raised concerns about the prop... Mehrere Mitglieder äußerten Bedenken. Es ging ... 1-2
2 In the end, they agreed to postpone the decision. Am Ende einigten sie sich darauf, die Entschei... 1-1
3 The chair thanked everyone. Die Vorsitzende dankte allen. 1-1
4 The next meeting will be held in May. Das nächste Treffen findet im Mai statt. 1-1

At the displayed 2-to-2 log weight of −5-5, the program finds the intended 1-to-2 split at English sentence 2 and four 1-to-1 matches. Relaxing that weight to −3-3 leaves the split intact but groups English sentences 3 and 4 with German sentences 4 and 5. The table and figure use −5-5. The additional printed path shows how the assumed move weights change what the same length evidence supports.

The example estimates cc from the complete paired paragraph. An application can estimate a stabler value from a representative set of aligned segments rather than using a single noisy document.

Dictionary or embedding evidence can distinguish plausible segmentations with similar lengths. Compare a length-only baseline with the added signal on the same held-out human alignments to see whether it helps.

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