Files
2025-09-09 20:09:05 +08:00

157 lines
6.0 KiB
Python

import os
import pickle
from collections import Counter
from multiprocessing import Pool, cpu_count
from tqdm import tqdm
# ==============================================================================
# --- 用户配置区 ---
# ==============================================================================
# 1. [必须修改] 指向您最终生成的多通道数据集的根目录
# 这个目录应该包含 'train' 和 'test' 两个子文件夹
DATASET_FOLDER = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/normwear/processed_ppg_full" # <--- !!! 修改为您的最终数据集路径 !!!
# 2. [建议修改] 定义数字标签到疾病名称的映射
# 请根据您在数据划分时使用的 'Disease_Label_Numeric' 列来填写
# 这会让最终的报告非常清晰易读
LABEL_MAP = {
0: "下肢动脉硬化闭塞症",
1: "以上均无",
2: "冠心病",
3: "心律失常(房颤、频发早搏等)",
4: "糖尿病",
5: "脑卒中(中风)",
6: "颈动脉斑块",
7: "高脂血症(高胆固醇等)",
8: "高血压"
}
# {
# 0: "下肢动脉硬化闭塞症",
# 1: "以上均无",
# 2: "冠心病",
# 3: "心律失常(房颤、频发早搏等)",
# 4: "糖尿病",
# 5: "脑卒中(中风)",
# 6: "颈动脉斑块",
# 7: "高脂血症(高胆固醇等)",
# 8: "高血压"
# }
# ==============================================================================
# --- 并行处理的工作函数 ---
# ==============================================================================
def read_label_from_pkl(file_path):
"""
从单个 .pkl 文件中安全地读取标签。
"""
try:
with open(file_path, 'rb') as f:
data = pickle.load(f)
# 标签的嵌套结构是: {'label': [{'class': 1}]}
label = data['label'][0]['class']
return int(label)
except Exception:
# 如果文件损坏或格式不符,返回 None
return None
# ==============================================================================
# --- 核心统计与报告函数 ---
# ==============================================================================
def analyze_and_print_distribution(folder_path, title):
"""
扫描指定文件夹,并行统计标签分布,并打印格式化的报告。
"""
print("\n" + "="*60)
print(f" {title}")
print("="*60)
if not os.path.isdir(folder_path):
print(f"错误:找不到目录 '{folder_path}'")
return None
# 1. 收集所有 .pkl 文件的路径
files_to_process = [os.path.join(root, name)
for root, _, files in os.walk(folder_path)
for name in files if name.endswith('.pkl')]
if not files_to_process:
print("目录下没有找到任何 .pkl 文件。")
return Counter()
# 2. 启动多进程并行读取标签
print(f"正在从 {len(files_to_process)} 个文件中并行读取标签...")
labels = []
num_processes = max(1, cpu_count() - 1)
with Pool(processes=num_processes) as pool:
results_iterator = pool.imap_unordered(read_label_from_pkl, files_to_process)
for label in tqdm(results_iterator, total=len(files_to_process), desc=f"分析 {os.path.basename(folder_path)}"):
if label is not None:
labels.append(label)
# 3. 统计标签数量
label_counts = Counter(labels)
total_samples = len(labels)
if total_samples == 0:
print("成功读取了0个有效标签。")
return label_counts
# 4. 打印格式化的报告
print("\n{:<10} | {:<20} | {:>10} | {:>12}".format("标签ID", "标签名称", "数量", "百分比"))
print("-" * 60)
# 按标签ID排序后打印
for label_id, count in sorted(label_counts.items()):
label_name = LABEL_MAP.get(label_id, "未知标签")
percentage = (count / total_samples) * 100
print("{:<10} | {:<20} | {:>10,} | {:>11.2f}%".format(label_id, label_name, count, percentage))
print("-" * 60)
print("{:<10} | {:<20} | {:>10,} | {:>11.2f}%".format("总计", "", total_samples, 100.0))
return label_counts
# ==============================================================================
# --- 主流程控制器 ---
# ==============================================================================
if __name__ == "__main__":
# 定义训练集和测试集的路径
train_folder = os.path.join(DATASET_FOLDER, 'train')
test_folder = os.path.join(DATASET_FOLDER, 'test')
# 分析训练集
train_counts = analyze_and_print_distribution(train_folder, "训 练 集 标 签 分 布")
# 分析测试集
test_counts = analyze_and_print_distribution(test_folder, "测 试 集 标 签 分 布")
# 分析整体分布
if train_counts is not None and test_counts is not None:
total_counts = train_counts + test_counts
# 创建一个虚拟的 "总计" 文件夹路径用于报告标题
total_folder_for_title = os.path.join(DATASET_FOLDER, 'total')
# 为了复用打印函数,我们手动计算并打印总计
total_samples = sum(total_counts.values())
print("\n" + "="*60)
print(f" 整 体 数 据 集 标 签 分 布")
print("="*60)
if total_samples > 0:
print("\n{:<10} | {:<20} | {:>10} | {:>12}".format("标签ID", "标签名称", "数量", "百分比"))
print("-" * 60)
for label_id, count in sorted(total_counts.items()):
label_name = LABEL_MAP.get(label_id, "未知标签")
percentage = (count / total_samples) * 100
print("{:<10} | {:<20} | {:>10,} | {:>11.2f}%".format(label_id, label_name, count, percentage))
print("-" * 60)
print("{:<10} | {:<20} | {:>10,} | {:>11.2f}%".format("总计", "", total_samples, 100.0))
else:
print("数据集中没有找到有效样本。")
print("\n\n统计完成!")