7  Choose a string metric

This package ships around thirty ways to score how alike two strings are. Picking one by reputation – “Jaro-Winkler is the standard for names” – leaves the obvious question unanswered: standard for which names, against which wrong answers?

This chapter answers it by measurement. Three hand-labelled sets of pairs, one each for given names, surnames and addresses, are scored by every candidate comparator, and the results say which comparator separates the true pairs from the false ones in each field. Every number below is computed when this page is rendered; the code is all here, so the same exercise runs on your own labelled pairs by swapping the data in.

Three things fall out of it, and they are worth stating before the tables:

  1. The field matters more than the metric’s reputation. The comparator that wins on addresses is near the bottom on given names, and vice versa.
  2. Jaro-Winkler’s prefix bonus is a liability when the wrong answers share a prefix – ALAN/ALANA, HARRIS/HARRISON, 12 SMITH ST/12 SMITH AVE. Plain Jaro, or a length-sensitive edit similarity, discriminates better on exactly the pairs that cause trouble.
  3. For the hardest pairs no comparator works, because the strings do not carry the answer: BOB and ROBERT are the same person and SIMON and SIMONE are not, and no function of two character vectors can know that. Those pairs are fixed by standardising before scoring, by comparing parsed components, or by another field – never by a better metric. sec-recipe does all three.

7.1 The candidates

Comparator Call What it rewards
Jaro-Winkler jaro_winkler(a, b) character agreement, with a bonus for a shared prefix
Jaro jaro_winkler(a, b, p = 0) the same, with no prefix bonus
Jaro-Winkler, tokens jaro_winkler_tokens(a, b) the best alignment of whole words, in any order
Monge-Elkan monge_elkan(a, b, symmetric = TRUE) each word’s best match in the other string
Levenshtein levenshtein_similarity(a, b) few insertions, deletions, substitutions, relative to length
OSA osa_similarity(a, b) the same, counting an adjacent swap as one edit
Editex editex_similarity(a, b) edits, charging less for letters that sound alike
Indel indel_similarity(a, b) insertions and deletions only (no substitutions)
LCS (subsequence) lcs_seq_similarity(a, b) a long common subsequence
LCS (substring) lcs_str_similarity(a, b) one long contiguous run in common
Prefix prefix_similarity(a, b) a long common start
Smith-Waterman smith_waterman(a, b) the best-matching local region, gaps forgiven
Jaccard, 2-grams jaccard_index(a, b, q = 2) shared character pairs, penalising unshared ones
Jaccard, 3-grams jaccard_index(a, b, q = 3) the same, over longer and so more specific grams
Cosine, 3-grams cosine_similarity(a, b, q = 3) shared 3-grams, weighted by how often each occurs
Tversky containment tversky_index(a, b, q = 3, alpha = 1, beta = 0) how much of a appears in b, ignoring extra material in b
Token set fuzz_token_set_ratio(a, b) the words in common, ignoring order and duplicates
Weighted ratio fuzz_wratio(a, b) RapidFuzz’s own blend of ratio, partial and token scorers
Soundex agreement soundex(a) == soundex(b) the same phonetic code – a blocking key, included for contrast
comparators <- list(
    jaro_winkler   = function(a, b) jaro_winkler(a, b),
    jaro           = function(a, b) jaro_winkler(a, b, p = 0),
    jw_tokens      = function(a, b) jaro_winkler_tokens(a, b),
    monge_elkan    = function(a, b) monge_elkan(a, b, symmetric = TRUE),
    levenshtein    = function(a, b) levenshtein_similarity(a, b),
    osa            = function(a, b) osa_similarity(a, b),
    editex         = function(a, b) editex_similarity(a, b),
    indel          = function(a, b) indel_similarity(a, b),
    lcs_seq        = function(a, b) lcs_seq_similarity(a, b),
    lcs_str        = function(a, b) lcs_str_similarity(a, b),
    prefix         = function(a, b) prefix_similarity(a, b),
    smith_waterman = function(a, b) smith_waterman(a, b),
    jaccard_q2     = function(a, b) jaccard_index(a, b, q = 2),
    jaccard_q3     = function(a, b) jaccard_index(a, b, q = 3),
    cosine_q3      = function(a, b) cosine_similarity(a, b, q = 3),
    tversky_in     = function(a, b) tversky_index(a, b, q = 3, alpha = 1, beta = 0),
    fuzz_token_set = function(a, b) fuzz_token_set_ratio(a, b) / 100,
    fuzz_wratio    = function(a, b) fuzz_wratio(a, b) / 100,
    soundex_equal  = function(a, b) as.numeric(soundex(a) == soundex(b))
)

Every one is put on the same scale, where 1 means identical: the *_similarity() functions already are, the RapidFuzz scorers are divided by 100, and distances are left out in favour of their similarity twins. rLink() does this conversion itself, so a comparator chosen here drops straight into a linkage (sec-uc-link).

7.2 The test pairs, graded by difficulty

A comparison is only as good as what it is compared against. Scoring true matches against randomly chosen non-matches flatters every metric: every comparator in the list separates SMITH/SMYTH from SMITH/NGUYEN. What distinguishes them is the awkward middle, so each set grades both classes:

easy moderate hard
match one keystroke, a transposition, a dropped letter a phonetic variant, a prefix convention, an abbreviation a nickname, a short form, reordered or extra words
non-match unrelated values the same root word, a different locality one decisive letter or digit apart
given <- read.csv(text = "a,b,kind,degree,match
MICHELLE,MICHELE,dropped letter,easy,TRUE
JOHN,JOHM,keystroke,easy,TRUE
SARAH,SARA,dropped letter,easy,TRUE
JEFFREY,JEFFERY,transposition,easy,TRUE
MICHAEL,MCIHAEL,transposition,easy,TRUE
ANNE MARIE,ANNEMARIE,spacing,easy,TRUE
CATHERINE,KATHERINE,phonetic,moderate,TRUE
PHILIP,FILIP,phonetic,moderate,TRUE
GEOFFREY,JEFFREY,phonetic,moderate,TRUE
STEVEN,STEPHEN,phonetic,moderate,TRUE
SHAUN,SHAWN,phonetic,moderate,TRUE
ASHLEIGH,ASHLEY,phonetic,moderate,TRUE
MARY JANE,JANE MARY,word order,hard,TRUE
ALEXANDER,ALEX,short form,hard,TRUE
CHRISTOPHER,CHRIS,short form,hard,TRUE
SAMANTHA,SAM,short form,hard,TRUE
ROBERT,BOB,nickname,hard,TRUE
WILLIAM,BILL,nickname,hard,TRUE
ELIZABETH,LIZ,nickname,hard,TRUE
MARGARET,PEGGY,nickname,hard,TRUE
JOHN,PETER,unrelated,easy,FALSE
MARY,SIOBHAN,unrelated,easy,FALSE
ROBERT,AMELIA,unrelated,easy,FALSE
HARRY,FRANCESCA,unrelated,easy,FALSE
GRACE,DIMITRIOS,unrelated,easy,FALSE
JOHN,JOHNATHAN,same root,moderate,FALSE
KIM,KIMBERLEY,same root,moderate,FALSE
CHRIS,CHRISTINE,same root,moderate,FALSE
SAM,SAMUEL,same root,moderate,FALSE
STEPHEN,STEPHANIE,same root,moderate,FALSE
JOAN,JOHN,one letter apart,hard,FALSE
JULIE,JULIA,one letter apart,hard,FALSE
CLARE,CLARA,one letter apart,hard,FALSE
ANDREA,ANDREW,one letter apart,hard,FALSE
ERIN,ERIC,one letter apart,hard,FALSE
ALAN,ALANA,one letter apart,hard,FALSE
SIMON,SIMONE,one letter apart,hard,FALSE
MARTIN,MARTINA,one letter apart,hard,FALSE
DANIEL,DANIELLE,one letter apart,hard,FALSE
BRIAN,BRIANNA,one letter apart,hard,FALSE
", stringsAsFactors = FALSE)
surname <- read.csv(text = "a,b,kind,degree,match
JONES,JONSE,transposition,easy,TRUE
WILLIAMSON,WILLIAMSEN,keystroke,easy,TRUE
NGUYEN,NGYUEN,transposition,easy,TRUE
KOWALCZYK,KOWALCYZK,transposition,easy,TRUE
PAPADOPOULOS,PAPADOPOLOUS,transposition,easy,TRUE
OBRIEN,O BRIEN,punctuation,easy,TRUE
SMITH,SMYTH,phonetic,moderate,TRUE
SHEPHERD,SHEPPARD,phonetic,moderate,TRUE
MACDONALD,MCDONALD,prefix variant,moderate,TRUE
FITZGERALD,FITZGERLAD,transposition,moderate,TRUE
CHAUDHRY,CHOUDARY,phonetic,moderate,TRUE
DE LA CRUZ,DELACRUZ,spacing,moderate,TRUE
SMITH,SMITH-JONES,double-barrelled,hard,TRUE
LEE,LEE NGUYEN,name added,hard,TRUE
VAN DER BERG,BERG,prefix dropped,hard,TRUE
WOJCIECHOWSKI,WOJCIK,shortened,hard,TRUE
SMITH,NGUYEN,unrelated,easy,FALSE
JONES,PAPADOPOULOS,unrelated,easy,FALSE
BROWN,SZCZEPANSKI,unrelated,easy,FALSE
TAYLOR,MWANGI,unrelated,easy,FALSE
WILSON,FERNANDEZ,unrelated,easy,FALSE
HARRIS,HARRISON,same root,moderate,FALSE
MORRIS,MORRISON,same root,moderate,FALSE
STEWART,STEWARDSON,same root,moderate,FALSE
ANDERSON,HENDERSON,rhyming,moderate,FALSE
WILLIAMS,WILLIAMSON,same root,moderate,FALSE
THOMSON,THOMPSON,one letter apart,hard,FALSE
JOHNSON,JOHNSTON,one letter apart,hard,FALSE
BAKER,BARKER,one letter apart,hard,FALSE
CHAN,CHEN,one letter apart,hard,FALSE
WANG,WONG,one letter apart,hard,FALSE
HALL,HILL,one letter apart,hard,FALSE
MARTIN,MARTIN JR,suffix,hard,FALSE
SINGH,SINGHA,one letter apart,hard,FALSE
", stringsAsFactors = FALSE)
address <- read.csv(text = 'a,b,kind,degree,match
12 SMITH ST,12 SMITH STREET,abbreviation,easy,TRUE
100 QUEEN ST BRISBANE,100 QUEEN STREET BRISBANE,abbreviation,easy,TRUE
12 SMITH ST,12 SMTIH ST,transposition,easy,TRUE
PO BOX 123 BRISBANE,P O BOX 123 BRISBANE,punctuation,easy,TRUE
7 BOTTLEBRUSH CRESCENT,7 BOTTLEBRUSH CRES,abbreviation,easy,TRUE
45 ST KILDA RD MELBOURNE,45 SAINT KILDA ROAD MELBOURNE,abbreviation,moderate,TRUE
12 SMITH ST BRISBANE QLD 4000,12 SMITH STREET BRISBANE 4000,dropped token,moderate,TRUE
LEVEL 3 100 QUEEN ST,100 QUEEN ST LEVEL 3,token order,moderate,TRUE
1/12 SMITH ST,UNIT 1 12 SMITH ST,format,moderate,TRUE
GPO BOX 9 SYDNEY NSW 2001,G.P.O. BOX 9 SYDNEY 2001,punctuation,moderate,TRUE
12 SMITH ST,UNIT 4 12 SMITH ST ANNERLEY QLD 4103,extra detail,hard,TRUE
9 KING ST,9 KING STREET WEST END BRISBANE QUEENSLAND,extra detail,hard,TRUE
12 SMITH ST,88 ORCHID AVE SURFERS PARADISE,unrelated,easy,FALSE
100 QUEEN ST BRISBANE,7 BOTTLEBRUSH CRESCENT CAIRNS,unrelated,easy,FALSE
PO BOX 123 BRISBANE,41 MARINE PARADE REDCLIFFE,unrelated,easy,FALSE
45 ST KILDA RD MELBOURNE,2 HIGH ST FREMANTLE,unrelated,easy,FALSE
12 SMITH ST BRISBANE,12 SMITH ST SYDNEY,different locality,moderate,FALSE
100 QUEEN ST BRISBANE,100 QUEEN ST MELBOURNE,different locality,moderate,FALSE
12 KING ST,12 KINGS ST,different street,moderate,FALSE
12 SMITH ST,12 SMITH AVE,different street type,hard,FALSE
12 SMITH ST,21 SMITH ST,transposed number,hard,FALSE
12 SMITH ST,12A SMITH ST,different dwelling,hard,FALSE
UNIT 1 12 SMITH ST,UNIT 2 12 SMITH ST,different dwelling,hard,FALSE
12 SMITH ST 4000,12 SMITH ST 4001,different postcode,hard,FALSE
45 ST KILDA RD MELBOURNE,45 ST KILDA RD EAST MELBOURNE,different locality,hard,FALSE
', stringsAsFactors = FALSE)

for (nm in c("given", "surname", "address")) {
    d <- get(nm)
    d$match <- as.logical(d$match)
    d$degree <- factor(d$degree, levels = c("easy", "moderate", "hard"))
    assign(nm, d)
}

The labels encode one judgement: would a reviewer, seeing only this field, call these the same person or address? Several pairs are genuinely arguable – THOMSON/THOMPSON is a misspelling as often as it is two families – and they are labelled non-match deliberately, because a comparator that cannot be told to be cautious there is a comparator that will merge two people. The non-match side is adversarial by design: half of it is near misses, where a real linkage would see mostly unrelated pairs. The absolute numbers below are therefore pessimistic; what they are good for is ranking the comparators against each other on the pairs that decide a linkage.

7.3 How each comparator is scored

Two measures, both reported per field:

  • AUC – the probability that a randomly chosen true pair outranks a randomly chosen false one, over the easy and moderate pairs only. It needs no threshold, which matters because the right threshold differs per comparator. The hard pairs are excluded here and reported separately, since (as the tables show) no comparator separates them and including them only compresses the ranking.
  • Mean score per cell of the match x degree grid, which is where the behaviour actually shows: a comparator is useful when its moderate matches sit well above its moderate non-matches.
score_all <- function(pairs) {
    scores <- lapply(comparators, function(f) f(pairs$a, pairs$b))
    cbind(pairs, as.data.frame(scores))
}

# Mann-Whitney / rank formulation: no bootstrapping, no ties problem
auc <- function(score, match) {
    r <- rank(score)
    n1 <- sum(match)
    n0 <- sum(!match)
    (sum(r[match]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}

report <- function(pairs) {
    scored <- score_all(pairs)
    easy_mod <- scored$degree != "hard"
    cell <- function(v, keep) round(mean(v[keep]), 2)
    out <- do.call(rbind, lapply(names(comparators), function(nm) {
        v <- scored[[nm]]
        data.frame(
            comparator = nm,
            auc = round(auc(v[easy_mod], scored$match[easy_mod]), 2),
            tp_easy = cell(v, scored$match & scored$degree == "easy"),
            tp_mod  = cell(v, scored$match & scored$degree == "moderate"),
            tp_hard = cell(v, scored$match & scored$degree == "hard"),
            fp_easy = cell(v, !scored$match & scored$degree == "easy"),
            fp_mod  = cell(v, !scored$match & scored$degree == "moderate"),
            fp_hard = cell(v, !scored$match & scored$degree == "hard")
        )
    }))
    out$margin <- out$tp_mod - out$fp_mod
    out[order(-out$auc, -out$margin), ]
}

kable_report <- function(pairs, caption) {
    knitr::kable(
        report(pairs), row.names = FALSE, caption = caption,
        col.names = c("Comparator", "AUC", "easy", "moderate", "hard",
                      "easy", "moderate", "hard", "margin")
    )
}

In the tables, the first group of three columns is the mean score on true matches of each difficulty, the second group the mean on non-matches, and margin is the moderate gap between them – the headroom a threshold has to work in.

7.4 Given names

kable_report(given, NULL)
Table 7.1: Given names: 20 matched and 20 non-matched pairs. AUC over the easy and moderate pairs.
Comparator AUC easy moderate hard easy moderate hard margin
levenshtein 0.99 0.79 0.74 0.35 0.04 0.50 0.79 0.24
osa 0.99 0.84 0.74 0.35 0.04 0.50 0.79 0.24
lcs_seq 0.99 0.84 0.74 0.37 0.11 0.50 0.79 0.24
indel 0.98 0.87 0.78 0.48 0.13 0.65 0.83 0.13
fuzz_token_set 0.98 0.87 0.78 0.55 0.13 0.65 0.83 0.13
editex 0.97 0.83 0.81 0.41 0.19 0.58 0.84 0.23
lcs_str 0.95 0.66 0.64 0.37 0.11 0.48 0.76 0.16
jaro 0.90 0.93 0.86 0.68 0.16 0.83 0.89 0.03
jaccard_q2 0.85 0.58 0.49 0.30 0.00 0.38 0.63 0.11
jaro_winkler 0.84 0.95 0.88 0.70 0.16 0.89 0.93 -0.01
jw_tokens 0.84 0.96 0.88 0.76 0.16 0.89 0.93 -0.01
jaccard_q3 0.83 0.43 0.38 0.19 0.00 0.29 0.54 0.09
cosine_q3 0.80 0.59 0.53 0.35 0.00 0.51 0.68 0.02
monge_elkan 0.80 0.92 0.88 0.76 0.16 0.89 0.93 -0.01
soundex_equal 0.78 1.00 0.33 0.00 0.00 0.20 0.90 0.13
prefix 0.70 0.57 0.28 0.16 0.00 0.48 0.76 -0.20
fuzz_wratio 0.65 0.87 0.78 0.76 0.19 0.87 0.83 -0.09
smith_waterman 0.59 0.84 0.75 0.76 0.16 0.94 0.87 -0.19
tversky_in 0.53 0.54 0.49 0.21 0.00 0.92 0.76 -0.43

The ordering is emphatic, and it is the opposite of the folklore. The length-sensitive edit similarities – levenshtein_similarity(), osa_similarity(), lcs_seq_similarity() – separate these names almost perfectly, while jaro_winkler() lands tenth of nineteen with a negative margin: its moderate non-matches score higher (0.89) than its moderate matches (0.88).

The reason is in the prefix row, and in the data. Every moderate non-match here (JOHN/JOHNATHAN, KIM/KIMBERLEY, SAM/SAMUEL) is a longer name that starts with the shorter one, and most of the hard non-matches (ALAN/ALANA, SIMON/SIMONE, MARTIN/MARTINA) are the same thing with one letter. Jaro-Winkler is built to reward a shared prefix, so it rewards precisely the wrong pairs. Turning the bonus off recovers much of the loss:

confusable <- data.frame(
    a = c("ALAN", "SIMON", "MARTIN", "JOHN", "KIM", "DANIEL"),
    b = c("ALANA", "SIMONE", "MARTINA", "JOHNATHAN", "KIMBERLEY", "DANIELLE")
)
data.frame(
    confusable,
    jaro_winkler = round(jaro_winkler(confusable$a, confusable$b), 2),
    jaro         = round(jaro_winkler(confusable$a, confusable$b, p = 0), 2),
    osa          = round(osa_similarity(confusable$a, confusable$b), 2)
)
       a         b jaro_winkler jaro  osa
1   ALAN     ALANA         0.96 0.93 0.80
2  SIMON    SIMONE         0.97 0.94 0.83
3 MARTIN   MARTINA         0.97 0.95 0.86
4   JOHN JOHNATHAN         0.89 0.81 0.44
5    KIM KIMBERLEY         0.84 0.78 0.33
6 DANIEL  DANIELLE         0.95 0.92 0.75

p is tunable rather than all-or-nothing: 0 gives plain Jaro, 0.25 the maximum bonus. If your true matches are typos near the start of the string – common with scanned or dictated data – keep the bonus. If your hard non-matches are suffix extensions, as above, drop it.

The easy column shows what is uncontroversial: every comparator in the table scores an easy match above 0.4 and an unrelated pair below 0.2, so for clean data with only keystroke noise the choice hardly matters. It starts mattering at tp_mod, and by tp_hard the question has changed entirely.

What no comparator can do

Look along the hard row. The best tp_hard figures belong to comparators that also score hard non-matches high, which is no use. The honest reading is that the hard matches here are not a string problem at all:

semantic <- given[given$degree == "hard" & given$match, c("a", "b", "kind")]
data.frame(
    semantic,
    jaro_winkler = round(jaro_winkler(semantic$a, semantic$b), 2),
    osa          = round(osa_similarity(semantic$a, semantic$b), 2),
    jw_tokens    = round(jaro_winkler_tokens(semantic$a, semantic$b), 2)
)
             a         b       kind jaro_winkler  osa jw_tokens
13   MARY JANE JANE MARY word order         0.56 0.33      1.00
14   ALEXANDER      ALEX short form         0.89 0.44      0.89
15 CHRISTOPHER     CHRIS short form         0.89 0.45      0.89
16    SAMANTHA       SAM short form         0.85 0.38      0.85
17      ROBERT       BOB   nickname         0.50 0.33      0.50
18     WILLIAM      BILL   nickname         0.73 0.43      0.73
19   ELIZABETH       LIZ   nickname         0.78 0.33      0.78
20    MARGARET     PEGGY   nickname         0.44 0.12      0.44

BOB is not a corrupted ROBERT and PEGGY is not a corrupted MARGARET; they are different words for the same person. The fix is a lookup, not a metric. freplace_tokens() applies a nickname table to whole words in one vectorised pass, and the scores stop being a judgement call:

nicknames <- c(
    BOB = "ROBERT", BILL = "WILLIAM", LIZ = "ELIZABETH", BETH = "ELIZABETH",
    PEGGY = "MARGARET", ALEX = "ALEXANDER", CHRIS = "CHRISTOPHER",
    SAM = "SAMANTHA", JIM = "JAMES"
)
standardised <- freplace_tokens(semantic$b, names(nicknames), nicknames)
data.frame(
    semantic["a"], b = semantic$b, standardised,
    before = round(jaro_winkler(semantic$a, semantic$b), 2),
    after  = round(jaro_winkler(semantic$a, standardised), 2)
)
             a         b standardised before after
13   MARY JANE JANE MARY    JANE MARY   0.56  0.56
14   ALEXANDER      ALEX    ALEXANDER   0.89  1.00
15 CHRISTOPHER     CHRIS  CHRISTOPHER   0.89  1.00
16    SAMANTHA       SAM     SAMANTHA   0.85  1.00
17      ROBERT       BOB       ROBERT   0.50  1.00
18     WILLIAM      BILL      WILLIAM   0.73  1.00
19   ELIZABETH       LIZ    ELIZABETH   0.78  1.00
20    MARGARET     PEGGY     MARGARET   0.44  1.00

The one row that stays low is MARY JANE/JANE MARY, which is not a vocabulary problem but a word-order one – and that is a metric choice after all: jaro_winkler_tokens() scores it 1, as the table above shows. A nickname table also has a cost: SAM = "SAMANTHA" fixes one row here and would wrongly merge SAM/SAMUEL, so the table belongs with the rest of your standardisation rules, under review, not buried in a scoring call.

7.5 Surnames

kable_report(surname, NULL)
Table 7.2: Surnames: 16 matched and 18 non-matched pairs. AUC over the easy and moderate pairs.
Comparator AUC easy moderate hard easy moderate hard margin
osa 0.94 0.85 0.81 0.39 0.07 0.74 0.79 0.07
lcs_seq 0.94 0.87 0.81 0.39 0.11 0.74 0.79 0.07
editex 0.92 0.83 0.84 0.47 0.20 0.76 0.85 0.08
jaro 0.91 0.95 0.90 0.72 0.35 0.88 0.89 0.02
soundex_equal 0.90 1.00 1.00 0.00 0.00 0.40 0.62 0.60
jw_tokens 0.90 0.97 0.94 0.79 0.35 0.91 0.91 0.03
jaro_winkler 0.86 0.96 0.93 0.78 0.35 0.91 0.91 0.02
levenshtein 0.85 0.77 0.80 0.39 0.07 0.74 0.79 0.06
indel 0.83 0.88 0.84 0.55 0.13 0.83 0.84 0.01
fuzz_wratio 0.83 0.88 0.84 0.88 0.21 0.83 0.85 0.01
monge_elkan 0.83 0.95 0.88 0.85 0.35 0.91 0.91 -0.03
fuzz_token_set 0.76 0.85 0.76 0.91 0.13 0.83 0.87 -0.07
prefix 0.66 0.53 0.36 0.28 0.00 0.58 0.49 -0.22
lcs_str 0.60 0.63 0.50 0.37 0.09 0.74 0.58 -0.24
jaccard_q2 0.55 0.49 0.45 0.31 0.00 0.67 0.47 -0.22
smith_waterman 0.55 0.78 0.70 0.96 0.15 0.95 0.78 -0.25
jaccard_q3 0.48 0.35 0.24 0.23 0.00 0.63 0.28 -0.39
cosine_q3 0.47 0.49 0.34 0.46 0.00 0.78 0.38 -0.44
tversky_in 0.44 0.50 0.32 0.62 0.00 0.93 0.44 -0.61

osa_similarity() and lcs_seq_similarity() lead again, but the interesting rows are the next two.

editex_similarity() is the only comparator whose moderate matches (0.84) beat its easy ones (0.83), because the moderate band is where the phonetic variants live. It charges less for a substitution between letters that sound alike, which is exactly the error surnames collect when they are taken down by ear:

phonetic <- surname[surname$kind %in% c("phonetic", "prefix variant") &
                    surname$match, c("a", "b")]
data.frame(
    phonetic,
    levenshtein = round(levenshtein_similarity(phonetic$a, phonetic$b), 2),
    editex      = round(editex_similarity(phonetic$a, phonetic$b), 2)
)
           a        b levenshtein editex
7      SMITH    SMYTH        0.80   0.90
8   SHEPHERD SHEPPARD        0.75   0.81
9  MACDONALD MCDONALD        0.89   0.89
11  CHAUDHRY CHOUDARY        0.75   0.81

soundex_equal – phonetic-code agreement, not a similarity at all – has the largest margin in the table (0.60) and perfect recall on the easy and moderate matches. That is a real result, and a trap. It is 0 on every hard match and 0.62 on the hard non-matches, because Soundex is built to merge:

hard_fp <- surname[surname$degree == "hard" & !surname$match, c("a", "b")]
data.frame(
    hard_fp,
    code_a = soundex(hard_fp$a),
    code_b = soundex(hard_fp$b),
    same   = soundex(hard_fp$a) == soundex(hard_fp$b)
)
         a         b code_a code_b  same
27 THOMSON  THOMPSON   T525   T512 FALSE
28 JOHNSON  JOHNSTON   J525   J523 FALSE
29   BAKER    BARKER   B260   B626 FALSE
30    CHAN      CHEN   C500   C500  TRUE
31    WANG      WONG   W520   W520  TRUE
32    HALL      HILL   H400   H400  TRUE
33  MARTIN MARTIN JR   M635   M635  TRUE
34   SINGH    SINGHA   S520   S520  TRUE

CHAN/CHEN, WANG/WONG and HALL/HILL all collapse to one code. That makes phonetic codes excellent blocking keys – generous, cheap, and they bring the right pairs into consideration – and poor deciders. sec-uc-link compares the codes by how aggressively they merge; use one to generate candidates and a similarity to score them.

The hard matches here are the other familiar surname problem: SMITH/SMITH-JONES after a marriage, LEE/LEE NGUYEN, VAN DER BERG/BERG. One string is contained in the other, which is a containment question, and the containment-shaped comparators answer it:

contained <- surname[surname$degree == "hard" & surname$match, c("a", "b")]
data.frame(
    contained,
    osa            = round(osa_similarity(contained$a, contained$b), 2),
    tversky_in     = round(tversky_index(contained$a, contained$b, q = 3,
                                         alpha = 1, beta = 0), 2),
    fuzz_token_set = round(fuzz_token_set_ratio(contained$a, contained$b) / 100, 2),
    smith_waterman = round(smith_waterman(contained$a, contained$b), 2)
)
               a           b  osa tversky_in fuzz_token_set smith_waterman
13         SMITH SMITH-JONES 0.45       1.00           1.00           1.00
14           LEE  LEE NGUYEN 0.30       1.00           1.00           1.00
15  VAN DER BERG        BERG 0.33       0.20           1.00           1.00
16 WOJCIECHOWSKI      WOJCIK 0.46       0.27           0.63           0.83

tversky_index(alpha = 1, beta = 0) asks only “how much of a is in b?” and so ignores the words b has added. Note that this makes it directional, which the VAN DER BERG/BERG row shows: the extra words are on the a side there, and the score collapses to 0.20. When either side may be the fuller one – which is the normal case across two files – score both directions and keep the larger:

both_ways <- pmax(
    tversky_index(contained$a, contained$b, q = 3, alpha = 1, beta = 0),
    tversky_index(contained$b, contained$a, q = 3, alpha = 1, beta = 0)
)
data.frame(contained, containment = round(both_ways, 2))
               a           b containment
13         SMITH SMITH-JONES        1.00
14           LEE  LEE NGUYEN        1.00
15  VAN DER BERG        BERG        1.00
16 WOJCIECHOWSKI      WOJCIK        0.75

Containment costs precision: tversky_in is near the bottom of Table tbl-surname overall, because it also rates MARTIN/MARTIN JR and SINGH/SINGHA highly – which is the whole trade in one row. So score both: a high osa_similarity() or a high containment score, with the reason recorded, beats one blended number nobody can audit.

7.6 Addresses

kable_report(address, NULL)
Table 7.3: Addresses: 12 matched and 13 non-matched pairs. AUC over the easy and moderate pairs.
Comparator AUC easy moderate hard easy moderate hard margin
tversky_in 0.95 0.85 0.78 1.00 0.02 0.63 0.84 0.15
jaccard_q3 0.93 0.69 0.59 0.22 0.01 0.45 0.69 0.14
cosine_q3 0.93 0.81 0.74 0.47 0.03 0.62 0.81 0.12
jaccard_q2 0.92 0.74 0.67 0.26 0.06 0.56 0.79 0.11
fuzz_token_set 0.89 0.90 0.93 0.90 0.34 0.84 0.93 0.09
fuzz_wratio 0.87 0.91 0.90 0.90 0.36 0.84 0.92 0.06
smith_waterman 0.87 0.94 0.76 1.00 0.17 0.75 0.89 0.01
indel 0.81 0.91 0.80 0.41 0.30 0.84 0.91 -0.04
jw_tokens 0.81 0.97 0.88 0.72 0.52 0.93 0.95 -0.05
jaro 0.80 0.92 0.81 0.68 0.56 0.87 0.93 -0.06
lcs_seq 0.79 0.85 0.76 0.26 0.25 0.81 0.88 -0.05
levenshtein 0.79 0.83 0.63 0.26 0.18 0.76 0.87 -0.13
osa 0.79 0.85 0.63 0.26 0.18 0.76 0.88 -0.13
editex 0.79 0.86 0.66 0.32 0.27 0.79 0.87 -0.13
jaro_winkler 0.77 0.94 0.83 0.73 0.56 0.92 0.96 -0.09
monge_elkan 0.76 0.94 0.91 0.77 0.42 0.93 0.87 -0.02
lcs_str 0.75 0.68 0.51 0.26 0.09 0.61 0.74 -0.10
soundex_equal 0.64 1.00 0.40 0.50 0.00 1.00 0.67 -0.60
prefix 0.60 0.51 0.11 0.11 0.00 0.61 0.44 -0.50

The ranking inverts. The q-gram set metrics and the containment score lead; jaro_winkler() is second from last, and the edit similarities that won on names are mid-table. Addresses break the assumptions those metrics make:

  • Length varies enormously between two renderings of the same address (9 KING ST versus 9 KING STREET WEST END BRISBANE QUEENSLAND). An edit similarity divides by the longer length, so a true match is punished for the detail one side happens to carry. tversky_in scores those pairs 1.00 (tp_hard) precisely because it does not.
  • The decisive difference is tiny. 12 SMITH ST versus 21 SMITH ST is two characters out of eleven, and a different house. Every comparator in the table scores the hard non-matches above 0.4, and the four best separators score them 0.69–0.84. There is no threshold that keeps those out.
  • Tokens move. LEVEL 3 100 QUEEN ST and 100 QUEEN ST LEVEL 3 are one address, which rewards the token and q-gram comparators and penalises anything positional, prefix_similarity() worst of all (0.11 on moderate matches).

So the first thing to do with an address is not to pick a better comparator; it is to stop comparing the whole string. Two moves fix most of it. Standardise the vocabulary, then compare components separately, exactly where an exact comparison belongs:

street_types <- c(
    STREET = "ST", ROAD = "RD", AVENUE = "AVE", CRESCENT = "CRES",
    PARADE = "PDE", DRIVE = "DR", COURT = "CT", PLACE = "PL",
    HIGHWAY = "HWY", LANE = "LN", TERRACE = "TCE", SAINT = "ST"
)
std_address <- function(x) {
    freplace_tokens(fsquish(fupper(ascii_fold(x))),
                    names(street_types), street_types)
}
house_number <- function(x) fextract("^[0-9]+[A-Z]?", fsquish(fupper(x)))

hard_cases <- address[address$degree == "hard", ]
data.frame(
    hard_cases[c("a", "b", "match")],
    no_a  = house_number(hard_cases$a),
    no_b  = house_number(hard_cases$b),
    agree = house_number(hard_cases$a) == house_number(hard_cases$b),
    tversky_in = round(tversky_index(std_address(hard_cases$a),
                                     std_address(hard_cases$b),
                                     q = 3, alpha = 1, beta = 0), 2)
)
                          a                                          b match
11              12 SMITH ST       UNIT 4 12 SMITH ST ANNERLEY QLD 4103  TRUE
12                9 KING ST 9 KING STREET WEST END BRISBANE QUEENSLAND  TRUE
20              12 SMITH ST                               12 SMITH AVE FALSE
21              12 SMITH ST                                21 SMITH ST FALSE
22              12 SMITH ST                               12A SMITH ST FALSE
23       UNIT 1 12 SMITH ST                         UNIT 2 12 SMITH ST FALSE
24         12 SMITH ST 4000                           12 SMITH ST 4001 FALSE
25 45 ST KILDA RD MELBOURNE              45 ST KILDA RD EAST MELBOURNE FALSE
   no_a no_b agree tversky_in
11   12 <NA>    NA       1.00
12    9    9  TRUE       1.00
20   12   12  TRUE       0.78
21   12   21 FALSE       0.78
22   12  12A FALSE       0.78
23 <NA> <NA>    NA       0.81
24   12   12  TRUE       0.93
25   45   45  TRUE       0.95

The house number separates 12 SMITH ST from 21 SMITH ST and from 12A SMITH ST in a way no similarity score will, and it says nothing at all about the PO BOX and unit-number forms, where it is NA – which is the right answer, and why the comparison has to be per component rather than one number for the whole line. fsplit_field(), fextract() and string_shape() (sec-uc-profile) are the tools for pulling the components out; freplace_tokens() for the vocabulary.

7.7 Cost is not the deciding factor

All nineteen comparators are compiled and parallel, so the choice can be made on accuracy alone. On 200,000 pairs of surnames:

set.seed(1)
pool <- c("SMITH", "SMYTH", "JONES", "NGUYEN", "PAPADOPOULOS", "OBRIEN",
          "WILLIAMSON", "CHAUDHRY", "SZCZEPANSKI", "LEE")
left  <- sample(pool, 2e5, replace = TRUE)
right <- sample(pool, 2e5, replace = TRUE)
timings <- sapply(comparators, function(f) system.time(f(left, right))[["elapsed"]])
cost <- data.frame(comparator = names(timings), seconds = round(unname(timings), 3))
knitr::kable(cost[order(cost$seconds), ], row.names = FALSE,
             col.names = c("Comparator", "Seconds"))
Table 7.4: Seconds to score 200,000 pairs, 16 cores, one run each (this machine – yours will vary).
Comparator Seconds
jaro_winkler 0.00
jaro 0.00
osa 0.00
editex 0.00
jaccard_q2 0.00
tversky_in 0.00
fuzz_token_set 0.00
fuzz_wratio 0.00
soundex_equal 0.00
levenshtein 0.01
indel 0.01
lcs_seq 0.01
lcs_str 0.01
jw_tokens 0.02
monge_elkan 0.02
prefix 0.02
smith_waterman 0.02
jaccard_q3 0.02
cosine_q3 0.02

The spread between the cheapest and the dearest is a few hundredths of a second over 200,000 pairs. Candidate generation, not scoring, is where a linkage spends its time (sec-benchmarks), so score two or three comparators per field and keep the columns – it costs almost nothing and makes a clerical reviewer’s job far easier than one blended number.

7.8 What to use

Field, and what goes wrong in it Use Why
Given name, typos and dropped letters osa_similarity() best AUC here; counts a transposition as one edit
Given name, where longer names are different people (ALAN/ALANA) osa_similarity(), or jaro_winkler(p = 0) length-sensitive; no prefix bonus to exploit
Given name, typos in the first letters jaro_winkler() the prefix bonus earns its keep
Given name, nicknames and short forms freplace_tokens() first, then score not a string-distance problem
Given names in one field, reordered jaro_winkler_tokens(), monge_elkan() align whole words in any order
Surname, taken down by ear editex_similarity() cheaper substitutions between like-sounding letters
Surname, general scoring osa_similarity(), lcs_seq_similarity() best AUC here
Surname, candidate generation soundex(), double_metaphone(), nysiis() perfect recall on easy and moderate pairs; far too generous to decide with
Surname, double-barrelled or added names tversky_index(alpha = 1, beta = 0), fuzz_token_set_ratio() containment, ignoring what the other side adds
Address, whole-string comparison jaccard_index(q = 3), cosine_similarity(q = 3) tolerant of token order, strict about unshared content
Address, one side carrying extra detail tversky_index(q = 3, alpha = 1, beta = 0), smith_waterman() asymmetric: extra material in b is free
Address, reordered tokens fuzz_token_set_ratio() set comparison over words
Address, house number, unit, postcode exact comparison of the parsed component the decisive differences are one character long
Free text, long strings fuzz_token_set_ratio(), cosine_similarity() word sets, not character edits
You need to explain a score edit_ops() returns the edits themselves

7.9 Putting it together

The four pairs below are the hardest kinds in this chapter: two different people whose names look alike, and two matches disguised by a nickname and by abbreviation. One comparator on one field cannot resolve them. The recipe can: standardise, use the comparator that suits each field, compare the decisive component exactly, and let the fields vote.

left_file <- data.frame(
    given   = c("ALAN", "DANIEL", "MICHELLE", "ROBERT"),
    surname = c("BAKER", "THOMSON", "WILLIAMSON", "SMITH"),
    address = c("12 Smith St", "100 Queen St Brisbane",
                "7 Bottlebrush Crescent", "45 St Kilda Rd Melbourne"),
    truth   = c("different person", "different person",
                "same person", "same person")
)
right_file <- data.frame(
    given   = c("ALANA", "DANIEL", "MICHELE", "BOB"),
    surname = c("BARKER", "THOMPSON", "WILLIAMSEN", "SMYTH"),
    address = c("21 SMITH ST", "100 QUEEN ST MELBOURNE",
                "7 BOTTLEBRUSH CRES", "45 SAINT KILDA ROAD MELBOURNE")
)

std_name <- function(x) {
    freplace_tokens(fsquish(fupper(ascii_fold(x))), names(nicknames), nicknames)
}
prepare <- function(d) {
    d$given   <- std_name(d$given)
    d$address <- std_address(d$address)
    d$no      <- house_number(d$address)
    d
}
left_std  <- prepare(left_file)
right_std <- prepare(right_file)

scored <- rLink(
    left_std, right_std,
    pairs   = data.frame(x_index = 1:4, y_index = 1:4),
    compare = list(
        given   = osa_similarity(given),
        surname = editex_similarity(surname),
        address = tversky_index(address, q = 3, alpha = 1, beta = 0),
        number  = (function(x, y) as.numeric(!is.na(x) & !is.na(y) & x == y))(no)
    ),
    keep = c("given", "surname", "truth")
)
scored$decision <- ifelse(
    scored$number == 1 & pmin(scored$given, scored$surname, scored$address) >= 0.75,
    "match", "non-match"
)
scored[, c("given_1", "given_2", "surname_1", "surname_2",
           "given", "surname", "address", "number", "decision", "truth_1")]
    given_1 given_2  surname_1  surname_2 given   surname   address number
     <char>  <char>     <char>     <char> <num>     <num>     <num>  <num>
1:     ALAN   ALANA      BAKER     BARKER 0.800 0.8333333 0.7777778      0
2:   DANIEL  DANIEL    THOMSON   THOMPSON 1.000 0.8750000 0.5789474      1
3: MICHELLE MICHELE WILLIAMSON WILLIAMSEN 0.875 0.9500000 1.0000000      1
4:   ROBERT  ROBERT      SMITH      SMYTH 1.000 0.9000000 1.0000000      1
    decision          truth_1
      <char>           <char>
1: non-match different person
2: non-match different person
3:     match      same person
4:     match      same person

All four land correctly, and each decision is readable: pair 1 is rejected by the house number although every name score is respectable, pair 2 by the locality inside the address score, and pair 4 is accepted only because BOB became ROBERT before anything was compared. That is the shape to aim for – one column per piece of evidence, a rule you can state in a sentence, and no single metric carrying the whole decision.

7.10 Running this on your own data

The ranking in this chapter is the ranking for these pairs. Fields differ, collection methods differ, and the only reliable way to choose is to grade a few dozen pairs of your own and re-run the tables:

  1. Take a sample of candidate pairs from your own blocking – from rLink() with compare = NULL, say – and label them, including the awkward ones. A hundred pairs per field is enough to separate the comparators; it is not enough to tune a threshold to three decimal places.
  2. Grade each pair easy, moderate or hard, and keep the kind column. When a comparator does badly, the kind of the pairs it fails on tells you what to standardise.
  3. Swap your data frame into report() above. Nothing else in the scaffolding is specific to these examples.
  4. Read margin and the moderate columns, not the top line. A comparator with a high AUC and a thin margin is one bad batch of data away from failing.

sec-uc-link puts the chosen comparators into a full linkage, and sec-theory explains what each one computes.