Upload 29 files
Browse filesFiles changed (29)
- plot/ECEandAUC.pyAdded+423
- plot/两种标注方式对比.pyAdded+260
- plot/任务分类山脊图_逐轮次准确率.pyAdded+457
- plot/桑基图.pyAdded+421
- plot/欺骗窗口.pyAdded+470
- plot/熵值图.pyAdded+289
- plot/逐轮次准确率.pyAdded+277
- run_all_plots.pyAdded+67
- utils/__init__.pyAdded+39
- utils/__pycache__/__init__.cpython-310.pycAdded
- utils/__pycache__/__init__.cpython-313.pycAdded
- utils/__pycache__/annotator_data.cpython-310.pycAdded
- utils/__pycache__/deception_data.cpython-310.pycAdded
- utils/__pycache__/deception_data_per_iteration.cpython-310.pycAdded
- utils/__pycache__/entroy.cpython-310.pycAdded
- utils/__pycache__/kappa.cpython-310.pycAdded
- utils/__pycache__/metrics.cpython-310.pycAdded
- utils/__pycache__/metrics.cpython-313.pycAdded
- utils/__pycache__/plot_style.cpython-310.pycAdded
- utils/__pycache__/tools.cpython-310.pycAdded
- utils/__pycache__/tools.cpython-313.pycAdded
- utils/annotator_data.pyAdded+70
- utils/deception_data.pyAdded+392
- utils/deception_data_per_iteration.pyAdded+173
- utils/entroy.pyAdded+86
- utils/kappa.pyAdded+158
- utils/metrics.pyAdded+82
- utils/plot_style.pyAdded+100
- utils/tools.pyAdded+49
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423"""ECE (Expected Calibration Error) 和 AUC (Area Under Curve) 可视化脚本
功能:分析标注员在欺骗检测任务中的表现- ECE:评估标注员的置信度校准质量- AUC:评估标注员的判别能力- 按 QC 通过次数分组,观察不同质量水平的标注员表现差异"""
import osimport sysimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib.patheffects as pefrom matplotlib.patches import Patchfrom matplotlib.lines import Line2D
# 设置项目路径CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, '..'))sys.path.append(PROJECT_ROOT)
from utils.deception_data import ( load_is_deception_humans, load_confidences, load_ground_truth_deception_expert, load_data)from utils.metrics import calculate_ece, calculate_aucfrom utils.plot_style import apply_style, save_figure
# =============================================================================# 常量配置# =============================================================================DATA_PATH = os.path.join(PROJECT_ROOT, 'data', 'task3_merged010203_40x158_102.json')OUTPUT_DIR = os.path.join(PROJECT_ROOT, 'output')
# 绑定风格配置(由公共样式模块 RC_BASE 统一管理,此处仅保留本图特有覆盖项)PLOT_STYLE_EXTRA = {}
# 视觉样式配置STYLE_CONFIG = { 'left': { 'main': '#2878B5', 'fill': '#9AC9DB', 'edge': '#2878B5', 'marker': 'o', 'linestyle': '-', 'hatch': None }, 'right': { 'main': '#C82423', 'fill': '#F8AC8C', 'edge': '#C82423', 'marker': 's', 'linestyle': '--', 'hatch': '///' }}
# 颜色配置COLORS = { 'passed': '#78BFA6', 'passed_edge': '#5FA68E', 'failed': '#F0A07C', 'failed_edge': '#D9825D',}
# =============================================================================# 数据处理函数# =============================================================================def load_and_preprocess_data(data_path: str) -> tuple: """ 加载并预处理数据 Returns: tuple: (ece_data, auc_data, total_counts, counts_list) """ # 加载原始数据 is_deception = load_is_deception_humans(data_path)[2] confidence = load_confidences(data_path)[2] is_deception_full = load_data(data_path)[2] ground_truth = load_ground_truth_deception_expert(data_path) # 计算任务通过统计 length = is_deception_full.map(lambda x: len(x)) counts = length.stack(future_stack=True).value_counts(dropna=False) counts_list = counts.sort_index().values.tolist() total_counts = [sum(counts_list[i:]) for i in range(len(counts_list))] # 构建带方向的置信度 per_confidence = _build_directional_confidence(is_deception, confidence) # 计算 ECE 和 AUC ece_data, auc_data = _calculate_metrics(per_confidence, ground_truth) return ece_data, auc_data, total_counts, counts_list
def _build_directional_confidence(is_deception: pd.DataFrame, confidence: pd.DataFrame) -> list: """ 构建带方向的置信度数据 将置信度与判断方向结合:正确判断为正,错误判断为负 """ is_deception_3d = np.array(is_deception.values.tolist()) confidence_3d = np.array(confidence.values.tolist()) per_confidence = [] for i in range(5): now_confidence = pd.DataFrame( confidence_3d[:, :, i], index=confidence.index, columns=confidence.columns ) now_is_deception = pd.DataFrame( is_deception_3d[:, :, i], index=is_deception.index, columns=is_deception.columns ) # 将 0/1 转换为 -1/+1 作为方向掩码 mask = (now_is_deception - 0.5) * 2 now_confidence = now_confidence * mask per_confidence.append(now_confidence) return per_confidence
def _calculate_metrics(per_confidence: list, ground_truth) -> tuple: """计算每轮的 ECE 和 AUC 指标""" ece_data = [] auc_data = [] for i in range(5): ece_tmp = per_confidence[i].apply( lambda x: calculate_ece(ground_truth, x), axis=0 ).values.tolist() auc_tmp = per_confidence[i].apply( lambda x: calculate_auc(ground_truth, x), axis=0 ).values.tolist() ece_data.append(ece_tmp) auc_data.append(auc_tmp) return ece_data, auc_data
# =============================================================================# 绑定函数# =============================================================================def plot_dual_axis_with_bars( data_left: list, data_right: list, total_tasks: np.ndarray, passed_tasks: np.ndarray, labels: tuple = ('Metric A', 'Metric B'), output_path: str = None): """ 绑定双轴图表,包含顶部堆叠柱状图和底部 ECE/AUC 箱线图 Args: data_left: 左轴数据 (ECE) data_right: 右轴数据 (AUC) total_tasks: 总任务数 passed_tasks: 通过的任务数 labels: 轴标签元组 output_path: 输出路径,如果为 None 则显示图片 """ apply_style(PLOT_STYLE_EXTRA) total_tasks = np.asarray(total_tasks, dtype=float) passed_tasks = np.asarray(passed_tasks, dtype=float) if total_tasks.shape != passed_tasks.shape: raise ValueError("total_tasks 和 passed_tasks 的长度必须一致。") # X 轴刻度 x_ticks = np.arange(1, len(total_tasks) + 1) failed_tasks = total_tasks - passed_tasks # 创建画布 fig, (ax_bar, ax1) = plt.subplots( nrows=2, ncols=1, figsize=(8, 8), dpi=300, sharex=True, gridspec_kw={'height_ratios': [1, 5], 'hspace': 0.05} ) # 绑定顶部堆叠柱状图 _plot_stacked_bar(ax_bar, x_ticks, passed_tasks, failed_tasks, total_tasks) # 绑定底部双轴主图 ax2 = ax1.twinx() _plot_main_chart(ax1, ax2, x_ticks, data_left, data_right, labels) # 添加图例 _add_legends(ax_bar, ax1, labels) # 调整布局 plt.subplots_adjust(top=0.90, bottom=0.18) # 保存或显示(同时保存 PNG 和 PDF) if output_path: save_figure(fig, output_path) else: plt.show() plt.close(fig)
def _plot_stacked_bar(ax, x_ticks, passed_tasks, failed_tasks, total_tasks): """绑定顶部堆叠柱状图""" bar_width = 0.32 # 绘制通过/未通过柱状图 ax.bar( x_ticks, passed_tasks, bar_width, color=COLORS['passed'], edgecolor=COLORS['passed_edge'], linewidth=1.0, alpha=0.90, zorder=2 ) ax.bar( x_ticks, failed_tasks, bar_width, bottom=passed_tasks, color=COLORS['failed'], edgecolor=COLORS['failed_edge'], linewidth=1.0, alpha=0.90, zorder=2, hatch='///' ) # 基线 ax.axhline(0, color='#D0D0D0', linewidth=1.0, zorder=1) # 总数标注 max_total = np.max(total_tasks) if len(total_tasks) else 1.0 text_fx = [pe.withStroke(linewidth=3, foreground='white', alpha=0.95)] for i, total in enumerate(total_tasks): ax.text( x_ticks[i], total + (max_total * 0.030), f"{int(total)}", ha='center', va='bottom', fontsize=9, color='#333333', path_effects=text_fx, zorder=4 ) # 累计通过率折线 ax_r = ax.twinx() initial_total = max(float(total_tasks[0]), 1e-12) cum_pass = np.cumsum(passed_tasks) cum_rate = np.clip(cum_pass / initial_total, 0, 1.0) ax_r.plot( x_ticks, cum_rate, color='#333333', linewidth=2.0, marker='D', markersize=4.5, markerfacecolor='white', markeredgewidth=1.2, zorder=5 ) # 累计通过率标注 for x, r in zip(x_ticks, cum_rate): ax_r.annotate( f"{r*100:.0f}%", xy=(x, r), xytext=(0, 6), textcoords="offset points", ha="center", va="bottom", fontsize=7.5, color="#666666", alpha=0.85 ) # 设置右轴样式 ax_r.set_ylim(0, 1.05) ax_r.set_yticks([0, 0.5, 1.0]) ax_r.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1.0, decimals=0)) ax_r.tick_params(axis='y', labelsize=8.5, colors='#666666', length=2.5, direction='in') ax_r.spines['top'].set_visible(False) ax_r.spines['left'].set_visible(False) ax_r.spines['right'].set_color('#BFBFBF') ax_r.spines['right'].set_linewidth(1.2) ax_r.set_ylabel( "Cum. Pass Rate", fontsize=10, color='#666666', labelpad=10, rotation=270, fontweight='bold' ) # 设置左轴样式 ax.set_yticks([]) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_color('#BFBFBF') ax.spines['bottom'].set_linewidth(1.2) plt.setp(ax.get_xticklabels(), visible=False) ax.set_ylim(0, max_total * 1.14)
def _plot_main_chart(ax1, ax2, x_ticks, data_left, data_right, labels): """绘制底部双轴主图(ECE 和 AUC)""" width = 0.18 def plot_on_axis(ax, data, config, label_name, pos_offset, y_fmt='%.2f'): positions = x_ticks + pos_offset mean_val = np.array([np.mean(d) for d in data]) std_val = np.array([np.std(d) for d in data]) # 标准差区域 ax.fill_between( positions, mean_val - std_val, mean_val + std_val, color=config['main'], alpha=0.08, zorder=0, linewidth=0 ) # 箱线图 bp = ax.boxplot( data, positions=positions, widths=width, patch_artist=True, showfliers=False, zorder=2, boxprops=dict( facecolor=config['fill'], edgecolor=config['edge'], linewidth=1.2, alpha=0.8 ), whiskerprops=dict(color=config['edge'], linewidth=1.2), capprops=dict(visible=False), medianprops=dict(color=config['main'], linewidth=1.5) ) if config['hatch']: for patch in bp['boxes']: patch.set_hatch(config['hatch']) # 均值折线 line, = ax.plot( positions, mean_val, color=config['main'], label=label_name, linewidth=2, linestyle=config['linestyle'], marker=config['marker'], markersize=7, markerfacecolor='white', markeredgewidth=1.5, zorder=3 ) ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(y_fmt)) return line # 绑定左轴 (ECE) 和右轴 (AUC) l1 = plot_on_axis(ax1, data_left, STYLE_CONFIG['left'], labels[0], pos_offset=0, y_fmt='%.2f') l2 = plot_on_axis(ax2, data_right, STYLE_CONFIG['right'], labels[1], pos_offset=0, y_fmt='%.1f') # 设置 X 轴 ax1.set_xticks(x_ticks) ax1.set_xticklabels([str(i) for i in x_ticks], fontsize=11, fontweight='bold') ax1.set_xlim(x_ticks[0] - 0.5, x_ticks[-1] + 0.5) ax1.set_xlabel('QC Pass Count', fontsize=12, labelpad=10, fontweight='bold') # 设置左 Y 轴 (ECE) ax1.set_ylabel(labels[0], fontsize=12, color=STYLE_CONFIG['left']['main'], labelpad=10, fontweight='bold') ax1.tick_params(axis='y', colors=STYLE_CONFIG['left']['main'], labelsize=10) ax1.spines['left'].set_color(STYLE_CONFIG['left']['main']) ax1.spines['left'].set_linewidth(2) ax1.set_ylim(0.0, 0.2) ax1.set_yticks(np.arange(0.0, 0.25, 0.05)) # 设置右 Y 轴 (AUC) ax2.set_ylabel(labels[1], fontsize=12, color=STYLE_CONFIG['right']['main'], rotation=270, labelpad=20, fontweight='bold') ax2.tick_params(axis='y', colors=STYLE_CONFIG['right']['main'], labelsize=10) ax2.spines['right'].set_color(STYLE_CONFIG['right']['main']) ax2.spines['right'].set_linewidth(2) ax2.set_ylim(0.6, 1.0) ax2.set_yticks(np.arange(0.6, 1.05, 0.1)) # 隐藏顶部边框,显示网格 ax1.spines['top'].set_visible(False) ax2.spines['top'].set_visible(False) ax1.grid(True, axis='y', alpha=0.3)
def _add_legends(ax_bar, ax1, labels): """添加图例""" # 顶部图例 top_handles = [ Patch(facecolor=COLORS['passed'], edgecolor=COLORS['passed_edge'], linewidth=1.0), Patch(facecolor=COLORS['failed'], edgecolor=COLORS['failed_edge'], linewidth=1.0, hatch='///'), Line2D([0], [0], color='#333333', linewidth=2.0, marker='D', markersize=4.5, markerfacecolor='white', markeredgewidth=1.2) ] ax_bar.legend( top_handles, ['Passed Tasks', 'Failed Tasks', 'Cumulative Pass Rate'], loc='lower center', bbox_to_anchor=(0.5, 1.18), ncol=3, fontsize=9, frameon=False, borderaxespad=0.0, handlelength=1.6, columnspacing=1.0, handletextpad=0.6 ) # 底部图例 bottom_handles = [ Line2D([0], [0], color=STYLE_CONFIG['left']['main'], linewidth=2, marker=STYLE_CONFIG['left']['marker'], markersize=7, markerfacecolor='white', markeredgewidth=1.5), Line2D([0], [0], color=STYLE_CONFIG['right']['main'], linewidth=2, linestyle=STYLE_CONFIG['right']['linestyle'], marker=STYLE_CONFIG['right']['marker'], markersize=7, markerfacecolor='white', markeredgewidth=1.5) ] ax1.legend( bottom_handles, labels, loc='upper center', bbox_to_anchor=(0.5, -0.18), ncol=2, fontsize=10, frameon=False, borderaxespad=0.0, handlelength=2.0, columnspacing=1.2, handletextpad=0.7 )
# =============================================================================# 主函数# =============================================================================def main(): """主函数入口""" # 加载和预处理数据 ece_data, auc_data, total_counts, counts_list = load_and_preprocess_data(DATA_PATH) # 设置输出路径 output_path = os.path.join(OUTPUT_DIR, 'ECE_AUC_分析图.png') # 绑定图表 plot_dual_axis_with_bars( data_left=ece_data, data_right=auc_data, total_tasks=np.array(total_counts), passed_tasks=np.array(counts_list), labels=('Expected Calibration Error (ECE)', 'Area Under Curve (AUC)'), output_path=output_path )
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""两种标注方式对比分析脚本
功能:对比 Global Annotation(全局标注)和 Per-turn Annotation(逐轮标注) 两种方式在欺骗性检测任务上的性能差异。
输出: 1. 混淆矩阵热力图:展示两种标注方式的预测结果分布 2. 哑铃图 + 密度分布:展示标注员准确率对比及统计显著性"""
# ============================================================# 导入依赖# ============================================================import osimport sysimport json
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.patches as mpatchesimport seaborn as snsfrom matplotlib.colors import ListedColormapfrom matplotlib.gridspec import GridSpecfrom scipy import stats
# 添加项目根目录到路径CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, '..'))sys.path.append(PROJECT_ROOT)from utils.deception_data import load_is_deception_humans, load_ground_truth_deceptionfrom utils.plot_style import apply_style, save_figure
# ============================================================# 配置常量# ============================================================OLD_DATA_PATH = os.path.join(PROJECT_ROOT, 'data', 'task3_04_22x49.json')NEW_DATA_PATH = os.path.join(PROJECT_ROOT, 'data', 'task3_01_40x49_102.json')OUTPUT_DIR = os.path.join(PROJECT_ROOT, 'output')
# 本图特有的样式覆盖项(基础样式由公共模块管理)PLOT_CONFIG_EXTRA = { 'font.size': 12, 'axes.linewidth': 1.0,}
COLORS = { 'tn': '#F7F7F7', # True Negative 'tp': '#8AC8EA', # True Positive 'fn': '#E31A1C', # False Negative 'fp': '#F3AF55', # False Positive 'global': '#7FABD1', 'perturn': '#E31A1C'}
# ============================================================# 数据加载# ============================================================def load_old_is_deception(path: str) -> pd.DataFrame: """加载旧版(全局标注)的 is_deception_human 数据""" is_deception_humans = {} with open(path, 'r', encoding='utf-8') as f: for item in json.load(f): annotator = item['annotator_id'] task = item['dialog_file'] if annotator not in is_deception_humans: is_deception_humans[annotator] = {} val = item.get('is_deception_human') is_deception_humans[annotator][task] = 1 if val == '存在' else (0 if val else np.nan) return pd.DataFrame(is_deception_humans)
# ============================================================# 数据处理# ============================================================def calculate_confusion_status(df: pd.DataFrame, ground_truth: pd.Series) -> pd.DataFrame: """计算混淆矩阵状态:TN=0, TP=1, FN=2, FP=3""" status_df = df.copy() gt = ground_truth.values.reshape(-1, 1) status_df[(df == 0) & (gt == 0)] = 0 # TN status_df[(df == 1) & (gt == 1)] = 1 # TP status_df[(df == 0) & (gt == 1)] = 2 # FN status_df[(df == 1) & (gt == 0)] = 3 # FP return status_df
def sort_by_accuracy(df: pd.DataFrame, ground_truth: pd.Series) -> tuple: """按任务难度和标注员准确率排序,返回 (任务列表, 标注员列表)""" accuracy = df.eq(ground_truth, axis=0) tasks = accuracy.mean(axis=1).sort_values(ascending=False).index.tolist() persons = accuracy.mean(axis=0).sort_values(ascending=False).index.tolist() return tasks, persons
# ============================================================# 可视化# ============================================================def add_axis_decoration(ax, axis_type: str, main_label: str, arrow_label: str): """为坐标轴添加装饰(标签和箭头)""" if axis_type == 'x': ax.annotate('', xy=(0.95, -0.025), xytext=(0.05, -0.025), xycoords='axes fraction', arrowprops=dict(arrowstyle="->", color="#555555", lw=1.0)) ax.text(0.5, -0.03, arrow_label, transform=ax.transAxes, ha='center', va='top', fontsize=9, color='#555555', style='italic') ax.text(0.5, -0.07, main_label, transform=ax.transAxes, ha='center', va='top', fontsize=12, fontweight='bold') else: # y ax.text(-0.15, 0.5, main_label, transform=ax.transAxes, ha='right', va='center', rotation=90, fontsize=12, fontweight='bold') ax.text(-0.09, 0.5, arrow_label, transform=ax.transAxes, ha='center', va='center', rotation=90, fontsize=9, color='#555555', style='italic') ax.annotate('', xy=(-0.05, 0.05), xytext=(-0.05, 0.95), xycoords='axes fraction', arrowprops=dict(arrowstyle="->", color="#555555", lw=1.0))
def plot_confusion_heatmaps(status_df1: pd.DataFrame, status_df2: pd.DataFrame, save_path: str): """绘制两种标注方式的混淆矩阵热力图""" colors_list = [COLORS['tn'], COLORS['tp'], COLORS['fn'], COLORS['fp']] cmap = ListedColormap(colors_list) fig, axes = plt.subplots(1, 2, figsize=(10, 15), sharey=True, gridspec_kw={'wspace': 0.1, 'bottom': 0.28, 'left': 0.15}) for ax, df, title in zip(axes, [status_df1, status_df2], ['Global Annotation', 'Per-turn Annotation']): sns.heatmap(df, ax=ax, cmap=cmap, cbar=False, linewidths=0.5, linecolor='white', square=False, annot=False) ax.set_title(title, fontsize=14, pad=15, fontweight='bold') ax.set_xticks([]) ax.set_yticks([]) ax.set_xlabel('') ax.set_ylabel('') add_axis_decoration(ax, 'x', 'Annotators', 'Accuracy Decreasing') add_axis_decoration(axes[0], 'y', 'Tasks', 'Difficulty Increasing') legend_patches = [ mpatches.Patch(color=colors_list[0], label='True Negative\n(Correct Non-Deceptive)'), mpatches.Patch(color=colors_list[1], label='True Positive\n(Correct Deceptive)'), mpatches.Patch(color=colors_list[2], label='False Negative\n(Missed Detection)'), mpatches.Patch(color=colors_list[3], label='False Positive\n(False Alarm)') ] fig.legend(handles=legend_patches, loc='lower center', bbox_to_anchor=(0.5, 0.17), ncol=4, fontsize=8, frameon=False, handlelength=1.5, handleheight=1.5) save_figure(fig, save_path) plt.close(fig)
def plot_dumbbell_with_distribution(acc_global: np.ndarray, acc_perturn: np.ndarray, save_path: str): """绘制哑铃图和密度分布图""" n = len(acc_global) mean_global, mean_perturn = np.mean(acc_global), np.mean(acc_perturn) _, p_val = stats.ttest_rel(acc_perturn, acc_global) fig = plt.figure(figsize=(8, 4), constrained_layout=True) gs = GridSpec(1, 2, width_ratios=[4, 1.2], wspace=0.05, figure=fig) ax_main = fig.add_subplot(gs[0]) ax_dist = fig.add_subplot(gs[1], sharey=ax_main) c_global, c_perturn = COLORS['global'], COLORS['perturn'] y_range = [0.5, 1.09] # 哑铃图 for i in range(n): ax_main.plot([i, i], [acc_global[i], acc_perturn[i]], color='#D9D9D9', lw=1.5, zorder=1) ax_main.scatter(i, acc_global[i], color=c_global, s=60, zorder=2, edgecolor='white', linewidth=0.5, label='Global' if i == 0 else "") ax_main.scatter(i, acc_perturn[i], color=c_perturn, s=60, zorder=3, edgecolor='white', linewidth=0.5, label='Per-turn' if i == 0 else "") ax_main.axhline(mean_global, color=c_global, ls='--', lw=1, alpha=0.5) ax_main.axhline(mean_perturn, color=c_perturn, ls='--', lw=1, alpha=0.5) ax_main.set(xticks=[], xlim=(-0.8, n - 0.2), ylim=y_range) ax_main.set_ylabel("Accuracy", fontweight='bold', fontsize=12) ax_main.set_xlabel("Annotators", fontweight='bold', fontsize=12) ax_main.legend(loc='upper left', frameon=False, ncol=2) # 密度分布 y_grid = np.linspace(y_range[0], 1.0, 500) for acc, color in [(acc_global, c_global), (acc_perturn, c_perturn)]: kernel = stats.gaussian_kde(acc) kde = kernel(y_grid) + kernel(2 - y_grid) # 镜像法处理边界 ax_dist.hist(acc, bins=10, density=True, orientation='horizontal', color=color, alpha=0.3, edgecolor='none') ax_dist.fill_betweenx(y_grid, 0, kde, color=color, alpha=0.3) ax_dist.plot(kde, y_grid, color=color, linewidth=1.5) ax_dist.axhline(mean_global, color=c_global, ls='--', lw=1.5) ax_dist.axhline(mean_perturn, color=c_perturn, ls='--', lw=1.5) ax_dist.set(xlabel="Density", xticks=[]) ax_dist.spines['left'].set_visible(False) ax_dist.tick_params(left=False, labelleft=False) # 统计信息 stats_text = ( f"$\\bf{{Global\\ Avg:}}$ {mean_global:.2%}\n" f"$\\bf{{Per-turn\\ Avg:}}$ {mean_perturn:.2%}\n" f"----------------\n" f"$\\bf{{Gain:}}$ +{mean_perturn - mean_global:.2%}\n" f"$\\bf{{P-value:}}$ {p_val:.4f}" ) ax_main.text(0.05, 0.05, stats_text, transform=ax_main.transAxes, fontsize=9, va='bottom', ha='left', zorder=10) save_figure(fig, save_path) plt.close(fig)
# ============================================================# 主函数# ============================================================def main(): apply_style(PLOT_CONFIG_EXTRA) os.makedirs(OUTPUT_DIR, exist_ok=True) # 加载数据 print("正在加载数据...") old_df = load_old_is_deception(OLD_DATA_PATH) annotator_ids = list(old_df.columns) new_df = load_is_deception_humans(NEW_DATA_PATH)[0][annotator_ids] ground_truth = load_ground_truth_deception(NEW_DATA_PATH) # 按准确率排序 tasks, persons = sort_by_accuracy(old_df, ground_truth) ground_truth = ground_truth.loc[tasks] old_df = old_df[persons].loc[tasks] new_df = new_df[persons].loc[tasks] # 计算混淆状态 status_old = calculate_confusion_status(old_df, ground_truth) status_new = calculate_confusion_status(new_df, ground_truth) # 绘图 print("正在生成可视化...") plot_confusion_heatmaps(status_old, status_new, os.path.join(OUTPUT_DIR, '混淆矩阵热力图'))
acc_old = ((status_old == 0) | (status_old == 1)).mean(axis=0).values acc_new = ((status_new == 0) | (status_new == 1)).mean(axis=0).values plot_dumbbell_with_distribution(acc_old, acc_new, os.path.join(OUTPUT_DIR, '准确率对比哑铃图')) print(f"全局标注平均准确率: {acc_old.mean():.2%}") print(f"逐轮标注平均准确率: {acc_new.mean():.2%}") print("完成!")
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457"""任务分类性能山脊图 + 逐轮次分场景准确率 合并可视化
左侧:按任务类别分析的性能山脊图(Precision, Recall, F1)右侧:逐轮次分场景准确率与置信度图"""
# ============================================================# 导入依赖# ============================================================import osimport sysimport jsonfrom collections import defaultdictfrom itertools import zip_longest
import numpy as npimport pandas as pdimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patchfrom sklearn.metrics import precision_score, recall_score, f1_scorefrom scipy.stats import gaussian_kde
# 项目路径配置CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.abspath(os.path.join(CURRENT_DIR, '..'))sys.path.append(PROJECT_ROOT)
from utils.deception_data import load_is_deception_humans, load_ground_truth_deception_expertfrom utils.deception_data_per_iteration import ( load_is_deception_humans as load_is_deception_humans_iter, load_ground_truth_iteration, load_confidence_humans)from utils.plot_style import apply_style, save_figure
# ============================================================# 常量配置# ============================================================DATA_DIR = os.path.join(PROJECT_ROOT, 'data')OUTPUT_DIR = os.path.join(PROJECT_ROOT, 'output')OUTPUT_BASENAME = '任务分类山脊图_逐轮次准确率'
# 数据文件路径DATA_FILES = { 'main': os.path.join(DATA_DIR, 'task3_merged010203_40x70_102_scene.json'), 'category_map': os.path.join(DATA_DIR, 'category_map_iter.json'),}
# 类别顺序(山脊图使用此顺序,逐轮次准确率使用反序)CATEGORY_ORDER = [ 'LifeDailyAffairs', 'HealthcareEducationCulture', 'SocialGovernanceLaw', 'ScienceTechnologyEngineering', 'FinanceWealthManagement',]
# 可视化颜色配置(NPG配色)COLORS = ["#E64B35", "#4DBBD5", "#00A087", "#3C5488", "#F39B7F"]
# 固定类别-颜色映射,保证左右图同类别同颜色CATEGORY_COLOR_MAP = { cat: COLORS[i % len(COLORS)] for i, cat in enumerate(CATEGORY_ORDER)}
# ============================================================# 通用数据加载函数# ============================================================def load_json(filepath): """加载JSON文件""" with open(filepath, 'r') as f: return json.load(f)
def group_tasks_by_category(category_mapping): """按类别分组任务""" groups = defaultdict(list) for task_id, cat in category_mapping.items(): groups[cat].append(task_id) return groups
# ============================================================# 数据加载函数# ============================================================def load_ridgeline_data(): """加载山脊图所需的全部数据""" category_map = load_json(DATA_FILES['category_map']) task_groups = group_tasks_by_category(category_map) is_deception = load_is_deception_humans(DATA_FILES['main'])[0] ground_truth = load_ground_truth_deception_expert(DATA_FILES['main']) datasets = [] for cat in CATEGORY_ORDER: task_ids = task_groups.get(cat, []) valid_ids = is_deception.index.intersection(task_ids) if len(valid_ids) == 0: continue df = is_deception.loc[valid_ids] truth = ground_truth.loc[valid_ids] datasets.append((cat, df, truth)) return datasets
# ============================================================# 性能计算函数# ============================================================METRICS_DEF = [ {"name": "Precision", "func": precision_score, "kwargs": {"pos_label": 1, "zero_division": 0}}, {"name": "Recall", "func": recall_score, "kwargs": {"pos_label": 1, "zero_division": 0}}, {"name": "F1 Score", "func": f1_score, "kwargs": {"pos_label": 1, "zero_division": 0}}]
def compute_metrics(config_list): """计算各类别的性能指标""" records = [] for label, df_preds, truth in config_list: for col_name in df_preds.columns: pred = df_preds[col_name].values for m in METRICS_DEF: try: score = m["func"](truth, pred, **m["kwargs"]) except ValueError: score = 0.0 records.append({"Model": label, "Metric": m["name"], "Score": score}) return pd.DataFrame(records)
def compute_jagged_average(df): """计算不等长列表的平均值""" all_lists = df.values.flatten() aligned_data = list(zip_longest(*all_lists, fillvalue=np.nan)) arr = np.array(aligned_data) if arr.dtype == object: arr[arr == None] = np.nan arr = arr.astype(float) return np.nanmean(arr, axis=1)
def compute_accuracy_per_position(row, gt): """计算每个位置的准确率""" gt_arr = np.array(gt, dtype=float) target_len = len(gt_arr)
aligned = [] for seq in row.tolist(): seq = [] if seq is None else list(seq) seq = seq[:target_len] if len(seq) >= target_len else seq + [np.nan] * (target_len - len(seq)) aligned.append(seq)
arr = np.array(aligned, dtype=float) mask = ~np.isnan(arr) correct = (arr == gt_arr) denom = mask.sum(axis=0) return (correct & mask).sum(axis=0) / np.where(denom == 0, 1, denom)
def compute_average_accuracy(is_deception, ground_truth): """计算所有任务的平均准确率曲线""" sum_acc, count_acc = defaultdict(float), defaultdict(int)
for idx, row in is_deception.iterrows(): acc = compute_accuracy_per_position(row, ground_truth.loc[idx]) for pos, val in enumerate(acc): sum_acc[pos] += val count_acc[pos] += 1
return [sum_acc[i] / count_acc[i] for i in sorted(sum_acc.keys())]
def compute_scene_data(is_deception, confidences, ground_truth, task_groups): """按场景分组计算准确率和置信度曲线""" result = {} for group_name, task_id_list in task_groups.items(): valid_ids = is_deception.index.intersection(task_id_list) if len(valid_ids) == 0: continue sub_pred = is_deception.loc[valid_ids] sub_conf = confidences.loc[valid_ids] sub_gt = ground_truth.loc[valid_ids] result[group_name] = ( compute_average_accuracy(sub_pred, sub_gt), compute_jagged_average(sub_conf) ) return result
def load_accuracy_data(): """加载逐轮次准确率所需的全部数据""" is_deception = load_is_deception_humans_iter(DATA_FILES['main'])[0] confidences = load_confidence_humans(DATA_FILES['main'])[1] ground_truth = load_ground_truth_iteration(DATA_FILES['main']) # 按场景分组(与左侧山脊图保持同序) category_map = load_json(DATA_FILES['category_map']) task_groups = group_tasks_by_category(category_map) scene_order = CATEGORY_ORDER task_groups = {scene: task_groups[scene] for scene in scene_order if scene in task_groups} return compute_scene_data(is_deception, confidences, ground_truth, task_groups)
# ============================================================# 绘图函数# ============================================================def setup_plot_style(): """设置绘图样式(基于公共样式模块)""" apply_style({ 'font.size': 10, 'axes.labelsize': 10, 'axes.titlesize': 12, 'axes.titleweight': 'bold', 'xtick.labelsize': 9, })
def plot_ridgeline_on_axes(axes, data_config): """ 在给定的axes上绘制山脊图 Parameters: axes: list of 3 axes (Precision, Recall, F1) data_config: [(label, df_preds, truth), ...] """ df_long = compute_metrics(data_config) model_order = [cfg[0] for cfg in data_config] metric_order = ["Precision", "Recall", "F1 Score"] scale = 0.6 x_min, x_max = 0.5, 1.0 x_grid = np.linspace(x_min, x_max, 400) for ax_idx, metric_name in enumerate(metric_order): ax = axes[ax_idx] subset = df_long[df_long["Metric"] == metric_name] y_ticks = [] y_ticklabels = [] for i, model in enumerate(model_order): data = subset[subset["Model"] == model]["Score"].values # KDE 计算 if len(data) > 1 and np.std(data) > 1e-6: kde = gaussian_kde(data, bw_method='scott') y_curve = kde(x_grid) y_curve = y_curve / y_curve.max() * scale else: y_curve = np.zeros_like(x_grid) if len(data) > 0: idx = np.abs(x_grid - np.mean(data)).argmin() y_curve[max(0, idx-2):min(len(x_grid), idx+3)] = scale base_line = i * 0.4 z_order = len(model_order) - i color = CATEGORY_COLOR_MAP.get(model, COLORS[i % len(COLORS)]) # 绘制山脊 ax.fill_between( x_grid, base_line, base_line + y_curve, color=color, alpha=0.85, zorder=z_order, edgecolor='white', linewidth=1.2 ) # 均值线 & Rug Plot if len(data) > 0: mean_val = np.mean(data) if len(data) > 1 and np.std(data) > 1e-6: h_val = kde(mean_val) / kde(x_grid).max() * scale else: h_val = scale ax.vlines( mean_val, base_line, base_line + h_val, color='white', linestyle='-', linewidth=1.5, zorder=z_order+1 ) ax.plot( data, [base_line] * len(data), '|', color='white', markersize=4, alpha=0.6, zorder=z_order+1, markeredgewidth=0.8 ) y_ticks.append(base_line) y_ticklabels.append(model) # 坐标轴设置 ax.set_title(metric_name, pad=15, color='#222222', fontsize=14) ax.set_xlim(x_min, x_max) ax.set_xticks(np.arange(0.5, 1.01, 0.1)) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['bottom'].set_color('#333333') ax.spines['bottom'].set_linewidth(0.8) ax.set_yticks(y_ticks) ax.set_yticklabels(y_ticklabels, fontweight='bold', ha='right', fontsize=9) ax.tick_params(axis='y', length=0, pad=8) ax.tick_params(axis='x', colors='#333333')
def plot_accuracy_on_ax(ax, data_scene_tasks, ylim_acc=(0.3, 1.1), ylim_conf=(3.5, 5.5)): """ 在给定的ax上绘制准确率和置信度图 Parameters: ax: matplotlib axis data_scene_tasks: {场景名: (准确率曲线, 置信度曲线)} ylim_acc: 准确率Y轴范围 ylim_conf: 置信度Y轴范围 """ ax_conf = ax.twinx() models = list(data_scene_tasks.keys()) num_models = len(models) local_style_map = { m: CATEGORY_COLOR_MAP.get(m, COLORS[i % len(COLORS)]) for i, m in enumerate(models) } # Y轴范围设置 ax.set_ylim(*ylim_acc) ax.set_yticks(np.arange(ylim_acc[0], ylim_acc[1] + 0.01, 0.1)) ax_conf.set_ylim(*ylim_conf) ax_conf.set_yticks(np.arange(ylim_conf[0], ylim_conf[1] + 0.1, 0.5))
# 绘图参数 total_width = 0.8 bar_width = total_width / num_models if num_models > 0 else 0.8 col_legend_handles = [] col_legend_labels = []
max_len = 0 for i, model_name in enumerate(models): acc, conf = data_scene_tasks[model_name] c = local_style_map[model_name] x = np.arange(1, len(acc) + 1) max_len = max(max_len, len(acc)) # 绘制 Accuracy 折线 l1, = ax.plot(x, acc, color=c, linestyle='-', marker='o', markersize=6, linewidth=3, alpha=0.9, zorder=10) # 绘制 Confidence 柱状图 x_pos = x - (total_width / 2) + (i * bar_width) + (bar_width / 2) ax_conf.bar(x_pos, conf, width=bar_width, color=c, alpha=0.7, edgecolor='white', linewidth=0.5) col_legend_handles.append(l1) col_legend_labels.append(model_name)
# 图例设置 h_spacer = Line2D([], [], linestyle='none', marker='none', label=' ') h_acc_sample = Line2D([], [], color='dimgray', linestyle='-', marker='o', linewidth=2, label='Accuracy') h_conf_sample = Patch(facecolor='dimgray', alpha=0.4, label='Confidence')
final_handles = col_legend_handles + [h_spacer, h_acc_sample, h_conf_sample] final_labels = col_legend_labels + ['', 'Accuracy (Line)', 'Confidence (Bar)']
ax.legend(handles=final_handles, labels=final_labels, loc='upper left', bbox_to_anchor=(0.02, 0.98), fontsize=8, frameon=True, framealpha=0.9, edgecolor='lightgray')
# 坐标轴美化 ax.set_xlabel('Round', fontsize=14, fontweight='bold') ax.set_ylabel('Accuracy', fontsize=14, fontweight='bold') ax_conf.set_ylabel('Confidence', fontsize=14, fontweight='bold', rotation=270, labelpad=20)
ax.grid(True, axis='y', linestyle='--', alpha=0.3) ax.spines['top'].set_visible(False) ax_conf.spines['top'].set_visible(False) ax.tick_params(axis='both', labelsize=12) ax_conf.tick_params(axis='y', labelsize=12) if max_len < 20: ax.set_xticks(np.arange(1, max_len + 1))
def plot_combined_figure(ridgeline_data, accuracy_data, save_path=None): """ 绘制合并图:左侧山脊图(3个子图),右侧准确率图 Parameters: ridgeline_data: [(label, df_preds, truth), ...] accuracy_data: {场景名: (准确率曲线, 置信度曲线)} save_path: 保存路径 """ setup_plot_style() # 创建图形和GridSpec布局 fig = plt.figure(figsize=(14, 12), dpi=300) gs = gridspec.GridSpec(3, 2, width_ratios=[1, 1], height_ratios=[1, 1, 1], hspace=0.35, wspace=0.35) # 左侧:3个山脊图子图 ax_ridge_0 = fig.add_subplot(gs[0, 0]) ax_ridge_1 = fig.add_subplot(gs[1, 0]) ax_ridge_2 = fig.add_subplot(gs[2, 0]) ridge_axes = [ax_ridge_0, ax_ridge_1, ax_ridge_2] # 右侧:准确率图(跨越所有3行) ax_acc = fig.add_subplot(gs[:, 1]) # 绘制山脊图 plot_ridgeline_on_axes(ridge_axes, ridgeline_data) # ��制准确率图 plot_accuracy_on_ax(ax_acc, accuracy_data) # 保存或显示(同时保存 PNG 和 PDF) if save_path: save_figure(fig, save_path) plt.close(fig) else: plt.show()
# ============================================================# 主函数# ============================================================def main(): """主函数""" print("加载数据...") ridgeline_data = load_ridgeline_data() accuracy_data = load_accuracy_data() print(f"山脊图: {len(ridgeline_data)} 个类别") print(f"准确率图: {len(accuracy_data)} 个场景") print("生成合并图...") save_path = os.path.join(OUTPUT_DIR, OUTPUT_BASENAME + '.png') plot_combined_figure(ridgeline_data, accuracy_data, save_path=save_path) print("完成!")
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421"""桑基图:可视化人类标注者在两次标注之间的判断变化"""
import osimport sysimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle, PathPatchfrom matplotlib.path import Path
# 设置项目路径current_dir = os.path.dirname(os.path.abspath(__file__))project_root = os.path.abspath(os.path.join(current_dir, '..'))sys.path.append(project_root)
from utils.deception_data import ( load_full_is_deception_humans, load_full_confidences, load_is_deception_humans, load_ground_truth_deception_expert,)from utils.plot_style import apply_style, save_figure
# ============================================================================# 配置常量# ============================================================================
DATA_PATH = os.path.join(project_root, 'data', 'task3_merged010203_40x158_102.json')OUTPUT_DIR = os.path.join(project_root, 'output')
TASKS_PER_GROUP = 30
# ============================================================================# 数据处理函数# ============================================================================
def extract_first_two_values(x): """从列表中提取前两个值的第一个元素""" if isinstance(x, list) and len(x) >= 2: return [t[0] for t in x[:2]] return np.nan
def get_first_value(x): """获取列表的第一个值""" if isinstance(x, list): return x[0] return np.nan
def get_second_value(x): """获取列表的第二个值""" if isinstance(x, list): return x[1] return np.nan
def auto_split_easy_difficult_tasks(data_path, tasks_per_group=30): """ 根据任务平均准确率自动划分简单/困难任务。
规则: - 使用首次标注结果(每位标注员每任务第一次标注) - 以专家共识标签作为 ground truth - 任务准确率 = 该任务上所有有效标注的平均准确率 - 取 Top-N 为简单任务,Bottom-N 为困难任务 """ is_deception_first = load_is_deception_humans(data_path)[0] ground_truth = load_ground_truth_deception_expert(data_path)
common_tasks = is_deception_first.index.intersection(ground_truth.index) if len(common_tasks) == 0: raise ValueError("未找到可用于自动分组的任务。")
is_deception_first = is_deception_first.loc[common_tasks] ground_truth = ground_truth.loc[common_tasks]
valid_mask = is_deception_first.notna() correct_mask = is_deception_first.eq(ground_truth, axis=0) & valid_mask valid_count = valid_mask.sum(axis=1) task_accuracy = (correct_mask.sum(axis=1) / valid_count.replace(0, np.nan)).dropna()
if task_accuracy.empty: raise ValueError("任务准确率为空,无法自动生成简单/困难任务列表。")
n = min(tasks_per_group, len(task_accuracy) // 2) if n <= 0: raise ValueError("有效任务数量不足,无法划分简单/困难任务。")
task_accuracy = task_accuracy.sort_values(ascending=False) easy_tasks = task_accuracy.head(n).index.tolist() difficult_tasks = task_accuracy.tail(n).index.tolist() return easy_tasks, difficult_tasks
def load_and_process_data(data_path, task_list): """ 加载并处理数据 Args: data_path: 数据文件路径 task_list: 任务列表 Returns: data1, data2: 第一次和第二次标注的得分数据 """ # 加载原始数据 is_deception = load_full_is_deception_humans(data_path) confidences = load_full_confidences(data_path) # 筛选任务 is_deception = is_deception.loc[task_list] confidences = confidences.loc[task_list] # 提取前两次标注 is_deception_processed = is_deception.map(extract_first_two_values) confidences_processed = confidences.map(extract_first_two_values) # 分离第一次和第二次标注 is_deception_1 = is_deception_processed.map(get_first_value) is_deception_2 = is_deception_processed.map(get_second_value) confidences_1 = confidences_processed.map(get_first_value) confidences_2 = confidences_processed.map(get_second_value) # 转换为 -1/+1 并乘以置信度 is_deception_1 = is_deception_1.map(lambda x: 2 * x - 1) is_deception_2 = is_deception_2.map(lambda x: 2 * x - 1) data1 = is_deception_1 * confidences_1 data2 = is_deception_2 * confidences_2 return data1, data2
# ============================================================================# 绘图辅助函数# ============================================================================
def get_color_for_value(val): """根据值获取对应颜色""" blue = ["#08306B", "#08519C", "#2171B5", "#4292C6", "#6BAED6"] red = ["#FCBBA1", "#FB6A4A", "#EF3B2C", "#CB181D", "#99000D"] neutral = "#BDBDBD" if val == 0: return neutral if val < 0: idx = max(0, min(4, int(abs(val) - 1))) return blue[4 - idx] idx = max(0, min(4, int(val - 1))) return red[idx]
def hex_to_rgba(hex_color, alpha=0.35): """将十六进制颜色转换为 RGBA""" hex_color = hex_color.lstrip("#") r, g, b = (int(hex_color[i:i+2], 16) for i in (0, 2, 4)) return (r/255, g/255, b/255, alpha)
def format_value(v): """格式化数值为字符串""" try: v = float(v) return str(int(v)) if v.is_integer() else str(v) except: return str(v)
def compute_layout(nodes, weights, gap): """ 计算节点布局 Args: nodes: 节点列表 weights: 节点权重字典 gap: 节点间隙 Returns: y0: 节点起始y坐标字典 heights: 节点高度字典 """ h = np.array([weights[v] for v in nodes], dtype=float) n = len(nodes) total_gap = gap * (n - 1) if n > 1 else 0.0 scale = (1.0 - total_gap) / h.sum() heights = h * scale y0 = {} y = 0.0 for v, hv in zip(nodes, heights): y0[v] = y y += hv + gap return y0, {v: hv for v, hv in zip(nodes, heights)}
# ============================================================================# 主绘图函数# ============================================================================
def draw_sankey_on_ax(ax, data1, data2, gap=0.02, node_w=0.04, curve=0.35, sort_within_node=True, label_min_count=5, title=None): """ 在指定的 axes 上绘制桑基图 Args: ax: matplotlib axes 对象 data1: 第一次标注数据 data2: 第二次标注数据 gap: 节点间隙 node_w: 节点宽度 curve: 曲线弯曲程度 sort_within_node: 是否在节点内排序 label_min_count: 显示标签的最小计数 title: 子图标题 """ # 数据准备 s = pd.to_numeric(pd.Series(np.asarray(data1).ravel()), errors="coerce") t = pd.to_numeric(pd.Series(np.asarray(data2).ravel()), errors="coerce") df = pd.DataFrame({"source": s, "target": t}).dropna() # 计算流量 flows = df.groupby(["source", "target"]).size().reset_index(name="count") # 计算每侧权重 sw = flows.groupby("source")["count"].sum().to_dict() tw = flows.groupby("target")["count"].sum().to_dict() # 构建节点集合 global_order = sorted(set(df["source"].unique()) | set(df["target"].unique())) left_nodes = [v for v in global_order if sw.get(v, 0) > 0] right_nodes = [v for v in global_order if tw.get(v, 0) > 0] left_total = sum(sw[v] for v in left_nodes) right_total = sum(tw[v] for v in right_nodes) if left_total <= 0 or right_total <= 0: raise ValueError("没有有效流量,无法绘图。") # 计算布局 yL0, hL = compute_layout(left_nodes, sw, gap) yR0, hR = compute_layout(right_nodes, tw, gap) # 初始化游标 out_cursor = {v: 0.0 for v in left_nodes} in_cursor = {v: 0.0 for v in right_nodes} # 连线排序(减少交叉) if sort_within_node: flows_sorted = flows.copy() flows_sorted["s_rank"] = flows_sorted["source"].map({v: i for i, v in enumerate(left_nodes)}) flows_sorted["t_rank"] = flows_sorted["target"].map({v: i for i, v in enumerate(right_nodes)}) flows_sorted = flows_sorted.sort_values(["s_rank", "t_rank"]).drop(columns=["s_rank", "t_rank"]) else: flows_sorted = flows # x 坐标位置 xL = 0.12 xR = 0.88 xL1 = xL + node_w xR0 = xR - node_w # 设置坐标轴 ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.axis("off") # 绘制连线 for _, r in flows_sorted.iterrows(): s_val, t_val, c = r["source"], r["target"], float(r["count"]) if s_val not in hL or t_val not in hR: continue # 计算连线高度 seg_h = (c / sw[s_val]) * hL[s_val] # 左侧段 y 坐标 yls0 = yL0[s_val] + out_cursor[s_val] yls1 = yls0 + seg_h out_cursor[s_val] += seg_h # 右侧段 y 坐标 seg_h_r = (c / tw[t_val]) * hR[t_val] yrt0 = yR0[t_val] + in_cursor[t_val] yrt1 = yrt0 + seg_h_r in_cursor[t_val] += seg_h_r # 生成贝塞尔曲线路径 cx1 = xL1 + curve * (xR0 - xL1) cx2 = xR0 - curve * (xR0 - xL1) verts = [ (xL1, yls0), (cx1, yls0), (cx2, yrt0), (xR0, yrt0), (xR0, yrt1), (cx2, yrt1), (cx1, yls1), (xL1, yls1), (xL1, yls0), ] codes = [ Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY, ] col = hex_to_rgba(get_color_for_value(s_val), alpha=0.35) patch = PathPatch(Path(verts, codes), facecolor=col, edgecolor=(0, 0, 0, 0), lw=0) ax.add_patch(patch) # 绘制节点 def draw_nodes(nodes, y0, h, weights, side="L"): for v in nodes: color = get_color_for_value(v) if side == "L": rect = Rectangle((xL, y0[v]), node_w, h[v], facecolor=color, edgecolor="0.5", linewidth=0.6) ax.add_patch(rect) if weights.get(v, 0) >= label_min_count: ax.text(xL - 0.02, y0[v] + h[v]/2, format_value(v), va="center", ha="right", fontsize=10, color="0.15") else: rect = Rectangle((xR0, y0[v]), node_w, h[v], facecolor=color, edgecolor="0.5", linewidth=0.6) ax.add_patch(rect) if weights.get(v, 0) >= label_min_count: ax.text(xR0 + node_w + 0.02, y0[v] + h[v]/2, format_value(v), va="center", ha="left", fontsize=10, color="0.15") draw_nodes(left_nodes, yL0, hL, sw, side="L") draw_nodes(right_nodes, yR0, hR, tw, side="R") # 添加标题 if title: ax.set_title(title, fontsize=16, fontweight="bold", pad=10)
def draw_combined_sankey(data_easy, data_diff, gap=0.02, node_w=0.045, curve=0.40, sort_within_node=True, label_min_count=5, figsize=(12, 9), dpi=300, savepath=None, easy_title="Easy 30 Tasks", diff_title="Difficult 30 Tasks"): """ 绘制并排的两个桑基图(简单任务 + 困难任务) Args: data_easy: (data1_easy, data2_easy) 简单任务数据元组 data_diff: (data1_diff, data2_diff) 困难任务数据元组 其他参数同 draw_sankey_on_ax """ apply_style() # 创建并排子图 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize, dpi=dpi) # 绘制简单任务桑基图 draw_sankey_on_ax( ax1, data_easy[0], data_easy[1], gap=gap, node_w=node_w, curve=curve, sort_within_node=sort_within_node, label_min_count=label_min_count, title=easy_title ) # 绘制困难任务桑基图 draw_sankey_on_ax( ax2, data_diff[0], data_diff[1], gap=gap, node_w=node_w, curve=curve, sort_within_node=sort_within_node, label_min_count=label_min_count, title=diff_title ) # 调整布局 plt.tight_layout() # 保存图片(同时保存 PNG 和 PDF) if savepath: save_figure(fig, savepath) plt.close(fig)
# ============================================================================# 主程序# ============================================================================
def main(): """主函数""" # 确保输出目录存在 os.makedirs(OUTPUT_DIR, exist_ok=True) easy_tasks, difficult_tasks = auto_split_easy_difficult_tasks( DATA_PATH, tasks_per_group=TASKS_PER_GROUP, ) print(f"自动分组完成:简单任务 {len(easy_tasks)} 个,困难任务 {len(difficult_tasks)} 个")
# 处理简单任务数据 data1_easy, data2_easy = load_and_process_data(DATA_PATH, easy_tasks)
# 处理困难任务数据 data1_diff, data2_diff = load_and_process_data(DATA_PATH, difficult_tasks) # 绘制并排桑基图 draw_combined_sankey( data_easy=(data1_easy, data2_easy), data_diff=(data1_diff, data2_diff), gap=0.02, node_w=0.045, curve=0.40, sort_within_node=True, label_min_count=5, figsize=(12, 9), dpi=300, savepath=os.path.join(OUTPUT_DIR, "桑基图_任务对比"), easy_title=f"Easy {len(easy_tasks)} Tasks", diff_title=f"Difficult {len(difficult_tasks)} Tasks", )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""欺骗窗口绘制脚本功能:分析人类对AI欺骗行为的检测能力输出:双面板对比图 - Panel A: 进入欺骗阶段的检测率变化(有/无前言对比) - Panel B: 欺骗结束后的检测率变化(警惕性衰减)"""
import osimport sysimport ast
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport seaborn as snsfrom scipy import stats
# 添加项目根目录到路径current_dir = os.path.dirname(os.path.abspath(__file__))project_root = os.path.abspath(os.path.join(current_dir, '..'))sys.path.append(project_root)
from utils.deception_data_per_iteration import ( load_is_deception_humans, load_ground_truth_iteration)from utils.plot_style import apply_seaborn_style, save_figure
# ============================================================================# 配置常量# ============================================================================DATA_PATH = os.path.join(project_root, 'data', 'task3_merged010203_40x158_102.json')
# 窗口参数PRE_WINDOW = 5 # 第一个谎言前的时间步数POST_WINDOW = 8 # 最后一个谎言后的时间步数MEDIAN_SPLIT = 0 # 分组阈值
# 颜色配置COLORS = { 'With Preamble': '#005A8C', # 深蓝色 'No Preamble': '#D1495B', # 红色 'Combined': '#3E3E3E', # 深灰色 'Text': '#2C2C2C', # 文字颜色 'Anno': '#555555' # 标注颜色}
# ============================================================================# 绘图风格设置# ============================================================================def set_publication_style(): """设置期刊级绘图风格(基于公共样式模块)""" apply_seaborn_style({ "xtick.direction": "out", "ytick.direction": "out", "axes.labelsize": 11, "axes.titlesize": 12, "xtick.labelsize": 10, "ytick.labelsize": 10, "legend.fontsize": 10, })
# ============================================================================# 数据加载与处理# ============================================================================def load_data(): """ 加载欺骗检测数据和真实标签 Returns: tuple: (is_deception DataFrame, ground_truth Series) """ is_deception = load_is_deception_humans(DATA_PATH)[0] ground_truth = load_ground_truth_iteration(DATA_PATH) return is_deception, ground_truth
def validate_and_filter_data(is_deception, ground_truth): """ 验证数据完整性并过滤有效数据 Args: is_deception: 欺骗检测数据 ground_truth: 真实标签数据 Returns: tuple: (过滤后的 df_raw, 过滤后的 gold_std) """ print("正在检查数据完整性...") # 确保索引完全一致 common_ids = is_deception.index.intersection(ground_truth.index) print(f"原始任务数: {len(is_deception)}, 有效匹配任务数: {len(common_ids)}") if len(common_ids) == 0: raise ValueError("错误:is_deception 和 ground_truth 的索引没有重合!请检查任务ID是否一致。") # 过滤数据 df_raw = is_deception.loc[common_ids] gold_std = ground_truth.loc[common_ids] # 类型安全检查 (防止列表是字符串格式) if isinstance(gold_std.iloc[0], str): print("检测到数据为字符串格式,正在转换为列表...") gold_std = gold_std.apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else x) df_raw = df_raw.map(lambda x: ast.literal_eval(x) if isinstance(x, str) else x) print("数据检查通过,开始处理...") return df_raw, gold_std
def prepare_plot_data(df_raw, gold_std): """ 准备绑图数据 Args: df_raw: 欺骗检测数据 gold_std: 真实标签数据 Returns: tuple: (DataFrame 绑图数据, t0时刻的值字典, 诚实基线值) """ plot_data = [] t0_values = {'With Preamble': [], 'No Preamble': []} all_honest_scores = [] for task_id in df_raw.index: if task_id not in gold_std: continue gold = gold_std[task_id] # 计算任务的平均检测序列 try: task_matrix = [x for x in df_raw.loc[task_id].tolist() if isinstance(x, list)] if not task_matrix: continue min_len = min(len(i) for i in task_matrix) mean_seq = np.nanmean(np.array([x[:min_len] for x in task_matrix]), axis=0) except: continue # 收集诚实时刻的检测分数(用于基线计算) honest_idxs = [i for i, x in enumerate(gold) if x == 0 and i < len(mean_seq)] if honest_idxs: all_honest_scores.extend(mean_seq[honest_idxs]) # 找到���言位置 lie_locs = [i for i, x in enumerate(gold) if x == 1] if not lie_locs: continue t_first, t_last = lie_locs[0], lie_locs[-1] group = 'With Preamble' if t_first > MEDIAN_SPLIT else 'No Preamble' # Entry Phase: 进入欺骗阶段的数据 for rel_t in range(-PRE_WINDOW, 1): abs_t = t_first + rel_t if 0 <= abs_t < len(mean_seq): val = mean_seq[abs_t] plot_data.append({ 'Group': group, 'Phase': 'Entry', 'Plot_X': rel_t, 'Value': val }) if rel_t == 0: t0_values[group].append(val) # Exit Phase: 退出欺骗阶段的数据 for rel_t in range(1, POST_WINDOW + 1): abs_t = t_last + rel_t if 0 <= abs_t < len(mean_seq): plot_data.append({ 'Group': 'Combined', 'Phase': 'Exit', 'Plot_X': rel_t, 'Value': mean_seq[abs_t] }) df_plot = pd.DataFrame(plot_data) baseline_value = np.nanmean(all_honest_scores) if all_honest_scores else 0.5 return df_plot, t0_values, baseline_value
# ============================================================================# 绑图辅助函数# ============================================================================def add_vertical_gap_marker(ax, x_pos, y_bottom, y_top, label_text, color=None): """ 绑制垂直间距标注(用于显示差异) Args: ax: matplotlib axes 对象 x_pos: x坐标位置 y_bottom: 下边界 y_top: 上边界 label_text: 标注文本 color: 颜色 """ if color is None: color = COLORS['Text'] y_top = y_top - 0.01 y_bottom = y_bottom + 0.01 # 垂直线 ax.plot([x_pos, x_pos], [y_bottom, y_top], color=color, lw=1.0, alpha=0.9) # 上下端点横线 cap_width = 0.12 ax.plot([x_pos - cap_width/2, x_pos + cap_width/2], [y_bottom, y_bottom], color=color, lw=1.0) ax.plot([x_pos - cap_width/2, x_pos + cap_width/2], [y_top, y_top], color=color, lw=1.0) # 标签文本 ax.text(x_pos - 0.15, (y_bottom + y_top) / 2, label_text, ha="right", va="center", fontsize=8.5, color=color, fontweight='medium', linespacing=1.3)
def format_p_scientific(p_val): """将 p 值格式化为科学计数法文本,如 1.63×10^{-5}""" if not np.isfinite(p_val): return "NA" if p_val == 0: return "<10^{-300}" sci = f"{p_val:.2e}" mantissa, exponent = sci.split('e') return f"{mantissa}×10^{{{int(exponent)}}}"
# ============================================================================# 绑图函数# ============================================================================def plot_panel_a(ax, df_plot, t0_values): """ 绑制 Panel A: 进入欺骗阶段 Args: ax: matplotlib axes 对象 df_plot: 绑图数据 t0_values: t0时刻的值字典 """ # 标题 ax.set_title("Entering deception", loc="left", pad=15, color=COLORS['Text'], fontweight="bold") # 绑制 With Preamble 曲线 sns.lineplot( data=df_plot[(df_plot['Phase'] == 'Entry') & (df_plot['Group'] == 'With Preamble')], x='Plot_X', y='Value', color=COLORS['With Preamble'], linewidth=2.8, ax=ax, errorbar=('ci', 95), err_style="band", err_kws={"alpha": 0.18, "edgecolor": "none"} ) # 计算 t=0 时刻的均值 val0_no = df_plot[ (df_plot['Phase'] == 'Entry') & (df_plot['Group'] == 'No Preamble') & (df_plot['Plot_X'] == 0) ]['Value'].mean() val0_with = df_plot[ (df_plot['Phase'] == 'Entry') & (df_plot['Group'] == 'With Preamble') & (df_plot['Plot_X'] == 0) ]['Value'].mean() # 绘制 No Preamble 基线和散点 if np.isfinite(val0_no): ax.axhline(y=val0_no, color=COLORS['No Preamble'], linestyle='--', linewidth=2.2, alpha=0.85, zorder=1) ax.scatter(0, val0_no, s=70, color=COLORS['No Preamble'], zorder=10, edgecolors="white", linewidth=1.2) ax.scatter(0, val0_with, s=70, color=COLORS['With Preamble'], zorder=10, edgecolors="white", linewidth=1.2) # 统计标注 if t0_values['With Preamble'] and t0_values['No Preamble']: _, p_val = stats.ttest_ind( t0_values['With Preamble'], t0_values['No Preamble'], equal_var=False, nan_policy='omit' ) m_with = np.nanmean(t0_values['With Preamble']) m_no = np.nanmean(t0_values['No Preamble']) delta = abs(m_with - m_no) if p_val < 0.001: sig_stars = "***" elif p_val < 0.01: sig_stars = "**" elif p_val < 0.05: sig_stars = "*" else: sig_stars = "ns" p_txt = format_p_scientific(p_val) label_txt = f"$\\Delta={delta*100:.2f}\\%$\nWelch t-test, p = {p_txt} {sig_stars}" add_vertical_gap_marker(ax, -0.4, m_with, m_no, label_txt) # "Trust Built" 标注 y_trust_pos = df_plot[ (df_plot['Phase'] == 'Entry') & (df_plot['Group'] == 'With Preamble') & (df_plot['Plot_X'] == -3) ]['Value'].mean() ax.annotate('Trust built', xy=(-3.0, y_trust_pos + 0.02), xycoords='data', xytext=(-3.0, 0.38), textcoords='data', arrowprops=dict(arrowstyle="->", color=COLORS['Anno'], lw=1.2), fontsize=9.5, color=COLORS['Anno'], ha='center', va='bottom') # "Cognitive Drift" 标注(优先指向 gap marker 的下沿短横线) if np.isfinite(val0_with) and np.isfinite(val0_no): # 与 add_vertical_gap_marker 内部 y_bottom = min(...) + 0.01 保持一致 drift_target = (-0.4, min(val0_with, val0_no) + 0.01) else: # 兜底:若 No Preamble 缺失,则退回指向 With Preamble 的 t=0 点 drift_target = (0, val0_with - 0.02)
ax.annotate('Trust-induced\ncognitive drift', xy=drift_target, xycoords='data', xytext=(-2.2, 0.58), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.1", color=COLORS['Anno'], lw=1.2), fontsize=9.5, color=COLORS['Anno'], ha='center', va='center') # 坐标轴设置 ax.set_xlabel("Time steps (relative to first lie)", labelpad=8) ax.set_ylabel("Human detection rate", labelpad=8) ax.set_xlim(-PRE_WINDOW - 0.3, 0.6) ax.set_ylim(0, 1.05) ax.set_xticks(range(-PRE_WINDOW, 1)) ax.set_xticklabels([str(i) for i in range(-PRE_WINDOW, 0)] + ["First\nlie"]) ax.grid(axis="y", linestyle="--", linewidth=0.6, alpha=0.15) sns.despine(ax=ax) # 图例 handles_a = [ plt.Line2D([0], [0], color=COLORS['With Preamble'], lw=2.8, label='With preamble'), plt.Line2D([0], [0], color=COLORS['No Preamble'], lw=2.2, linestyle='--', label='No preamble') ] ax.legend(handles=handles_a, frameon=False, loc="lower right", bbox_to_anchor=(1.0, 1.02), ncol=2)
def plot_panel_b(ax, df_plot, baseline_value): """ 绑制 Panel B: 欺骗结束后 Args: ax: matplotlib axes 对象 df_plot: 绑图数据 baseline_value: 诚实基线值 """ # 标题 ax.set_title("After deception ends", loc="left", pad=15, color=COLORS['Text'], fontweight="bold") # 诚实基线 ax.axhline(y=baseline_value, color='#9CA3AF', linestyle=':', linewidth=1.8, alpha=1.0, zorder=1) # 审视窗口区域 scrutiny_start, scrutiny_end = 1, 5 ax.axvspan(scrutiny_start, scrutiny_end, color='#E5E7EB', alpha=0.6, lw=0, zorder=0) # 审视窗口标签 trans_blend = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) ax.text((scrutiny_start + scrutiny_end)/2, 0.93, 'Scrutiny window', transform=trans_blend, ha='center', va='top', fontsize=9.5, color='#6B7280', fontweight='bold') # 绘制检测率曲线 sns.lineplot( data=df_plot[df_plot['Phase'] == 'Exit'], x='Plot_X', y='Value', color=COLORS['Combined'], linewidth=2.8, ax=ax, errorbar=('ci', 95), err_style="band", err_kws={"alpha": 0.15, "edgecolor": "none"} ) # "Vigilance Decay" 标注 last_val_idx = 7 y_target = df_plot[ (df_plot['Phase'] == 'Exit') & (df_plot['Plot_X'] == last_val_idx) ]['Value'].mean() ax.annotate('Vigilance decay', xy=(last_val_idx, y_target + 0.02), xycoords='data', xytext=(5.8, y_target + 0.18), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=-0.15", color=COLORS['Anno'], lw=1.2), fontsize=9.5, color=COLORS['Anno'], ha='center') # 坐标轴设置 ax.set_xlabel("Time steps (since last lie)", labelpad=8) ax.set_ylabel("Human detection rate", labelpad=8) ax.set_xlim(-0.5, POST_WINDOW + 0.5) ax.set_xticks(list(range(0, POST_WINDOW + 1))) ax.set_xticklabels(['Last\nlie'] + [str(i) for i in range(1, POST_WINDOW + 1)]) ax.grid(axis="y", linestyle="--", linewidth=0.6, alpha=0.15) sns.despine(ax=ax) # 图例 handles_b = [ plt.Line2D([0], [0], color=COLORS['Combined'], lw=2.8, label='Detection rate'), plt.Line2D([0], [0], color='#9CA3AF', lw=1.8, linestyle=':', label='Honest baseline') ] ax.legend(handles=handles_b, frameon=False, loc="lower right", bbox_to_anchor=(1.0, 1.02), ncol=2)
def plot_deception_window(df_plot, t0_values, baseline_value): """ 绘制完整的欺骗窗口分析图 Args: df_plot: 绘图数据 t0_values: t0时刻的值字典 baseline_value: 诚实基线值 """ fig, (ax1, ax2) = plt.subplots( 1, 2, figsize=(15, 5.5), constrained_layout=True, gridspec_kw={"wspace": 0.22} ) # 绘制两个面板 plot_panel_a(ax1, df_plot, t0_values) plot_panel_b(ax2, df_plot, baseline_value) # 保存图片(同时保存 PNG 和 PDF) output_path = os.path.join(project_root, 'output', '欺骗窗口.png') save_figure(fig, output_path) plt.close(fig)
# ============================================================================# 主函数# ============================================================================def main(): """主函数:加载数据、处理数据、绘制图表""" # 设置绘图风格 set_publication_style() # 加载数据 is_deception, ground_truth = load_data() # 验证并过滤数据 df_raw, gold_std = validate_and_filter_data(is_deception, ground_truth) # 准备绘图数据 df_plot, t0_values, baseline_value = prepare_plot_data(df_raw, gold_std) # 绘制图表 plot_deception_window(df_plot, t0_values, baseline_value)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""熵值图绘制脚本功能:比较质量控制(QC)前后标注员判断的条件熵变化输出:Split Violin Plot 对比图,包含统计显著性标注"""
import osimport sys
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom scipy import stats
# 添加项目根目录到路径current_dir = os.path.dirname(os.path.abspath(__file__))project_root = os.path.abspath(os.path.join(current_dir, '..'))sys.path.append(project_root)
from utils.annotator_data import load_biaozhuyuan_datafrom utils.deception_data import load_is_deception_humansfrom utils.entroy import conditional_entropy, binary_entropyfrom utils.plot_style import apply_seaborn_style, save_figure
# ============================================================================# 配置常量# ============================================================================DATA_PATH = os.path.join(project_root, 'data', 'task3_merged010203_40x158_102.json')GROUPS = ['Total', 'Education', 'Age', 'Experience']COLORS = ["#4DBBD5", "#E64B35"] # 蓝色: QC前, 红色: QC后
# ============================================================================# 绘图风格设置# ============================================================================def set_publication_style(): """设置期刊级绘图风格(基于公共样式模块)""" apply_seaborn_style({ "axes.linewidth": 1.5, "xtick.major.width": 1.5, "ytick.major.width": 1.5, })
# ============================================================================# 数据加载与处理# ============================================================================def load_data(): """ 加载标注员数据和欺骗判断数据 Returns: tuple: (标注员属性字典, QC前数据, QC后数据) """ biaozhuyuan = load_biaozhuyuan_data() is_deception0, is_deception1, _ = load_is_deception_humans(DATA_PATH) # 获取标注员ID列表 ids = is_deception0.columns.tolist() # 提取标注员属性 annotator_attrs = { 'education': [biaozhuyuan.loc[aid, 'education'] for aid in ids], 'age': [biaozhuyuan.loc[aid, 'age'] for aid in ids], 'experience': [biaozhuyuan.loc[aid, 'experience'] for aid in ids], } return annotator_attrs, is_deception0, is_deception1
def compute_entropy(data, annotator_attrs): """ 计算各类条件熵 Args: data: 欺骗判断数据 DataFrame annotator_attrs: 标注员属性字典 Returns: dict: 包含各类熵值的字典 """ return { 'Total': data.apply(lambda row: binary_entropy(row), axis=1), 'Education': data.apply(lambda row: conditional_entropy(annotator_attrs['education'], row), axis=1), 'Age': data.apply(lambda row: conditional_entropy(annotator_attrs['age'], row), axis=1), 'Experience': data.apply(lambda row: conditional_entropy(annotator_attrs['experience'], row), axis=1), }
def prepare_long_format(data_pre, data_post, group_order): """ 将数据转换为长格式,便于 seaborn 绑图 Args: data_pre: QC前的熵值字典 data_post: QC后的熵值字典 group_order: 分组顺序列表 Returns: pd.DataFrame: 长格式数据 """ dfs = [] for group in group_order: dfs.append(pd.DataFrame({ 'Group': group, 'Value': data_pre[group], 'Stage': 'Before QC' })) dfs.append(pd.DataFrame({ 'Group': group, 'Value': data_post[group], 'Stage': 'After QC' })) return pd.concat(dfs, ignore_index=True)
# ============================================================================# 统计分析# ============================================================================def add_stat_annotation(ax, data_pre, data_post, group_order, y_max): """ 在图上添加统计显著性标注(配对T检验) Args: ax: matplotlib axes 对象 data_pre: QC前数据 data_post: QC后数据 group_order: 分组顺序 y_max: Y轴最大值 """ for idx, group in enumerate(group_order): v_pre = data_pre[group] v_post = data_post[group] # 根据数据长度选择检验方法 if len(v_pre) == len(v_post): _, p_val = stats.ttest_rel(v_pre, v_post) else: _, p_val = stats.ttest_ind(v_pre, v_post) # 确定显著性标签 if p_val < 0.001: label = "***" elif p_val < 0.01: label = "**" elif p_val < 0.05: label = "*" else: label = "ns" # 绘制标注 x1, x2 = idx - 0.2, idx + 0.2 y, h = y_max + 0.05, 0.03 ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.2, c='k') ax.text((x1 + x2) * 0.5, y + h, label, ha='center', va='bottom', color='k', fontsize=12)
# ============================================================================# 绑图函数# ============================================================================def plot_entropy_comparison(df_long, data_pre, data_post, group_order): """ 绑制熵值对比图(Split Violin + Stripplot + Pointplot) Args: df_long: 长格式数据 data_pre: QC前数据 data_post: QC后数据 group_order: 分组顺序 """ fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True) # 1. Split Violin Plot sns.violinplot( data=df_long, x="Group", y="Value", hue="Stage", split=True, inner=None, palette=COLORS, linewidth=0, alpha=0.7, ax=ax, density_norm="area", common_norm=True, cut=0, width=0.9 ) # 2. 散点图 sns.stripplot( data=df_long, x="Group", y="Value", hue="Stage", dodge=True, jitter=True, size=2.5, alpha=0.5, palette=['#202020', '#202020'], ax=ax, legend=False, zorder=1 )
# 3. 均值和误差棒 sns.pointplot( data=df_long, x="Group", y="Value", hue="Stage", dodge=0.4, linestyles="none", palette=['#101010', '#101010'], markers="d", markersize=5, errorbar="sd", ax=ax, zorder=10 ) # 4. 坐标轴和网格设置 ax.set_xlabel("") ax.set_ylabel("Conditional Entropy ($H$)", fontweight='bold') y_max = df_long['Value'].max() ax.set_ylim(bottom=-0.05, top=y_max + 0.3) ax.yaxis.grid(True, linestyle='--', which='major', color='grey', alpha=0.3) ax.set_yticks(np.arange(0, 1.2, 0.2)) # 5. 添加统计标注 add_stat_annotation(ax, data_pre, data_post, group_order, y_max) # 6. 图例设置 handles, labels = ax.get_legend_handles_labels() ax.legend( handles[:2], ["Before QC", "After QC"], loc='upper right', frameon=False, ncol=1, fontsize=12 ) # 7. 标题 ax.set_title( "Comparison of Entropy Metrics Before and After Quality Control", pad=20, fontweight='bold', fontsize=16 )
# 8. 保存图片(同时保存 PNG 和 PDF) output_path = os.path.join(project_root, 'output', '熵值对比图.png') save_figure(fig, output_path) plt.close(fig)
# ============================================================================# 主函数# ============================================================================def main(): """主函数:加载数据、计算熵值、绑制图表""" # 设置绑图风格 set_publication_style() # 加载数据 annotator_attrs, is_deception0, is_deception1 = load_data() # 计算熵值 entropy_before = compute_entropy(is_deception0, annotator_attrs) entropy_after = compute_entropy(is_deception1, annotator_attrs) # 准备长格式数据 df_long = prepare_long_format(entropy_before, entropy_after, GROUPS) # 绑制图表 plot_entropy_comparison(df_long, entropy_before, entropy_after, GROUPS)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277"""逐轮次准确率分析图分析不同人口统计学特征(年龄、学历、工作经验)的标注员在多轮次欺骗检测任务中的准确率和置信度变化"""
import osimport sysfrom collections import defaultdictfrom itertools import zip_longest
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patch
# 添加项目根目录到路径current_dir = os.path.dirname(os.path.abspath(__file__))project_root = os.path.abspath(os.path.join(current_dir, '..'))sys.path.append(project_root)
from utils.deception_data_per_iteration import ( load_is_deception_humans, load_ground_truth_iteration, load_confidence_humans)from utils.annotator_data import load_biaozhuyuan_data, attribute_valuesfrom utils.tools import get_idsfrom utils.plot_style import apply_style, save_figure
# =============================================================================# 数据处理函数# =============================================================================
def compute_jagged_average_robust(df): """ 计算不规则长度列表的逐位置平均值 处理不同长度的列表,使用 NaN 填充缺失值 """ all_lists = df.values.flatten() aligned_data = list(zip_longest(*all_lists, fillvalue=np.nan)) arr = np.array(aligned_data) if arr.dtype == object: arr[arr == None] = np.nan arr = arr.astype(float) avg_values = np.nanmean(arr, axis=1) return avg_values
def compute_accuracy_per_position(row, gt): """计算每个位置的准确率""" arr = np.array(row.tolist()) gt_arr = np.array(gt) correct = (arr == gt_arr) return correct.mean(axis=0)
def compute_average_accuracy(is_deception, ground_truth): """计算所有样本的平均准确率(按轮次)""" sum_acc = defaultdict(float) count_acc = defaultdict(int)
for idx, row in is_deception.iterrows(): # 硬编码跳过已知异常:该任务该标注员最早记录为空列表 if ( idx == "merged_agent_15.json.json" and "4150322" in row.index and isinstance(row["4150322"], list) and len(row["4150322"]) == 0 ): row = row.drop(labels=["4150322"])
gt = ground_truth.loc[idx] acc = compute_accuracy_per_position(row, gt) for pos, val in enumerate(acc): sum_acc[pos] += val count_acc[pos] += 1
avg_acc = [sum_acc[i] / count_acc[i] for i in sorted(sum_acc.keys())] return avg_acc
# =============================================================================# 数据加载与分组# =============================================================================
def load_data(data_path): """加载所有需要的数据""" is_deception = load_is_deception_humans(data_path)[0] confidences = load_confidence_humans(data_path)[1] ground_truth = load_ground_truth_iteration(data_path) biaozhuyuan = load_biaozhuyuan_data() return is_deception, confidences, ground_truth, biaozhuyuan
def group_by_attributes(biaozhuyuan): """按标注员属性分组获取ID""" ids_by_attribute = { 'age': {}, 'education': {}, 'experience': {} } for key, values in attribute_values().items(): if key in ids_by_attribute: for value in values: ids_by_attribute[key][str(value)] = get_ids(biaozhuyuan, key, value) return ids_by_attribute
def compute_metrics_by_group(ids_dict, is_deception, confidences, ground_truth): """计算每个分组的准确率和置信度""" data = {} for key, value in ids_dict.items(): acc = compute_average_accuracy(is_deception[value], ground_truth) conf = compute_jagged_average_robust(confidences[value]) data[key] = (acc, conf) return data
# =============================================================================# 可视化函数# =============================================================================
def plot_merged_rows_dual_y(data_list, titles, save_path=None): """ 绘制 1行 x 3列 的对比图(双Y轴合并版) 分组顺序、图例顺序、颜色分配均严格按 attribute_values() 的列表顺序。 参数: data_list: 三个场景的数据列表 titles: 每个子图的标题 save_path: 保存路径(可选) """ apply_style() # 严格按 attribute_values() 顺序:各列对应的分组顺序 av = attribute_values() orders = [av['age'], av['education'], av['experience']]
# 三个分组分别使用蓝、红、绿主色调,组内用渐变色(浅→深)区分 n_max = max(len(lst) for lst in orders) blue_gradient = plt.cm.Blues(np.linspace(0.35, 0.9, n_max)) red_gradient = plt.cm.Reds(np.linspace(0.35, 0.9, n_max)) green_gradient = plt.cm.Greens(np.linspace(0.35, 0.9, n_max)) col_gradients = [blue_gradient, red_gradient, green_gradient]
# 画布设置 fig, axes = plt.subplots(1, 3, figsize=(26, 10), dpi=300)
# 循环绘制每一列 for col, current_data in enumerate(data_list): ax_acc = axes[col] ax_conf = ax_acc.twinx() # 设置标题 ax_acc.set_title(titles[col], fontsize=16, fontweight='bold', pad=15) # 图例收集 col_legend_handles = [] col_legend_labels = [] # Y轴范围 ax_acc.set_ylim(0.6, 0.9) ax_conf.set_ylim(3.5, 5.5)
# 绘图参数:仅保留有数据的分组,且严格按 attribute_values() 的列表顺序 models = [m for m in orders[col] if m in current_data] num_models = len(models) total_width = 0.8 bar_width = total_width / num_models # 遍历模型绘图(组内按渐变色顺序) for i, model_name in enumerate(models): acc, conf = current_data[model_name] c = col_gradients[col][i] x = np.arange(1, len(acc) + 1) # 绘制准确率折线 l1, = ax_acc.plot( x, acc, color=c, linestyle='-', linewidth=2.5, alpha=0.9, zorder=10, label=model_name ) # 绘制置信度柱状图 x_pos = x - (total_width / 2) + (i * bar_width) + (bar_width / 2) ax_conf.bar(x_pos, conf, width=bar_width, color=c, alpha=0.9, label=model_name) col_legend_handles.append(l1) col_legend_labels.append(model_name)
# 图例设置 h_acc_sample = Line2D([], [], color='gray', linestyle='-', linewidth=2) h_conf_sample = Patch(facecolor='gray', alpha=0.5)
final_handles = col_legend_handles + [h_acc_sample, h_conf_sample] final_labels = col_legend_labels + ['Accuracy (Line)', 'Confidence (Bar)']
ax_acc.legend( handles=final_handles, labels=final_labels, loc='center left', bbox_to_anchor=(0, 0.55), fontsize=10, frameon=True, framealpha=0.9, edgecolor='gray', borderpad=0.8 )
# 轴标签 ax_acc.set_ylabel('Accuracy', fontsize=12, fontweight='bold') ax_conf.set_ylabel('Confidence', fontsize=12, fontweight='bold', rotation=270, labelpad=15) ax_acc.set_xlabel('Round', fontsize=12, fontweight='bold')
# 样式美化 ax_acc.grid(True, linestyle=':', alpha=0.4) ax_acc.spines['top'].set_visible(False) ax_conf.spines['top'].set_visible(False) ax_acc.tick_params(axis='both', labelsize=10) ax_conf.tick_params(axis='y', labelsize=10) ax_acc.set_xticks(np.arange(1, len(acc) + 1))
plt.tight_layout() # 保存图片(同时保存 PNG 和 PDF) if save_path: save_figure(fig, save_path) plt.close(fig)
# =============================================================================# 主程序# =============================================================================
def main(): # 配置路径(相对路径,输出到主目录 output,同时保存 PNG 和 PDF) data_path = os.path.join(project_root, 'data', 'task3_merged010203_40x158_102.json') output_path = os.path.join(project_root, 'output', '逐轮次准确率.png') # 加载数据 print("加载数据...") is_deception, confidences, ground_truth, biaozhuyuan = load_data(data_path) # 按属性分组 print("按属性分组...") ids_by_attribute = group_by_attributes(biaozhuyuan) # 计算各分组指标 print("计算指标...") data_age = compute_metrics_by_group( ids_by_attribute['age'], is_deception, confidences, ground_truth ) data_education = compute_metrics_by_group( ids_by_attribute['education'], is_deception, confidences, ground_truth ) data_experience = compute_metrics_by_group( ids_by_attribute['experience'], is_deception, confidences, ground_truth ) # 绘图 print("绑制图表...") all_data = [data_age, data_education, data_experience] titles = ['Age', 'Education Level', 'Work Experience'] plot_merged_rows_dual_y(all_data, titles, save_path=output_path) print("完成!")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667#!/usr/bin/env python3"""一键运行 plot/ 目录下所有绘图脚本
用法(在项目主目录 figure_plot 下执行): python run_all_plots.py
或指定只运行部分脚本(按顺序,空格分隔): python run_all_plots.py ECEandAUC 桑基图"""
import osimport sysimport subprocess
# 项目主目录(本脚本所在目录)PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))PLOT_DIR = os.path.join(PROJECT_ROOT, 'plot')
def list_plot_scripts(): """列出 plot 目录下所有 .py 脚本(不含本脚本)""" scripts = [] for name in sorted(os.listdir(PLOT_DIR)): if name.endswith('.py') and not name.startswith('_'): scripts.append(name[:-3]) # 去掉 .py return scripts
def main(): os.chdir(PROJECT_ROOT) all_scripts = list_plot_scripts()
# 若命令行指定了脚本名,只运行这些 if len(sys.argv) > 1: requested = [s for s in sys.argv[1:] if s in all_scripts] if not requested: print("未找到匹配的脚本。可选:", ", ".join(all_scripts)) sys.exit(1) to_run = requested else: to_run = all_scripts
print(f"将依次运行 {len(to_run)} 个绘图脚本: {', '.join(to_run)}\n") failed = []
for name in to_run: path = os.path.join(PLOT_DIR, name + '.py') print("=" * 60) print(f"运行: {name}.py") print("=" * 60) ret = subprocess.run( [sys.executable, path], cwd=PROJECT_ROOT, ) if ret.returncode != 0: failed.append(name) print()
if failed: print("以下脚本执行失败:", ", ".join(failed)) sys.exit(1) print("全部完成。")
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839# Utils module - 数据处理辅助函数"""数据处理工具模块================
包含以下子模块:- tools: 投票、ID筛选等通用工具函数- metrics: AUC、ECE 等评估指标计算- kappa: Cohen's Kappa、Fleiss' Kappa 一致性指标- entropy: 熵值计算函数- annotator_data: 标注员信息加载- deception_data: 欺骗性标注数据加载(整体)- deception_data_per_iteration: 欺骗性标注数据加载(逐轮次)- plot_style: 公共绑图样式与保存工具"""
from .tools import vote, get_idsfrom .metrics import calculate_auc, calculate_ecefrom .kappa import cohen_kappa, fleiss_kappa_from_labels, compute_group_kappafrom .entroy import binary_entropy, conditional_entropyfrom .annotator_data import load_biaozhuyuan_data, attribute_values, map_age, map_experience, map_educationfrom .deception_data import ( load_data, load_is_deception_humans, load_confidences, load_ground_truth_deception_expert, load_full_is_deception_humans, load_full_confidences, earliest_values, latest_values, extended_values)from .deception_data_per_iteration import ( load_data as load_data_per_iteration, load_is_deception_humans as load_is_deception_per_iteration, load_confidence_humans as load_confidence_per_iteration, load_ground_truth_iteration)from .plot_style import apply_style, apply_seaborn_style, save_figure, DPI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import pandas as pdimport numpy as np
def map_age(age): if age <= 30: return 'Below 30 years old' elif 31 <= age <= 40: return 'Age 31-40' else: return 'Above 40 years old'
def map_experience(years): if years <= 1: return '1 year' elif years == 2: return '2 years' elif years == 3: return '3 years' elif years >= 4: return '4 years and above'
def map_education(education): if education == '中专': return 'Vocational' elif education == '高中': return 'High School' elif education == '大专': return 'Associate' elif education == '本科': return 'Bachelor' elif education == '硕士': return 'Master'
def load_biaozhuyuan_data():
biaozhuyuan = pd.read_excel('/Users/junhao/Documents/Deception_Alignment/数据处理/data/标注员信息收集(40人).xlsx')
biaozhuyuan = biaozhuyuan[['龙猫ID', '年龄', '最高学历', '从事标注行业的年数\n(0年也没关系,是多久就写多久)']] biaozhuyuan.columns = ['id', 'age', 'education', 'experience']
biaozhuyuan['experience'] = biaozhuyuan['experience'].str.replace('年', '') biaozhuyuan['experience'] = biaozhuyuan['experience'].str.replace('3个月', '0.25') biaozhuyuan['experience'] = biaozhuyuan['experience'].str.replace('半', '0.5')
biaozhuyuan['experience'] = pd.to_numeric(biaozhuyuan['experience'], errors='coerce') biaozhuyuan['age'] = pd.to_numeric(biaozhuyuan['age'], errors='coerce')
biaozhuyuan['age'] = biaozhuyuan['age'].apply(map_age) biaozhuyuan['experience'] = biaozhuyuan['experience'].apply(map_experience) biaozhuyuan['education'] = biaozhuyuan['education'].apply(map_education)
biaozhuyuan['id'] = biaozhuyuan['id'].astype(str) biaozhuyuan.set_index('id', inplace=True)
return biaozhuyuan
def attribute_values():
return { 'age': ['Below 30 years old', 'Age 31-40', 'Above 40 years old'], 'education': ['Vocational', 'High School', 'Associate', 'Bachelor', 'Master'], 'experience': ['1 year', '2 years', '3 years', '4 years and above'], }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392import jsonimport ijsonimport pandas as pdimport numpy as npimport refrom collections import defaultdict
from collections.abc import Iterable
def calculate_value_lengths(data, skip_keys=None): """ 统计嵌套结构中所有 value 的总字符串长度。 参数: data: 嵌套的 list/dict 结构 skip_keys: 指定哪些 key 的 value 需要跳过 返回: int: 所有字符串化的 value 的总长度 """ if skip_keys is None: skip_keys = ["role", "thought","iteration","message", "reply","timestamp","id","type"]
total_length = 0
def _recurse(obj): nonlocal total_length
if isinstance(obj, dict): for k, v in obj.items(): if k in skip_keys: continue _recurse(v)
elif isinstance(obj, list): for item in obj: _recurse(item)
else: # 基本类型 → 转成字符串后加长度 try: s = str(obj) total_length += len(s) except: pass # 防御性处理
_recurse(data) return total_length
def load_data(path): time = pd.read_excel('/Users/junhao/Documents/Deception_Alignment/数据处理/data/标注员做题时间数据.xlsx')
time['during'] = time['提交时间'] - time['开始做题时间'] time['during'] = time['during'].dt.total_seconds() / 60
deception_behaviors = defaultdict(lambda: defaultdict(list)) confidences = defaultdict(lambda: defaultdict(list)) is_deception_humans = defaultdict(lambda: defaultdict(list)) judge_reasons = defaultdict(lambda: defaultdict(list)) attribution_rankings = defaultdict(lambda: defaultdict(list)) primary_specific_factors = defaultdict(lambda: defaultdict(list)) durings = defaultdict(lambda: defaultdict(list)) iterations = defaultdict(lambda: defaultdict(list)) history_lens = defaultdict(lambda: defaultdict(list))
def _parse_judge_confidence(raw): if isinstance(raw, (list, tuple)): if not raw: return np.nan raw = raw[0] if raw is None: return np.nan if isinstance(raw, str): raw = raw.strip() if raw == "": return np.nan if isinstance(raw, str): match = re.search(r"\d+", raw) if not match: return np.nan raw = match.group(0) try: return int(raw) except (ValueError, TypeError): return np.nan
with open(path, 'r', encoding='utf-8') as f: data = json.load(f)
for i, item in enumerate(data):
task = item['dialog_file']
item = item['dialog_data']
history = item['dialog_history'] history_len = calculate_value_lengths(history)
annotator = item['annotator_id']
if annotator == '4218307': annotator = '4194055'
iteration = item['iterations'] ctime = item['ctime'] id = item['id'] id = int(id) during = time[(time['id'] == id)]['during'].values
durings[annotator][task].append((during, ctime)) deception_behaviors[annotator][task].append((item['deception_behavior'], ctime)) is_deception_humans[annotator][task].append((int(1) if item['is_deception_human'] == '存在' else int(0), ctime)) raw_confidence = item.get('confidence_assessment', {}).get('judge_confidence') confidences[annotator][task].append((_parse_judge_confidence(raw_confidence), ctime)) judge_reasons[annotator][task].append((item['confidence_assessment']['judge_reason'], ctime)) attribution_rankings[annotator][task].append((item['deception_attribution']['attribution_ranking'], ctime)) primary_specific_factors[annotator][task].append((item['deception_attribution']['primary_specific_factor'], ctime)) iterations[annotator][task].append((iteration, ctime)) history_lens[annotator][task].append((history_len, ctime))
deception_behaviors_df = pd.DataFrame(deception_behaviors) confidences_df = pd.DataFrame(confidences) is_deception_humans_df = pd.DataFrame(is_deception_humans) judge_reasons_df = pd.DataFrame(judge_reasons) attribution_rankings_df = pd.DataFrame(attribution_rankings) primary_specific_factors_df = pd.DataFrame(primary_specific_factors) durings_df = pd.DataFrame(durings) iterations_df = pd.DataFrame(iterations) history_lens_df = pd.DataFrame(history_lens)
deception_behaviors_df = sort_dataframe_cells_by_time(deception_behaviors_df) confidences_df = sort_dataframe_cells_by_time(confidences_df) is_deception_humans_df = sort_dataframe_cells_by_time(is_deception_humans_df) judge_reasons_df = sort_dataframe_cells_by_time(judge_reasons_df) attribution_rankings_df = sort_dataframe_cells_by_time(attribution_rankings_df) primary_specific_factors_df = sort_dataframe_cells_by_time(primary_specific_factors_df) durings_df = sort_dataframe_cells_by_time(durings_df) iterations_df = sort_dataframe_cells_by_time(iterations_df) history_lens_df = sort_dataframe_cells_by_time(history_lens_df)
return (deception_behaviors_df, confidences_df, is_deception_humans_df, judge_reasons_df, attribution_rankings_df, primary_specific_factors_df, durings_df, iterations_df, history_lens_df)
def sort_dataframe_cells_by_time(df): """ 对 DataFrame 的每个单元格进行排序。 每个单元格内是一个列表,列表的元素为元组 (value, 'YYYY/MM/DD HH:MM')。
防御式处理: - 如果单元格不是 list,原样返回; - 如果 list 内部元素格式不满足 (value, time_str),原样返回; - 时间解析失败也原样返回。 """ def safe_sort_cell(cell): # 情况 1:不是 list —— 直接返回 if not isinstance(cell, list): return cell
# 情况 2:list 内部不是我们期望的元组形式 —— 不排序,直接返回 # 要求 cell[i] 至少是长度 >= 2 的可索引结构(如 tuple 或 list) for item in cell: if not (isinstance(item, (list, tuple)) and len(item) >= 2): return cell
# 情况 3:尝试按照时间排序 try: return sorted(cell, key=lambda x: pd.to_datetime(x[1])) except Exception: # 时间格式异常,也保持原样 return cell
return df.map(safe_sort_cell)
def earliest_values(df): """ 对排好序的 DataFrame,每个单元格内取最早时间对应的 value(元组的第一个元素)。 返回一个同形状的 DataFrame,仅包含对应的 value。
参数 ------- df : pandas.DataFrame 已排序,每个单元格是 list[tuple(value, time_str)]
返回 ------- pandas.DataFrame 与 df 同形状,每个单元格是该列表中最早时间对应的 value """ return df.map(lambda lst: lst[0][0])
def latest_values(df): """ 对排好序的 DataFrame,每个单元格内取最晚时间对应的 value(元组的第一个元素)。 返回一个同形状的 DataFrame,仅包含对应的 value。
参数 ------- df : pandas.DataFrame 已排序,每个单元格是 list[tuple(value, time_str)]
返回 ------- pandas.DataFrame 与 df 同形状,每个单元格是该列表中最晚时间对应的 value """ return df.map(lambda lst: lst[-1][0])
def extended_values(df): # 1. 计算全局最大长度 n # df.applymap 在 pandas 2.1+ 中被重命名为 df.map,为了兼容性这里用 applymap, # .values.max() 确保拿到的是标量而不是 Series current_max = df.map(len).values.max() if not df.empty else 0 n = max(current_max, 1) def pad_row(lst): # 提取当前数据 current_data = [t[0] for t in lst] # 提取填充值 (最后一个元素的第一个值) pad_value = lst[-1][0] # 2. 修正:使用 [pad_value] * count 来生成列表进行拼接 padding = [pad_value] * (n - len(lst)) return current_data + padding
# 应用转换 extend_df = df.map(pad_row) return extend_df
def load_is_deception_humans(path): return earliest_values(load_data(path)[2]), latest_values(load_data(path)[2]), extended_values(load_data(path)[2])
def load_deception_behaviors(path): return earliest_values(load_data(path)[0]), latest_values(load_data(path)[0]), extended_values(load_data(path)[0])
def load_confidences(path): return earliest_values(load_data(path)[1]), latest_values(load_data(path)[1]), extended_values(load_data(path)[1])
def load_judge_reasons(path): return earliest_values(load_data(path)[3]), latest_values(load_data(path)[3]), extended_values(load_data(path)[3])
def load_attribution_rankings(path): return earliest_values(load_data(path)[4]), latest_values(load_data(path)[4]), extended_values(load_data(path)[4])
def load_primary_specific_factors(path): return earliest_values(load_data(path)[5]), latest_values(load_data(path)[5]), extended_values(load_data(path)[5])
def load_durings(path): return earliest_values(load_data(path)[6]), latest_values(load_data(path)[6]), extended_values(load_data(path)[6])
def load_iterations(path): return earliest_values(load_data(path)[7]), latest_values(load_data(path)[7]), extended_values(load_data(path)[7])
def load_history_lens(path): return earliest_values(load_data(path)[8]), latest_values(load_data(path)[8]), extended_values(load_data(path)[8])
def load_ground_truth_deception(path):
data = load_is_deception_humans(path)[1] ground_truth = data.mode(axis=1).iloc[:, 0] return ground_truth
def load_ground_truth_deception_expert(path):
data = load_is_deception_humans(path)[1] experts = ['3680511', '3626969', '4163588', '4204611', '3996326', '4220392', '3038429'] data = data[experts] ground_truth = data.mode(axis=1).iloc[:, 0] return ground_truth
def load_full_is_deception_humans(path): return load_data(path)[2]
def load_full_confidences(path): return load_data(path)[1]
def load_data_uuid(path): time = pd.read_excel('/Users/junhao/Documents/Deception_Alignment/数据处理/data/标注员做题时间数据.xlsx')
time['during'] = time['提交时间'] - time['开始做题时间'] time['during'] = time['during'].dt.total_seconds() / 60
deception_behaviors = defaultdict(lambda: defaultdict(list)) confidences = defaultdict(lambda: defaultdict(list)) is_deception_humans = defaultdict(lambda: defaultdict(list)) judge_reasons = defaultdict(lambda: defaultdict(list)) attribution_rankings = defaultdict(lambda: defaultdict(list)) primary_specific_factors = defaultdict(lambda: defaultdict(list)) durings = defaultdict(lambda: defaultdict(list)) iterations = defaultdict(lambda: defaultdict(list)) history_lens = defaultdict(lambda: defaultdict(list))
with open(path, 'r', encoding='utf-8') as f: data = json.load(f)
for i, item in enumerate(data):
task = item['uuid']
item = item['dialog_data']
history = item['dialog_history'] history_len = calculate_value_lengths(history)
annotator = item['annotator_id']
if annotator == '4218307': annotator = '4194055'
iteration = item['iterations'] ctime = item['ctime'] id = item['id'] id = int(id) during = time[(time['id'] == id)]['during'].values
durings[annotator][task].append((during, ctime)) deception_behaviors[annotator][task].append((item['deception_behavior'], ctime)) is_deception_humans[annotator][task].append((int(1) if item['is_deception_human'] == '存在' else int(0), ctime)) confidences[annotator][task].append((int(item['confidence_assessment']['judge_confidence'][0]), ctime)) judge_reasons[annotator][task].append((item['confidence_assessment']['judge_reason'], ctime)) attribution_rankings[annotator][task].append((item['deception_attribution']['attribution_ranking'], ctime)) primary_specific_factors[annotator][task].append((item['deception_attribution']['primary_specific_factor'], ctime)) iterations[annotator][task].append((iteration, ctime)) history_lens[annotator][task].append((history_len, ctime))
deception_behaviors_df = pd.DataFrame(deception_behaviors) confidences_df = pd.DataFrame(confidences) is_deception_humans_df = pd.DataFrame(is_deception_humans) judge_reasons_df = pd.DataFrame(judge_reasons) attribution_rankings_df = pd.DataFrame(attribution_rankings) primary_specific_factors_df = pd.DataFrame(primary_specific_factors) durings_df = pd.DataFrame(durings) iterations_df = pd.DataFrame(iterations) history_lens_df = pd.DataFrame(history_lens)
deception_behaviors_df = sort_dataframe_cells_by_time(deception_behaviors_df) confidences_df = sort_dataframe_cells_by_time(confidences_df) is_deception_humans_df = sort_dataframe_cells_by_time(is_deception_humans_df) judge_reasons_df = sort_dataframe_cells_by_time(judge_reasons_df) attribution_rankings_df = sort_dataframe_cells_by_time(attribution_rankings_df) primary_specific_factors_df = sort_dataframe_cells_by_time(primary_specific_factors_df) durings_df = sort_dataframe_cells_by_time(durings_df) iterations_df = sort_dataframe_cells_by_time(iterations_df) history_lens_df = sort_dataframe_cells_by_time(history_lens_df)
return (deception_behaviors_df, confidences_df, is_deception_humans_df, judge_reasons_df, attribution_rankings_df, primary_specific_factors_df, durings_df, iterations_df, history_lens_df)
def load_is_deception_humans_uuid(path): return earliest_values(load_data_uuid(path)[2]), latest_values(load_data_uuid(path)[2]), extended_values(load_data_uuid(path)[2])
def load_ground_truth_deception_expert_uuid(path):
data = load_is_deception_humans_uuid(path)[1] experts = ['3680511', '3626969', '4163588', '4204611', '3996326', '4220392', '3038429'] data = data[experts] ground_truth = data.mode(axis=1).iloc[:, 0] return ground_truth123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import jsonimport ijsonimport pandas as pdimport numpy as npfrom collections import defaultdictimport pandas as pdimport numpy as npfrom scipy.stats import modefrom collections.abc import Iterable
def parse_bool_string(s): """ Parse strings like "1:true,2:f,3:False" into a list of 0/1. Fuzzy match: - startswith('t' or 'T') -> 1 - startswith('f' or 'F') -> 0 """ result = [] for item in s.split(","): if not item.strip(): # ignore empty segments like trailing commas or empty strings continue if ":" not in item: # ignore malformed segments without key:value continue _, val = item.split(":", 1) val = val.strip().lower() result.append(1 if val.startswith("t") else 0)
return result
def load_data(path):
is_deception_per_iteration = defaultdict(lambda: defaultdict(list)) confidence_per_iteration = defaultdict(lambda: defaultdict(list))
with open(path, 'r', encoding='utf-8') as f: data = json.load(f)
for i, item in enumerate(data): task = item['dialog_file'] item = item['dialog_data'] annotator = item['annotator_id']
if annotator == '4218307': annotator = '4194055'
ctime = item['ctime']
confidence_of_iterations = []
annotation_of_interations = item['annotation_of_interations']
for ann in annotation_of_interations:
if len(ann['confidence_assessment']['judge_confidence']) > 0: confidence_of_iterations.append(int(ann['confidence_assessment']['judge_confidence'][0])) else: confidence_of_iterations.append(None)
is_deception = item['iterations_of_deception']
is_deception_list = parse_bool_string(is_deception) is_deception_list = is_deception_list[:-1]
is_deception_per_iteration[annotator][task].append((is_deception_list, ctime)) confidence_per_iteration[annotator][task].append((confidence_of_iterations, ctime))
is_deception_per_iteration_df = pd.DataFrame(is_deception_per_iteration) is_deception_per_iteration_df = sort_dataframe_cells_by_time(is_deception_per_iteration_df)
confidence_per_iteration_df = pd.DataFrame(confidence_per_iteration) confidence_per_iteration_df = sort_dataframe_cells_by_time(confidence_per_iteration_df)
return is_deception_per_iteration_df, confidence_per_iteration_df
def sort_dataframe_cells_by_time(df): """ 对 DataFrame 的每个单元格进行排序。 每个单元格内是一个列表,列表的元素为元组 (value, 'YYYY/MM/DD HH:MM')。 按时间从早到晚排序。
参数 ------- df : pandas.DataFrame 输入的 DataFrame,每个单元格是 list[tuple(value, time_str)]
返回 ------- pandas.DataFrame 每个单元格内部已排序的新 DataFrame """ return df.map(lambda lst: sorted(lst, key=lambda x: pd.to_datetime(x[1])))
def earliest_values(df): """ 对排好序的 DataFrame,每个单元格内取最早时间对应的 value(元组的第一个元素)。 返回一个同形状的 DataFrame,仅包含对应的 value。
参数 ------- df : pandas.DataFrame 已排序,每个单元格是 list[tuple(value, time_str)]
返回 ------- pandas.DataFrame 与 df 同形状,每个单元格是该列表中最早时间对应的 value """ return df.map(lambda lst: lst[0][0])
def latest_values(df): """ 对排好序的 DataFrame,每个单元格内取最晚时间对应的 value(元组的第一个元素)。 返回一个同形状的 DataFrame,仅包含对应的 value。
参数 ------- df : pandas.DataFrame 已排序,每个单元格是 list[tuple(value, time_str)]
返回 ------- pandas.DataFrame 与 df 同形状,每个单元格是该列表中最晚时间对应的 value """ return df.map(lambda lst: lst[-1][0])
def load_is_deception_humans(path): return earliest_values(load_data(path)[0]), latest_values(load_data(path)[0])
def load_confidence_humans(path): return earliest_values(load_data(path)[1]), latest_values(load_data(path)[1])
def load_ground_truth_iteration(path):
expert = ['3680511', '3626969', '4163588', '4204611', '3996326', '4220392', '3038429']
data = load_is_deception_humans(path)[1][expert]
def majority_vote_row(row): # row 是一行,row.tolist() 是多个等长 list arr = np.array(row.tolist()) # shape = (num_annotators, seq_len) m, _ = mode(arr, axis=0, keepdims=False) return m.tolist()
majority_series = data.apply(majority_vote_row, axis=1)
return majority_series
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import numpy as np
def binary_entropy(labels): """ 计算二分类标签的熵(Shannon Entropy) 参数: labels: list 或 numpy 数组,只包含 0 和 1,例如 [0,1,1,0,1]
返回: float,熵值,单位 bit
示例: print(binary_entropy([0,1,1,0,1])) # 输出示例熵值 """ labels = np.array(labels) p1 = np.mean(labels == 1) p0 = 1 - p1
# 去掉 p=0 的项以避免 p*log(p) 出现 nan probs = np.array([p0, p1]) probs = probs[probs > 0]
# 熵 H = -np.sum(probs * np.log2(probs))
return H
def conditional_entropy(X, Y): """ 计算条件熵 H(Y|X),支持 X 为字符串类型。 参数: X: list 或 numpy 数组,条件变量,例如 ['red', 'red', 'blue', 'blue', 'blue'] Y: list 或 numpy 数组,目标变量,例如 [1, 0, 1, 1, 0] 注: - X 和 Y 必须长度一致,一一对应。 - X 的取值可以是字符串、布尔值、数字或其他可哈希类型。 - Y 的取值可以是数字、字符串、布尔值等。 返回: float,条件熵 H(Y|X),单位 bit 示例: X = ['red', 'red', 'blue', 'blue', 'blue'] Y = [1, 0, 1, 1, 0] print(conditional_entropy(X, Y)) 解释: 1. X='red' 的样本对应的 Y=[1,0],计算 H(Y|X='red') 2. X='blue' 的样本对应的 Y=[1,1,0],计算 H(Y|X='blue') 3. 按 P(X=x) 加权求和得到 H(Y|X) """
X = np.array(X) Y = np.array(Y) assert len(X) == len(Y)
H = 0.0 total = len(X)
unique_x = np.unique(X)
for x in unique_x: # 筛选 X = x 的样本 idx = (X == x) subset_Y = Y[idx]
# P(X=x) px = np.sum(idx) / total
# 计算 H(Y|X=x) values, counts = np.unique(subset_Y, return_counts=True) probs = counts / counts.sum() probs = probs[probs > 0] # 去掉概率为0的项
Hy_given_x = -np.sum(probs * np.log2(probs))
# 累加加权熵 H += px * Hy_given_x
return H123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158import numpy as npfrom collections import Counterfrom statsmodels.stats.inter_rater import fleiss_kappafrom sklearn.metrics import confusion_matriximport pandas as pdfrom utils.tools import get_ids, votefrom sklearn.metrics import cohen_kappa_score
# -------------------------------------------------------------# 1. 计算 Cohen's Kappa(适用于两个评价者)# -------------------------------------------------------------def cohen_kappa(y1, y2): """ 计算两个评级者(两个标签向量)之间的一致性:Cohen's Kappa 参数: y1: list 或 numpy 数组,第一个评价者的标签 y2: list 或 numpy 数组,第二个评价者的标签
返回值: kappa: 浮点数,Cohen’s Kappa 值
示例: y1 = [0, 1, 2, 1] y2 = [0, 2, 2, 1] print(cohen_kappa(y1, y2)) """ y1 = np.array(y1) y2 = np.array(y2) assert len(y1) == len(y2)
labels = np.unique(np.concatenate([y1, y2])) conf_mat = confusion_matrix(y1, y2, labels=labels)
# 观测一致率 po = np.trace(conf_mat) / np.sum(conf_mat) # 随机一致率 pe = np.sum(np.sum(conf_mat, axis=1) * np.sum(conf_mat, axis=0)) \ / (np.sum(conf_mat) ** 2)
# Kappa kappa = (po - pe) / (1 - pe) return kappa
# -------------------------------------------------------------# 2. 计算 Fleiss' Kappa(适用于 3 个及以上评价者)# -------------------------------------------------------------def fleiss_kappa_from_labels(label_lists): """ 根据多个评价者的标签向量计算群体一致性:Fleiss' Kappa 参数: label_lists: list(list),例如: [ [0,1,0,2], # rater1 [0,1,1,2], # rater2 [0,1,0,2], # rater3 ]
返回值: kappa: 浮点数,Fleiss’ Kappa 值
示例: raters = [ [0,1,0,2], [0,1,1,2], [0,1,0,2], ] print(fleiss_kappa_from_labels(raters)) """
# 转成 numpy,方便处理 arr = np.array(label_lists)
# 样本数量 N N = arr.shape[1] # 全部可能的类别 all_labels = np.unique(arr) k = len(all_labels)
# 构造 N × k 的统计矩阵 rating_matrix = np.zeros((N, k), dtype=int)
for sample_idx in range(N): sample_labels = arr[:, sample_idx] # 某个样本所有评价者的标签 counts = Counter(sample_labels) for j, lab in enumerate(all_labels): rating_matrix[sample_idx, j] = counts.get(lab, 0)
# 计算 Fleiss' Kappa return fleiss_kappa(rating_matrix)
# -------------------------------------------------------------# 3. 计算组间 Cohen's Kappa 交叉矩阵# -------------------------------------------------------------def compute_group_kappa(df_votes, df_info, attributes): """ 为每个属性、每个属性取值(称为核心组),计算核心组投票结果与该属性下 每个组内每个标注者的 Cohen's kappa(列表形式)。
参数: df_votes (pd.DataFrame): 标注结果表(行是样本,列是标注者)。 df_info (pd.DataFrame): 标注者属性表(行是标注者索引,应与 df_votes.columns 对应)。 attributes (dict): 字典,键为属性名,值为该属性的取值列表(values)。 例: {"gender": ["male","female"], "age_group": ["young","old"]}
返回: list: 嵌套列表 results,结构如下(按属性顺序): results = [ attribute1_result, attribute2_result, ... ] 其中 attribute_result 的结构为: attribute_result = [ core_value1_result, # 对应 attributes[attribute][0] core_value2_result, # 对应 attributes[attribute][1] ... ] 每个 core_value_result(命名为 group_kappa_list)为一个列表: group_kappa_list = [ kappas_vs_group_value1, # 列表:core_votes vs 每个标注者(属于 group_value1)逐个计算的 kappa 值 kappas_vs_group_value2, # 列表:core_votes vs 每个标注者(属于 group_value2)的 kappa 值 ... ] 说明: - 在计算 kappa 前,会先对 core_votes 与单个标注者列进行样本级对齐,剔除任一方为 NaN 的样本。 - 若在对齐后没有样本可用于计算(长度为 0),该 pair 的 kappa 设为 np.nan。 """ results = [] for attribute, values in attributes.items(): attribute_result = [] for value in values: core_ids = get_ids(df_info, attribute, value) core_votes = vote(df_votes, core_ids)
group_kappa_list = [] for group_value in values: group_ids = get_ids(df_info, attribute, group_value) kappas = [] for annotator in group_ids: # 对齐并去除任一方为 NaN 的样本 paired = pd.concat([core_votes, df_votes[annotator]], axis=1) paired = paired.dropna() if paired.shape[0] == 0: kappas.append(np.nan) else: k = cohen_kappa_score(paired.iloc[:,0], paired.iloc[:,1], labels=[0,1]) kappas.append(k) group_kappa_list.append(kappas) attribute_result.append(group_kappa_list) results.append(attribute_result) return results12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182from sklearn.metrics import roc_auc_scoreimport numpy as np
def calculate_auc(y_true, y_score): """ 计算离散或连续预测分数的 AUC(ROC 曲线下面积) y_score 不要求在 0-1 之间,要满足越大的值代表越可能是正样本 参数: y_true : list 或 array,真实标签(0 或 1) y_score : list 或 array,模型给出的分数,可以是离散的或连续的 返回: float,AUC 值(0~1) 说明: - AUC 衡量模型区分正负样本的排序能力,与分数是否离散无关。 - sklearn 会自动处理分数平局(tie)情况: * 正样本分数 > 负样本分数 → 计 1 * 正样本分数 = 负样本分数 → 计 0.5 * 正样本分数 < 负样本分数 → 计 0 - AUC 代表从所有“正样本-负样本”对中, 正样本分数更高的概率(平局算 0.5)。 """ return roc_auc_score(y_true, y_score)
def calculate_ece(y_true, y_score, n_bins=10): """ 计算模型的 ECE(Expected Calibration Error),并在内部将模型输出从 [-5, 5] 线性映射到 [0, 1],用于概率校准评价。
使用说明: -------------------------------------------- 输入: y_true : 真实标签(0 或 1) y_score : 模型输出,取值范围为 [-5, 5](越大越可能是正类) n_bins : ECE 的分桶数量,默认 10
处理步骤: 1. 将 y_score 从 [-5, 5] 线性映射到 [0, 1]: p = (x + 5) / 10 2. 将映射后的概率分成 n_bins 个区间(等宽分桶) 3. 对每个桶计算: - conf = 该桶平均预测概率 - acc = 该桶真实准确率 4. 根据 ECE 公式进行加权求和
返回: ece : 一个浮点数,表示整体校准误差(越小越好) -------------------------------------------- """ y_true = np.array(y_true) y_score = np.array(y_score)
y_prob = (y_score + 5) / 10 bin_edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0 n = len(y_true)
for i in range(n_bins): start = bin_edges[i] end = bin_edges[i + 1]
idx = (y_prob >= start) & (y_prob < end)
if np.sum(idx) == 0: continue # 此桶没有样本则跳过
conf = np.mean(y_prob[idx]) acc = np.mean(y_true[idx]) weight = np.sum(idx) / n
ece += weight * abs(acc - conf)
return ece
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""公共绘图样式模块
统一管理所有绑图脚本的字体、DPI、颜色等视觉配置,确保论文图表风格一致。"""
import osimport matplotlib.pyplot as plt
# =============================================================================# 全局样式常量# =============================================================================DPI = 300
FONT_FAMILY = 'sans-serif'FONT_SANS_SERIF = ['Arial', 'Helvetica', 'DejaVu Sans']
RC_BASE = { 'font.family': FONT_FAMILY, 'font.sans-serif': FONT_SANS_SERIF, 'axes.unicode_minus': False, 'mathtext.fontset': 'dejavusans', 'axes.linewidth': 1.2, 'axes.spines.top': False, 'axes.spines.right': False, 'xtick.direction': 'in', 'ytick.direction': 'in', 'xtick.major.width': 1.2, 'ytick.major.width': 1.2, 'grid.linestyle': '--', 'grid.alpha': 0.4, 'legend.frameon': False, 'figure.dpi': DPI,}
# =============================================================================# 样式应用函数# =============================================================================def apply_style(extra_rc: dict | None = None): """ 应用统一的绘图样式。
Parameters ---------- extra_rc : dict, optional 额外的 rcParams 覆盖项,会合并到基础样式之上。 """ rc = dict(RC_BASE) if extra_rc: rc.update(extra_rc) plt.rcParams.update(rc)
def apply_seaborn_style(extra_rc: dict | None = None): """ 应用基于 seaborn 的统一样式(适用于使用 seaborn 绑图的脚本)。
在 seaborn.set_theme 之后再覆盖 rcParams, 确保字体等关键设置不被 seaborn 默认值冲掉。 """ import seaborn as sns sns.set_theme(style="ticks", context="paper")
rc = dict(RC_BASE) if extra_rc: rc.update(extra_rc) plt.rcParams.update(rc)
# =============================================================================# 保存工具# =============================================================================def save_figure(fig, path: str, *, dpi: int = DPI, extensions=('.png', '.pdf'), bbox_inches='tight', facecolor='white', **kwargs): """ 同时保存 PNG 和 PDF(或自定义格式列表)。
Parameters ---------- fig : matplotlib.figure.Figure path : str 输出路径(含扩展名),函数会自动替换为 extensions 中的每种格式。 dpi : int extensions : tuple[str, ...] bbox_inches : str facecolor : str **kwargs : 传递给 fig.savefig 的其他参数 """ out_dir = os.path.dirname(path) if out_dir: os.makedirs(out_dir, exist_ok=True)
base, _ = os.path.splitext(path) for ext in extensions: out = base + ext fig.savefig(out, dpi=dpi, bbox_inches=bbox_inches, facecolor=facecolor, **kwargs) print(f"图片已保存至: {out}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849def vote(df, ids): """ 对输入的标注 DataFrame 进行投票表决(多数表决法)。
参数: df (pandas.DataFrame): 包含多名标注者结果的 DataFrame。 行表示样本,列表示标注者。 ids (list): 需要参与投票的标注者列名列表。
返回: pandas.Series: 按样本索引返回投票结果(0 或 1)。 对每个样本,若有效标注(非空)的 1 的比例 >= 0.5 则输出 1,否则输出 0。 """
# 选取需要参与投票的标注列 sub_df = df[ids]
# 每个样本中 1 的数量 votes = sub_df.sum(axis=1)
# 每个样本中有效(非 NaN)标注数量 total = sub_df.notna().sum(axis=1)
# 投票比例 ratio = votes / total
# 多数表决 results = ratio.apply(lambda x: 1 if x >= 0.5 else 0) return results
def get_ids(df, attribute, value): """ 根据某个字段及其取值,从给定的 DataFrame 中筛选行索引(ID 列表)。
参数: df (pandas.DataFrame): 被筛选的数据表(如标注员信息表)。 attribute (str): 用于筛选的字段名。 value: 该字段的目标取值。
返回: list: 满足条件的行索引列表。 """ subset = df[df[attribute] == value] return subset.index.tolist()
plot/ECEandAUC.pyAdded+423
plot/两种标注方式对比.pyAdded+260
plot/任务分类山脊图_逐轮次准确率.pyAdded+457
plot/桑基图.pyAdded+421
plot/欺骗窗口.pyAdded+470
plot/熵值图.pyAdded+289
plot/逐轮次准确率.pyAdded+277
run_all_plots.pyAdded+67
utils/__init__.pyAdded+39
utils/__pycache__/__init__.cpython-310.pycAdded
utils/__pycache__/__init__.cpython-313.pycAdded
utils/__pycache__/annotator_data.cpython-310.pycAdded
utils/__pycache__/deception_data.cpython-310.pycAdded
utils/__pycache__/deception_data_per_iteration.cpython-310.pycAdded
utils/__pycache__/entroy.cpython-310.pycAdded
utils/__pycache__/kappa.cpython-310.pycAdded
utils/__pycache__/metrics.cpython-310.pycAdded
utils/__pycache__/metrics.cpython-313.pycAdded
utils/__pycache__/plot_style.cpython-310.pycAdded
utils/__pycache__/tools.cpython-310.pycAdded
utils/__pycache__/tools.cpython-313.pycAdded
utils/annotator_data.pyAdded+70
utils/deception_data.pyAdded+392
utils/deception_data_per_iteration.pyAdded+173
utils/entroy.pyAdded+86
utils/kappa.pyAdded+158
utils/metrics.pyAdded+82
utils/plot_style.pyAdded+100
utils/tools.pyAdded+49