2025/02/02

編集距離の計算

編集距離(Edit Distance, Levenshtein Distance)の計算のライブラリは今となってはたくさんありそうですが、 いい感じに表示できる jiwer (https://jitsi.github.io/jiwer/) というPythonのライブラリがあったので、メモ。

こんな感じで書けます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import jiwer
import jaconv

def main():
    reference = "hello world"
    hypothesis = "hello duck"

    error = jiwer.wer(reference, hypothesis)
    print(error)
    error = jiwer.cer(reference, hypothesis)
    print(error)
    print("--------------")
    output = jiwer.process_characters(reference, hypothesis)
    print(jiwer.visualize_alignment(output))

    print("--------------")
    output = jiwer.process_characters("あいうえお", "あううお")
    prev_hyp = False
    for line in jiwer.visualize_alignment(output).split("\n"):
        zen = False
        if prev_hyp:
            prev_hyp = False
            zen = True
        if line[:4] == "REF:":
            zen = True
        if line[:4] == "HYP:":
            zen = True
            prev_hyp = True
        if zen:
            line = jaconv.h2z(line, kana=True, digit=True, ascii=True)
        print(line)

if __name__ == "__main__":
    main()
結果は
0.5
0.45454545454545453
--------------
sentence 1
REF: hello world
HYP: hello duck*
           SSSSD

number of sentences: 1
substitutions=4 deletions=1 insertions=0 hits=6

cer=45.45%

--------------
sentence 1
REF: あいうえお
HYP: あうう*お
      S D 

number of sentences: 1
substitutions=1 deletions=1 insertions=0 hits=3

cer=40.00%

のようになります。

0 件のコメント :