Files
normwear/data.py
T
2025-10-30 17:52:46 +08:00

328 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import pickle
import json
import shutil
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import numpy as np
from collections import Counter
import math
import concurrent.futures
# ==============================================================================
# --- 1. MASTER CONFIGURATION ---
# ==============================================================================
# --- A. 原始数据源 ---
RAW_DATA_FOLDERS = ['/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/normwear/processed_ppg_full/train',
'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/normwear/processed_ppg_full/test']
# --- B. 初始划分配置 ---
# 【修改】: 移除 TRAIN_LABELS_TO_KEEP,因为现在是基于二分类标签来选择
# 【修改】: 移除 NUM_TRAIN_SAMPLES 和 NUM_TEST_SAMPLES,替换为新的控制参数
# 【新增】: 控制最终训练集和测试集的总样本数(基于原始文件)
TOTAL_TRAIN_SAMPLES = 20000 # 训练集总样本数
TOTAL_TEST_SAMPLES = 8000 # 测试集总样本数
# 【新增】: 控制最终训练集和测试集中的患病率(正样本比例)
# 例如,0.05 表示 5% 的患病率
TARGET_TRAIN_PREVALENCE = 0.5
TARGET_TEST_PREVALENCE = 0.15
# 用于二分类转换的标签定义
POSITIVE_CLASS_LABELS = [2] # 哪些原始标签被视为“患病”(正样本,binary_label=1)
CONTROL_GROUP_LABEL = 1 # 哪个原始标签被视为“健康”(负样本,binary_label=0)
# 用于保证划分可复现的随机种子
RANDOM_STATE = 42
# --- C. 分段处理配置 ---
TARGET_LENGTH = 390
OVERLAP_RATIO = 0.5
# --- D. 输出路径配置 ---
OUTPUT_BASE_PATH = "/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/"
OUTPUT_DATASET_NAME = "ppg2e4" # 建议用新名字以区分
OUTPUT_SAMPLES_SUBFOLDER = "sample_for_downstream"
TEMP_SPLIT_FILENAME = "temp_initial_split.json"
# ==============================================================================
# --- 2. CORE FUNCTION 1: CREATE INITIAL SPLIT (基于原始文件) ---
# ==============================================================================
def process_file(file_path):
"""
读取单个pkl文件,提取标签并进行二分类转换。
返回一个包含文件信息的字典,如果文件无效或出错则返回None。
"""
try:
with open(file_path, 'rb') as f:
data = pickle.load(f)
original_label = None
for label_dict in data.get('label', []):
if 'class' in label_dict:
original_label = label_dict['class']
break
if original_label is None:
return None
if original_label in POSITIVE_CLASS_LABELS:
binary_label = 1
elif original_label == CONTROL_GROUP_LABEL:
binary_label = 0
else:
return None # 忽略不相关的标签
return {
'name': os.path.basename(file_path),
'path': file_path,
'original_label': original_label,
'binary_label': binary_label
}
except Exception:
# 在并行处理中,静默处理单个文件的错误,避免整个程序崩溃
return None
def get_class_label(file_path):
"""辅助函数:读取pkl文件并返回其'class'标签。"""
try:
with open(file_path, 'rb') as f:
data = pickle.load(f)
for label_dict in data.get('label', []):
if 'class' in label_dict:
return label_dict['class']
return None
except Exception as e:
print(f"Error reading {file_path}: {e}")
return None
# 【重大修改】: 重写 create_initial_split 函数
def create_initial_split():
"""
【已优化】: 使用并行方式扫描和处理大量原始文件,然后根据目标样本数和患病率进行抽样。
"""
print("--- Step 1: Creating Initial Split (Optimized with Parallel Processing) ---")
# 1. 快速、一次性地收集所有需要处理的文件路径
all_file_paths = []
print("Scanning for all .pkl files...")
for folder in RAW_DATA_FOLDERS:
if not os.path.isdir(folder):
print(f"Warning: Raw data folder '{folder}' not found. Skipping.")
continue
# 遍历文件夹并收集所有 .pkl 文件的完整路径
for filename in os.listdir(folder):
if filename.endswith('.pkl'):
all_file_paths.append(os.path.join(folder, filename))
if not all_file_paths:
raise ValueError("No .pkl files found in the specified directories.")
print(f"Found {len(all_file_paths)} total .pkl files to process.")
# 2. 使用线程池并行处理所有文件
all_samples_info = []
# ThreadPoolExecutor 非常适合 I/O 密集型任务(如读写文件)
# 'with' 语句能确保线程池在使用后被安全关闭
with concurrent.futures.ThreadPoolExecutor() as executor:
# executor.map 会将 all_file_paths 中的每个路径传递给 process_file 函数
# 它会自动管理线程,并以与输入相同的顺序返回结果
# tqdm(..., total=...) 用于创建一个美观的进度条
results = list(tqdm(executor.map(process_file, all_file_paths),
total=len(all_file_paths),
desc="Processing files in parallel"))
# 过滤掉处理失败或无效的文件(结果为 None)
all_samples_info = [res for res in results if res is not None]
if not all_samples_info:
raise ValueError(
"No valid .pkl files found matching positive or control labels after processing.")
# 3. 将所有样本按二分类标签分组 (这部分逻辑和原来一样,速度很快)
positive_pool = [s for s in all_samples_info if s['binary_label'] == 1]
negative_pool = [s for s in all_samples_info if s['binary_label'] == 0]
print(f"Found {len(all_samples_info)} total eligible original samples.")
print(f" - Positive samples (disease): {len(positive_pool)}")
print(f" - Negative samples (control): {len(negative_pool)}")
# 3. 定义一个内部函数来执行抽样,避免代码重复
def sample_dataset(total_samples, target_prevalence, pos_pool, neg_pool, dataset_name):
print(f"\nSampling for {dataset_name} set...")
# 计算需要的正负样本数量
num_positive = math.ceil(total_samples * target_prevalence)
num_negative = total_samples - num_positive
print(
f"Target: {total_samples} total samples ({num_positive} positive, {num_negative} negative).")
# 检查样本池是否有足够样本
if len(pos_pool) < num_positive:
print(
f"Warning: Not enough positive samples for {dataset_name}. Requested {num_positive}, but only {len(pos_pool)} available. Using all.")
num_positive = len(pos_pool)
if len(neg_pool) < num_negative:
print(
f"Warning: Not enough negative samples for {dataset_name}. Requested {num_negative}, but only {len(neg_pool)} available. Using all.")
num_negative = len(neg_pool)
# 从池中随机抽取样本
rng = np.random.RandomState(RANDOM_STATE)
# 使用 permutation + slicing 来实现无放回抽样
pos_indices = rng.permutation(len(pos_pool))[:num_positive]
neg_indices = rng.permutation(len(neg_pool))[:num_negative]
selected_pos = [pos_pool[i] for i in pos_indices]
selected_neg = [neg_pool[i] for i in neg_indices]
# 合并并打乱
final_dataset = selected_pos + selected_neg
rng.shuffle(final_dataset)
# 从总池中移除已选中的样本,以供下一个数据集使用
remaining_pos = [p for i, p in enumerate(
pos_pool) if i not in pos_indices]
remaining_neg = [n for i, n in enumerate(
neg_pool) if i not in neg_indices]
actual_prevalence = len(selected_pos) / \
len(final_dataset) if final_dataset else 0
print(
f"Created {dataset_name} set with {len(final_dataset)} samples. Actual prevalence: {actual_prevalence:.3f}")
return final_dataset, remaining_pos, remaining_neg
# 4. 依次为训练集和测试集抽样
# 首先抽训练集
final_train_pool, remaining_pos_pool, remaining_neg_pool = sample_dataset(
TOTAL_TRAIN_SAMPLES, TARGET_TRAIN_PREVALENCE, positive_pool, negative_pool, "Train"
)
# 然后从剩余的样本中抽测试集
final_test_pool, _, _ = sample_dataset(
TOTAL_TEST_SAMPLES, TARGET_TEST_PREVALENCE, remaining_pos_pool, remaining_neg_pool, "Test"
)
# 5. 生成临时的划分文件
initial_split_data = {
'train': {s['name']: s['path'] for s in final_train_pool},
'test': {s['name']: s['path'] for s in final_test_pool}
}
with open(TEMP_SPLIT_FILENAME, 'w') as f:
json.dump(initial_split_data, f, indent=2)
print(
f"\nInitial split generated with {len(final_train_pool)} train and {len(final_test_pool)} test files.")
print(f"Temporary split file created at: {TEMP_SPLIT_FILENAME}")
return TEMP_SPLIT_FILENAME
# ==============================================================================
# --- 3. CORE FUNCTION 2: SEGMENT AND FINALIZE DATASET (保持不变) ---
# ==============================================================================
def segment_and_finalize_dataset(initial_split_file):
"""
读取初始划分文件,对相应的文件进行分段,并生成最终的数据集和划分JSON。
(此函数无需修改)
"""
print("\n--- Step 2: Segmenting Files and Finalizing Dataset ---")
output_dataset_path = os.path.join(OUTPUT_BASE_PATH, OUTPUT_DATASET_NAME)
output_samples_root = os.path.join(
output_dataset_path, OUTPUT_SAMPLES_SUBFOLDER)
os.makedirs(output_samples_root, exist_ok=True)
stride = int(TARGET_LENGTH * (1 - OVERLAP_RATIO))
if stride <= 0:
stride = 1
print(
f"Segmentation settings: Target Length={TARGET_LENGTH}, Stride={stride}")
with open(initial_split_file, 'r') as f:
initial_split = json.load(f)
final_split = {'train': [], 'test': []}
all_original_files = {**initial_split['train'], **initial_split['test']}
for filename, file_path in tqdm(all_original_files.items(), desc="Segmenting all selected files"):
base_filename, ext = os.path.splitext(filename)
try:
with open(file_path, 'rb') as f:
original_data_dict = pickle.load(f)
original_data_array = original_data_dict['data']
if original_data_array.ndim != 2 or original_data_array.shape[1] < TARGET_LENGTH:
continue
sequence_length = original_data_array.shape[1]
chunk_index = 0
start_index = 0
while start_index + TARGET_LENGTH <= sequence_length:
segment_data_array = original_data_array[:,
start_index: start_index + TARGET_LENGTH]
new_data_dict = {
"uid": f"{original_data_dict.get('uid', base_filename)}_chunk_{chunk_index}",
"data": segment_data_array.astype(original_data_array.dtype),
"sampling_rate": original_data_dict.get('sampling_rate'),
"label": original_data_dict.get('label')
}
new_chunk_filename = f"{base_filename}_chunk_{chunk_index}{ext}"
output_file_path = os.path.join(
output_samples_root, new_chunk_filename)
with open(output_file_path, 'wb') as nf:
pickle.dump(new_data_dict, nf)
if filename in initial_split['train']:
final_split['train'].append(new_chunk_filename)
elif filename in initial_split['test']:
final_split['test'].append(new_chunk_filename)
chunk_index += 1
start_index += stride
except Exception as e:
print(f"Error processing file {filename}: {e}")
final_split['train'] = sorted(list(set(final_split['train'])))
final_split['test'] = sorted(list(set(final_split['test'])))
print(f"\nSegmentation complete.")
print(
f"Final train set size (after segmentation): {len(final_split['train'])} chunks")
print(
f"Final test set size (after segmentation): {len(final_split['test'])} chunks")
final_split_path = os.path.join(
output_dataset_path, "train_test_split.json")
with open(final_split_path, 'w') as f:
json.dump(final_split, f, indent=2)
print(f"Final split file created at: {final_split_path}")
# ==============================================================================
# --- 4. MAIN EXECUTION BLOCK (保持不变) ---
# ==============================================================================
if __name__ == "__main__":
try:
temp_split_file = create_initial_split()
segment_and_finalize_dataset(temp_split_file)
os.remove(temp_split_file)
print(f"\nTemporary file '{temp_split_file}' removed.")
print("\n🎉 Pipeline finished successfully!")
except Exception as e:
print(f"\nAn error occurred during the pipeline: {e}")