File size: 8,223 Bytes
1e012a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import json
import os
import pandas as pd
import plotly.graph_objects as go
from typing import Dict, List

def get_model_names() -> List[str]:
    """从evaluation_results文件夹获取所有模型名称"""
    model_names = []
    for item in os.listdir('.'):
        if item.startswith('evaluation_results.') and os.path.isdir(item):
            model_name = item.replace('evaluation_results.', '')
            model_names.append(model_name)
    return sorted(model_names)  # 排序以保持顺序一致

def load_report(model_name: str) -> Dict:
    """加载模型的评测报告"""
    report_path = f"evaluation_results.{model_name}/evaluation_report.json"
    with open(report_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def create_comparison_tables() -> Dict[str, pd.DataFrame]:
    """创建不同维度的对比表格"""
    # 动态获取所有模型名称
    models = get_model_names()
    
    # 加载所有报告
    reports = {model: load_report(model) for model in models}
    
    # 1. 整体表现
    overall_data = []
    for model, report in reports.items():
        overall = report['overall']
        overall_data.append({
            '模型': model,
            '总题数': overall['total'],
            '正确数': overall['correct'],
            '准确率': f"{overall['accuracy']*100:.2f}%"
        })
    overall_df = pd.DataFrame(overall_data)
    
    # 2. 按题型分类
    type_data = []
    for model, report in reports.items():
        for q_type, metrics in report['by_type'].items():
            type_data.append({
                '模型': model,
                '题型': q_type,
                '总题数': metrics['total'],
                '正确数': metrics['correct'],
                '准确率': f"{metrics['accuracy']*100:.2f}%"
            })
    type_df = pd.DataFrame(type_data)
    
    # 3. 按难度分类
    difficulty_data = []
    difficulty_order = ['easy', 'medium', 'hard']  # 预定义难度顺序
    for model, report in reports.items():
        for diff in difficulty_order:
            if diff in report['by_difficulty']:
                metrics = report['by_difficulty'][diff]
                difficulty_data.append({
                    '模型': model,
                    '难度': diff,
                    '总题数': metrics['total'],
                    '正确数': metrics['correct'],
                    '准确率': f"{metrics['accuracy']*100:.2f}%"
                })
    difficulty_df = pd.DataFrame(difficulty_data)
    
    # 4. 按朝代分类
    dynasty_data = []
    for model, report in reports.items():
        for dynasty, metrics in report['by_dynasty'].items():
            dynasty_data.append({
                '模型': model,
                '朝代': dynasty if dynasty else "未知",
                '总题数': metrics['total'],
                '正确数': metrics['correct'],
                '准确率': f"{metrics['accuracy']*100:.2f}%"
            })
    dynasty_df = pd.DataFrame(dynasty_data)
    
    return {
        'overall': overall_df,
        'by_type': type_df,
        'by_difficulty': difficulty_df,
        'by_dynasty': dynasty_df
    }

def plot_accuracy_comparison(dfs: Dict[str, pd.DataFrame]):
    """绘制准确率对比图"""
    # 1. 整体准确率对比
    fig = go.Figure(data=[
        go.Bar(
            name='整体准确率',
            x=dfs['overall']['模型'],
            y=[float(x.strip('%')) for x in dfs['overall']['准确率']],
            text=dfs['overall']['准确率'],
            textposition='auto',
        )
    ])
    fig.update_layout(
        title='各模型整体准确率对比',
        yaxis_title='准确率 (%)',
        yaxis_range=[0, 100],
        template='plotly_white'
    )
    fig.write_html('accuracy_comparison.html')
    
    # 2. 按题型的准确率对比
    type_pivot = pd.pivot_table(
        dfs['by_type'],
        values='准确率',
        index='题型',
        columns='模型',
        aggfunc=lambda x: x
    )
    fig = go.Figure(data=[
        go.Bar(
            name=model,
            x=type_pivot.index,
            y=[float(x.strip('%')) for x in type_pivot[model]],
            text=type_pivot[model],
            textposition='auto',
        ) for model in type_pivot.columns
    ])
    fig.update_layout(
        title='各模型在不同题型上的准确率对比',
        yaxis_title='准确率 (%)',
        yaxis_range=[0, 100],
        barmode='group',
        template='plotly_white',
        height=600  # 增加图表高度
    )
    fig.write_html('accuracy_by_type.html')

    # 3. 按难度的准确率对比
    difficulty_pivot = pd.pivot_table(
        dfs['by_difficulty'],
        values='准确率',
        index='难度',
        columns='模型',
        aggfunc=lambda x: x
    )
    # 确保难度顺序正确
    difficulty_order = ['easy', 'medium', 'hard']
    difficulty_pivot = difficulty_pivot.reindex(difficulty_order)
    
    fig = go.Figure(data=[
        go.Bar(
            name=model,
            x=difficulty_pivot.index,
            y=[float(x.strip('%')) for x in difficulty_pivot[model]],
            text=difficulty_pivot[model],
            textposition='auto',
        ) for model in difficulty_pivot.columns
    ])
    fig.update_layout(
        title='各模型在不同难度上的准确率对比',
        yaxis_title='准确率 (%)',
        yaxis_range=[0, 100],
        barmode='group',
        template='plotly_white'
    )
    fig.write_html('accuracy_by_difficulty.html')

    # 4. 按朝代的准确率对比
    dynasty_pivot = pd.pivot_table(
        dfs['by_dynasty'],
        values='准确率',
        index='朝代',
        columns='模型',
        aggfunc=lambda x: x
    )
    fig = go.Figure(data=[
        go.Bar(
            name=model,
            x=dynasty_pivot.index,
            y=[float(x.strip('%')) for x in dynasty_pivot[model]],
            text=dynasty_pivot[model],
            textposition='auto',
        ) for model in dynasty_pivot.columns
    ])
    fig.update_layout(
        title='各模型在不同朝代诗词上的准确率对比',
        yaxis_title='准确率 (%)',
        yaxis_range=[0, 100],
        barmode='group',
        template='plotly_white',
        height=800  # 增加图表高度以适应更多朝代
    )
    fig.write_html('accuracy_by_dynasty.html')

    # 5. 雷达图对比
    categories = ['整体'] + list(type_pivot.index)
    fig = go.Figure()
    
    for model in dfs['overall']['模型']:
        values = [float(dfs['overall'][dfs['overall']['模型']==model]['准确率'].iloc[0].strip('%'))]
        for q_type in type_pivot.index:
            values.append(float(type_pivot[model][q_type].strip('%')))
        
        fig.add_trace(go.Scatterpolar(
            r=values,
            theta=categories,
            name=model,
            fill='toself'
        ))

    fig.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 100]
            )),
        showlegend=True,
        title='各模型在不同维度的表现对比(雷达图)',
        template='plotly_white'
    )
    fig.write_html('radar_comparison.html')

def main():
    # 创建对比表格
    dfs = create_comparison_tables()
    
    # 保存为Excel文件
    with pd.ExcelWriter('model_comparison.xlsx') as writer:
        dfs['overall'].to_excel(writer, sheet_name='整体表现', index=False)
        dfs['by_type'].to_excel(writer, sheet_name='按题型分类', index=False)
        dfs['by_difficulty'].to_excel(writer, sheet_name='按难度分类', index=False)
        dfs['by_dynasty'].to_excel(writer, sheet_name='按朝代分类', index=False)
    
    # 打印表格
    print("\n整体表现:")
    print(dfs['overall'].to_string(index=False))
    
    print("\n按题型分类:")
    print(dfs['by_type'].to_string(index=False))
    
    print("\n按难度分类:")
    print(dfs['by_difficulty'].to_string(index=False))
    
    print("\n按朝代分类:")
    print(dfs['by_dynasty'].to_string(index=False))
    
    # 绘制对比图
    plot_accuracy_comparison(dfs)

if __name__ == '__main__':
    main()