如何用绘图工具复现论文中的分布偏移结果?
精准复现分布偏移图表及分析方案
一、数据预处理(关键前提)
确保你的数据是长格式(long-form),适配seaborn的绘图逻辑。示例数据结构如下:
| shift_ratio | metric_type | f1_score |
|---|---|---|
| 0.0 | Model F1 | 0.89 |
| 0.0 | Human F1 | 0.92 |
| 0.2 | Model F1 | 0.85 |
| 0.2 | Human F1 | 0.91 |
| ... | ... | ... |
如果数据是宽格式(每列对应一个指标),用pd.melt()转换:
import pandas as pd # 假设宽格式数据df包含列:shift_ratio, model_f1, human_f1 df_long = pd.melt(df, id_vars='shift_ratio', value_vars=['model_f1', 'human_f1'], var_name='metric_type', value_name='f1_score') # 重命名标签匹配论文样式 df_long['metric_type'] = df_long['metric_type'].replace({'model_f1': 'Model F1', 'human_f1': 'Human F1'})
二、复现论文图表样式(lineplot + regplot组合)
针对seaborn绘图效果不达预期的问题,重点调整线条样式、标记、颜色、坐标轴配置,对齐论文风格:
import seaborn as sns import matplotlib.pyplot as plt # 设置全局样式(匹配论文的字体、线条宽度) sns.set_style("ticks") plt.rcParams['font.family'] = 'Arial' # 替换成论文使用的字体 plt.rcParams['lines.linewidth'] = 2 plt.rcParams['markers.size'] = 6 # 创建画布 fig, ax = plt.subplots(figsize=(8, 5)) # 1. 绘制带标记的折线图(展示原始数据点+趋势) sns.lineplot(data=df_long, x='shift_ratio', y='f1_score', hue='metric_type', style='metric_type', markers=True, ax=ax) # 2. 添加拟合回归线(对应regplot需求) model_data = df_long[df_long['metric_type'] == 'Model F1'] human_data = df_long[df_long['metric_type'] == 'Human F1'] sns.regplot(data=model_data, x='shift_ratio', y='f1_score', scatter=False, color=sns.color_palette()[0], line_kws={'linestyle': '--'}, ax=ax) sns.regplot(data=human_data, x='shift_ratio', y='f1_score', scatter=False, color=sns.color_palette()[1], line_kws={'linestyle': ':'}, ax=ax) # 3. 对齐论文的坐标轴与标签 ax.set_xlabel('Distribution Shift Ratio', fontsize=12) ax.set_ylabel('F1 Score', fontsize=12) ax.set_title('Performance vs. Distribution Shift', fontsize=14) ax.legend(title='Metric', bbox_to_anchor=(1.05, 1), loc='upper left') # 调整图例位置 ax.set_ylim(0.5, 1.0) # 根据论文数据范围设置y轴边界 sns.despine() # 移除多余边框 plt.tight_layout() plt.show()
样式调整关键点:
- 线条/标记匹配:用
style参数区分不同指标的线条样式,markers=True显示数据点,和论文的标记形状对齐 - 拟合线样式:通过
line_kws设置虚线/点线,区分模型和人类的拟合趋势 - 字体与刻度:统一字体、坐标轴标签大小,确保和论文排版一致
三、分布偏移分析
从图表中可提取以下关键结论:
- 趋势对比:观察两条折线的下降斜率——若Model F1的下降幅度远大于Human F1,说明模型对分布偏移的鲁棒性弱于人类
- 量化分析:计算偏移程度与F1值的相关系数,量化偏移对性能的影响:
# 计算皮尔逊相关系数(负相关表示偏移越大,F1越低) model_corr = model_data['shift_ratio'].corr(model_data['f1_score']) human_corr = human_data['shift_ratio'].corr(human_data['f1_score']) print(f"Model F1与偏移程度的相关系数: {model_corr:.2f}") print(f"Human F1与偏移程度的相关系数: {human_corr:.2f}")
- 拐点分析:找到模型性能骤降的偏移阈值(比如shift_ratio=0.4时F1突然下跌),可标注在图表中:
ax.axvline(x=0.4, color='gray', linestyle='-.', label='Performance Drop Threshold') ax.legend()
内容的提问来源于stack exchange,提问作者user325923
相关产品推荐
相关产品推荐

