compute_wer.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import os
  2. import numpy as np
  3. import sys
  4. def compute_wer(ref_file,
  5. hyp_file,
  6. cer_detail_file):
  7. rst = {
  8. 'Wrd': 0,
  9. 'Corr': 0,
  10. 'Ins': 0,
  11. 'Del': 0,
  12. 'Sub': 0,
  13. 'Snt': 0,
  14. 'Err': 0.0,
  15. 'S.Err': 0.0,
  16. 'wrong_words': 0,
  17. 'wrong_sentences': 0
  18. }
  19. hyp_dict = {}
  20. ref_dict = {}
  21. with open(hyp_file, 'r') as hyp_reader:
  22. for line in hyp_reader:
  23. key = line.strip().split()[0]
  24. value = line.strip().split()[1:]
  25. hyp_dict[key] = value
  26. with open(ref_file, 'r') as ref_reader:
  27. for line in ref_reader:
  28. key = line.strip().split()[0]
  29. value = line.strip().split()[1:]
  30. ref_dict[key] = value
  31. cer_detail_writer = open(cer_detail_file, 'w')
  32. for hyp_key in hyp_dict:
  33. if hyp_key in ref_dict:
  34. out_item = compute_wer_by_line(hyp_dict[hyp_key], ref_dict[hyp_key])
  35. rst['Wrd'] += out_item['nwords']
  36. rst['Corr'] += out_item['cor']
  37. rst['wrong_words'] += out_item['wrong']
  38. rst['Ins'] += out_item['ins']
  39. rst['Del'] += out_item['del']
  40. rst['Sub'] += out_item['sub']
  41. rst['Snt'] += 1
  42. if out_item['wrong'] > 0:
  43. rst['wrong_sentences'] += 1
  44. cer_detail_writer.write(hyp_key + print_cer_detail(out_item) + '\n')
  45. cer_detail_writer.write("ref:" + '\t' + " ".join(list(map(lambda x: x.lower(), ref_dict[hyp_key]))) + '\n')
  46. cer_detail_writer.write("hyp:" + '\t' + " ".join(list(map(lambda x: x.lower(), hyp_dict[hyp_key]))) + '\n')
  47. if rst['Wrd'] > 0:
  48. rst['Err'] = round(rst['wrong_words'] * 100 / rst['Wrd'], 2)
  49. if rst['Snt'] > 0:
  50. rst['S.Err'] = round(rst['wrong_sentences'] * 100 / rst['Snt'], 2)
  51. cer_detail_writer.write('\n')
  52. cer_detail_writer.write("%WER " + str(rst['Err']) + " [ " + str(rst['wrong_words'])+ " / " + str(rst['Wrd']) +
  53. ", " + str(rst['Ins']) + " ins, " + str(rst['Del']) + " del, " + str(rst['Sub']) + " sub ]" + '\n')
  54. cer_detail_writer.write("%SER " + str(rst['S.Err']) + " [ " + str(rst['wrong_sentences']) + " / " + str(rst['Snt']) + " ]" + '\n')
  55. cer_detail_writer.write("Scored " + str(len(hyp_dict)) + " sentences, " + str(len(hyp_dict) - rst['Snt']) + " not present in hyp." + '\n')
  56. def compute_wer_by_line(hyp,
  57. ref):
  58. hyp = list(map(lambda x: x.lower(), hyp))
  59. ref = list(map(lambda x: x.lower(), ref))
  60. len_hyp = len(hyp)
  61. len_ref = len(ref)
  62. cost_matrix = np.zeros((len_hyp + 1, len_ref + 1), dtype=np.int16)
  63. ops_matrix = np.zeros((len_hyp + 1, len_ref + 1), dtype=np.int8)
  64. for i in range(len_hyp + 1):
  65. cost_matrix[i][0] = i
  66. for j in range(len_ref + 1):
  67. cost_matrix[0][j] = j
  68. for i in range(1, len_hyp + 1):
  69. for j in range(1, len_ref + 1):
  70. if hyp[i - 1] == ref[j - 1]:
  71. cost_matrix[i][j] = cost_matrix[i - 1][j - 1]
  72. else:
  73. substitution = cost_matrix[i - 1][j - 1] + 1
  74. insertion = cost_matrix[i - 1][j] + 1
  75. deletion = cost_matrix[i][j - 1] + 1
  76. compare_val = [substitution, insertion, deletion]
  77. min_val = min(compare_val)
  78. operation_idx = compare_val.index(min_val) + 1
  79. cost_matrix[i][j] = min_val
  80. ops_matrix[i][j] = operation_idx
  81. match_idx = []
  82. i = len_hyp
  83. j = len_ref
  84. rst = {
  85. 'nwords': len_ref,
  86. 'cor': 0,
  87. 'wrong': 0,
  88. 'ins': 0,
  89. 'del': 0,
  90. 'sub': 0
  91. }
  92. while i >= 0 or j >= 0:
  93. i_idx = max(0, i)
  94. j_idx = max(0, j)
  95. if ops_matrix[i_idx][j_idx] == 0: # correct
  96. if i - 1 >= 0 and j - 1 >= 0:
  97. match_idx.append((j - 1, i - 1))
  98. rst['cor'] += 1
  99. i -= 1
  100. j -= 1
  101. elif ops_matrix[i_idx][j_idx] == 2: # insert
  102. i -= 1
  103. rst['ins'] += 1
  104. elif ops_matrix[i_idx][j_idx] == 3: # delete
  105. j -= 1
  106. rst['del'] += 1
  107. elif ops_matrix[i_idx][j_idx] == 1: # substitute
  108. i -= 1
  109. j -= 1
  110. rst['sub'] += 1
  111. if i < 0 and j >= 0:
  112. rst['del'] += 1
  113. elif j < 0 and i >= 0:
  114. rst['ins'] += 1
  115. match_idx.reverse()
  116. wrong_cnt = cost_matrix[len_hyp][len_ref]
  117. rst['wrong'] = wrong_cnt
  118. return rst
  119. def print_cer_detail(rst):
  120. return ("(" + "nwords=" + str(rst['nwords']) + ",cor=" + str(rst['cor'])
  121. + ",ins=" + str(rst['ins']) + ",del=" + str(rst['del']) + ",sub="
  122. + str(rst['sub']) + ") corr:" + '{:.2%}'.format(rst['cor']/rst['nwords'])
  123. + ",cer:" + '{:.2%}'.format(rst['wrong']/rst['nwords']))
  124. if __name__ == '__main__':
  125. if len(sys.argv) != 4:
  126. print("usage : python compute-wer.py test.ref test.hyp test.wer")
  127. sys.exit(0)
  128. ref_file = sys.argv[1]
  129. hyp_file = sys.argv[2]
  130. cer_detail_file = sys.argv[3]
  131. compute_wer(ref_file, hyp_file, cer_detail_file)