import os import json import matplotlib.pyplot as plt def plot_filtered_yes_prob_histogram(folder_path, num_bins=10): """ 读取文件夹中所有 .json 文件,但只统计第一个回答为 'No' 或 'Bad' 的 文件的 "Yes prob" 值,并绘制其频率分布直方图。 Args: folder_path (str): 包含 .json 文件的文件夹路径。 num_bins (int): 直方图的柱子数量(分箱数量)。 """ yes_probs = [] total_files = 0 filtered_files = 0 for filename in os.listdir(folder_path): if filename.endswith(".json"): total_files += 1 file_path = os.path.join(folder_path, filename) try: with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) # 检查数据结构是否符合预期,并确保第一个字典不为空 if (isinstance(data, list) and len(data) > 1 and isinstance(data[0], dict) and data[0]): # 获取第一个字典中的值(回答) # 这种方法不需要知道具体的键(问题)是什么 first_answer = next(iter(data[0].values())) # ----> 这是新增的筛选条件 <---- if first_answer in ['No', 'Bad']: filtered_files += 1 # 如果条件满足,则提取 "Yes prob" if isinstance(data[1], dict) and 'Yes prob' in data[1]: yes_probs.append(data[1]['Yes prob']) except (json.JSONDecodeError, IndexError, KeyError, StopIteration) as e: print(f"处理文件 {filename} 时出错或因格式不符已跳过: {e}") if not yes_probs: print(f"在 {total_files} 个文件中,未找到符合条件 ('No' 或 'Bad') 的 'Yes prob' 值。") return print(f"总共扫描 {total_files} 个文件,其中 {filtered_files} 个文件的回答为 'No' 或 'Bad'。") print(f"正在为这 {len(yes_probs)} 个 'Yes prob' 值生成直方图...") # 绘制直方图 plt.figure(figsize=(12, 7)) plt.hist(yes_probs, bins=num_bins, edgecolor='black', alpha=0.7) plt.xlabel("'Yes prob'", fontsize=12) plt.ylabel("Num", fontsize=12) plt.title("x", fontsize=16) plt.grid(axis='y', linestyle='--', linewidth=0.7) # 保存图表 plt.savefig("/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_Sep28_2/filtered_yes_prob_histogram.png") print(f"筛选后的直方图已保存为 filtered_yes_prob_histogram.png") # --- 使用说明 --- # 1. 将下面的 'your_folder_path' 替换为您的文件夹实际路径。 # 2. (可选)您可以修改 'num_bins=15' 中的数字来调整直方图的精细程度。 # 3. 运行此脚本。 # 请在这里替换为您的文件夹路径 your_folder_path = '/nfs/ywang29/Reward_finetuning/VideoX-Fun/output_Sep28_2/train_sample' plot_filtered_yes_prob_histogram(your_folder_path, num_bins=15)