|
| 1 | +#encoding=utf8 |
| 2 | +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 3 | + |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | + |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +''' |
| 16 | +Evaluation script for CMRC 2018 |
| 17 | +version: v5 - special |
| 18 | +Note: |
| 19 | +v5 - special: Evaluate on SQuAD-style CMRC 2018 Datasets |
| 20 | +v5: formatted output, add usage description |
| 21 | +v4: fixed segmentation issues |
| 22 | +''' |
| 23 | + |
| 24 | +import argparse |
| 25 | +import json |
| 26 | +import re |
| 27 | +import sys |
| 28 | +from collections import OrderedDict |
| 29 | +import nltk |
| 30 | + |
| 31 | + |
| 32 | +# split Chinese with English |
| 33 | +def mixed_segmentation(in_str, rm_punc=False): |
| 34 | + in_str = str(in_str).lower().strip() |
| 35 | + segs_out = [] |
| 36 | + temp_str = "" |
| 37 | + sp_char = [ |
| 38 | + '-', ':', '_', '*', '^', '/', '\\', '~', '`', '+', '=', ',', '。', ':', |
| 39 | + '?', '!', '“', '”', ';', '’', '《', '》', '……', '·', '、', '「', '」', '(', |
| 40 | + ')', '-', '~', '『', '』' |
| 41 | + ] |
| 42 | + for char in in_str: |
| 43 | + if rm_punc and char in sp_char: |
| 44 | + continue |
| 45 | + if re.search(r'[\u4e00-\u9fa5]', char) or char in sp_char: |
| 46 | + if temp_str != "": |
| 47 | + ss = nltk.word_tokenize(temp_str) |
| 48 | + segs_out.extend(ss) |
| 49 | + temp_str = "" |
| 50 | + segs_out.append(char) |
| 51 | + else: |
| 52 | + temp_str += char |
| 53 | + |
| 54 | + # handling last part |
| 55 | + if temp_str != "": |
| 56 | + ss = nltk.word_tokenize(temp_str) |
| 57 | + segs_out.extend(ss) |
| 58 | + |
| 59 | + return segs_out |
| 60 | + |
| 61 | + |
| 62 | +# remove punctuation |
| 63 | +def remove_punctuation(in_str): |
| 64 | + in_str = str(in_str).lower().strip() |
| 65 | + sp_char = [ |
| 66 | + '-', ':', '_', '*', '^', '/', '\\', '~', '`', '+', '=', ',', '。', ':', |
| 67 | + '?', '!', '“', '”', ';', '’', '《', '》', '……', '·', '、', '「', '」', '(', |
| 68 | + ')', '-', '~', '『', '』' |
| 69 | + ] |
| 70 | + out_segs = [] |
| 71 | + for char in in_str: |
| 72 | + if char in sp_char: |
| 73 | + continue |
| 74 | + else: |
| 75 | + out_segs.append(char) |
| 76 | + return ''.join(out_segs) |
| 77 | + |
| 78 | + |
| 79 | +# find longest common string |
| 80 | +def find_lcs(s1, s2): |
| 81 | + m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] |
| 82 | + mmax = 0 |
| 83 | + p = 0 |
| 84 | + for i in range(len(s1)): |
| 85 | + for j in range(len(s2)): |
| 86 | + if s1[i] == s2[j]: |
| 87 | + m[i + 1][j + 1] = m[i][j] + 1 |
| 88 | + if m[i + 1][j + 1] > mmax: |
| 89 | + mmax = m[i + 1][j + 1] |
| 90 | + p = i + 1 |
| 91 | + return s1[p - mmax:p], mmax |
| 92 | + |
| 93 | + |
| 94 | +# |
| 95 | +def evaluate(ground_truth_file, prediction_file): |
| 96 | + f1 = 0 |
| 97 | + em = 0 |
| 98 | + total_count = 0 |
| 99 | + skip_count = 0 |
| 100 | + for instance in ground_truth_file["data"]: |
| 101 | + # context_id = instance['context_id'].strip() |
| 102 | + # context_text = instance['context_text'].strip() |
| 103 | + for para in instance["paragraphs"]: |
| 104 | + for qas in para['qas']: |
| 105 | + total_count += 1 |
| 106 | + query_id = qas['id'].strip() |
| 107 | + query_text = qas['question'].strip() |
| 108 | + answers = [x["text"] for x in qas['answers']] |
| 109 | + |
| 110 | + if query_id not in prediction_file: |
| 111 | + sys.stderr.write('Unanswered question: {}\n'.format( |
| 112 | + query_id)) |
| 113 | + skip_count += 1 |
| 114 | + continue |
| 115 | + |
| 116 | + prediction = str(prediction_file[query_id]) |
| 117 | + f1 += calc_f1_score(answers, prediction) |
| 118 | + em += calc_em_score(answers, prediction) |
| 119 | + |
| 120 | + f1_score = 100.0 * f1 / total_count |
| 121 | + em_score = 100.0 * em / total_count |
| 122 | + return f1_score, em_score, total_count, skip_count |
| 123 | + |
| 124 | + |
| 125 | +def calc_f1_score(answers, prediction): |
| 126 | + f1_scores = [] |
| 127 | + for ans in answers: |
| 128 | + ans_segs = mixed_segmentation(ans, rm_punc=True) |
| 129 | + prediction_segs = mixed_segmentation(prediction, rm_punc=True) |
| 130 | + lcs, lcs_len = find_lcs(ans_segs, prediction_segs) |
| 131 | + if lcs_len == 0: |
| 132 | + f1_scores.append(0) |
| 133 | + continue |
| 134 | + precision = 1.0 * lcs_len / len(prediction_segs) |
| 135 | + recall = 1.0 * lcs_len / len(ans_segs) |
| 136 | + f1 = (2 * precision * recall) / (precision + recall) |
| 137 | + f1_scores.append(f1) |
| 138 | + return max(f1_scores) |
| 139 | + |
| 140 | + |
| 141 | +def calc_em_score(answers, prediction): |
| 142 | + em = 0 |
| 143 | + for ans in answers: |
| 144 | + ans_ = remove_punctuation(ans) |
| 145 | + prediction_ = remove_punctuation(prediction) |
| 146 | + if ans_ == prediction_: |
| 147 | + em = 1 |
| 148 | + break |
| 149 | + return em |
| 150 | + |
| 151 | + |
| 152 | +def get_result(ground_truth_file, prediction_file): |
| 153 | + ground_truth_file = json.load(open(ground_truth_file, 'rb')) |
| 154 | + prediction_file = json.load(open(prediction_file, 'rb')) |
| 155 | + F1, EM, TOTAL, SKIP = evaluate(ground_truth_file, prediction_file) |
| 156 | + AVG = (EM + F1) * 0.5 |
| 157 | + output_result = OrderedDict() |
| 158 | + output_result['AVERAGE'] = '%.3f' % AVG |
| 159 | + output_result['F1'] = '%.3f' % F1 |
| 160 | + output_result['EM'] = '%.3f' % EM |
| 161 | + output_result['TOTAL'] = TOTAL |
| 162 | + output_result['SKIP'] = SKIP |
| 163 | + print(json.dumps(output_result)) |
| 164 | + return output_result |
| 165 | + |
| 166 | + |
| 167 | +if __name__ == '__main__': |
| 168 | + parser = argparse.ArgumentParser( |
| 169 | + description='Evaluation Script for CMRC 2018') |
| 170 | + parser.add_argument( |
| 171 | + '--dataset_file', |
| 172 | + default="cmrc2018_public/dev.json", |
| 173 | + help='Official dataset file') |
| 174 | + parser.add_argument( |
| 175 | + '--prediction_file', |
| 176 | + default="all_predictions.json", |
| 177 | + help='Your prediction File') |
| 178 | + args = parser.parse_args() |
| 179 | + ground_truth_file = json.load(open(args.dataset_file, 'rb')) |
| 180 | + prediction_file = json.load(open(args.prediction_file, 'rb')) |
| 181 | + F1, EM, TOTAL, SKIP = evaluate(ground_truth_file, prediction_file) |
| 182 | + AVG = (EM + F1) * 0.5 |
| 183 | + output_result = OrderedDict() |
| 184 | + output_result['AVERAGE'] = '%.3f' % AVG |
| 185 | + output_result['F1'] = '%.3f' % F1 |
| 186 | + output_result['EM'] = '%.3f' % EM |
| 187 | + output_result['TOTAL'] = TOTAL |
| 188 | + output_result['SKIP'] = SKIP |
| 189 | + output_result['FILE'] = args.prediction_file |
| 190 | + print(json.dumps(output_result)) |
0 commit comments