happyme531's picture
Upload 5 files
1e012a3 verified
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()