import json import re import argparse # 字母到数字的映射 letter_to_number = { "A": "0", "B": "1", "C": "2", "D": "3" } # 函数:从text中提取模型预测的答案 def extract_predicted_answer(text): # 匹配类似 "A", "B", "C", "D" 的答案 match = re.search(r'\b[A-D]\b', text) if match: return match.group(0) return None # 函数:计算正确率 def calculate_accuracy(file_path): total = 0 correct = 0 # 逐行读取JSONL文件 with open(file_path, 'r', encoding='utf-8') as file: for line in file: item = json.loads(line) total += 1 pred_letter = extract_predicted_answer(item['text']) # 从text中提取答案 true_answer = item['answer'] # 正确答案 if pred_letter: pred = letter_to_number[pred_letter] # 映射到数字 (1-4) true_answer = str(item['answer']) # 转为字符串,避免类型问题 if pred == true_answer: correct += 1 # 计算正确率 accuracy = (correct / total) * 100 # 打印结果 print(f"总样本数: {total}") print(f"正确样本数: {correct}") print(f"错误样本数: {total - correct}") print(f"正确率: {accuracy:.2f}%") # 主程序 if __name__ == "__main__": # 使用 argparse 获取命令行参数 parser = argparse.ArgumentParser(description="Evaluate model accuracy from JSONL file.") parser.add_argument("file_path", type=str, help="Path to the JSONL file containing inference results.") args = parser.parse_args() # 调用计算函数 calculate_accuracy(args.file_path)