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

249 lines
9.5 KiB
Python

# data.py (K-Fold Version with Data Quantity Control)
import os
import pickle
import json
import shutil
from tqdm import tqdm
import numpy as np
import concurrent.futures
import random
# ==============================================================================
# --- 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. 数据筛选与二分类配置 ---
POSITIVE_CLASS_LABELS = [2]
CONTROL_GROUP_LABEL = 1
# --- 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 = "ppg_for_kfold_subset1"
OUTPUT_SAMPLES_SUBFOLDER = "samples"
FINAL_SPLIT_FILENAME = "kfold_split_with_groups.json"
# --- E. 【新增】微调数据量控制 ---
# 控制用于微调的受试者比例。例如,0.5 表示随机选取50%的受试者的数据。
# 设置为 1.0 则使用所有受试者的数据。
FINETUNE_SUBJECT_FRACTION = 0.25
# 用于保证抽样可复现的随机种子
RANDOM_STATE = 42
# ==============================================================================
# --- 2. CORE FUNCTION: PROCESS, SEGMENT, AND GENERATE SPLIT ---
# ==============================================================================
# process_and_segment_file 函数保持不变,因为它处理的是单个文件
def process_and_segment_file(file_path):
# ... (此函数与上一版本完全相同) ...
try:
base_filename = os.path.splitext(os.path.basename(file_path))[0]
subject_id = base_filename.split('_')[0]
with open(file_path, 'rb') as f:
original_data_dict = pickle.load(f)
original_label = None
for label_dict in original_data_dict.get('label', []):
if 'class' in label_dict:
original_label = label_dict['class']
break
if original_label in POSITIVE_CLASS_LABELS:
binary_label = 1
elif original_label == CONTROL_GROUP_LABEL:
binary_label = 0
else:
return []
original_data_array = original_data_dict['data']
if original_data_array.ndim != 2 or original_data_array.shape[1] < TARGET_LENGTH:
return []
stride = int(TARGET_LENGTH * (1 - OVERLAP_RATIO))
if stride <= 0:
stride = 1
generated_chunks_info = []
sequence_length = original_data_array.shape[1]
chunk_index = 0
start_index = 0
output_dataset_path = os.path.join(
OUTPUT_BASE_PATH, OUTPUT_DATASET_NAME)
output_samples_root = os.path.join(
output_dataset_path, OUTPUT_SAMPLES_SUBFOLDER)
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}.pkl"
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)
generated_chunks_info.append({
'filename': new_chunk_filename,
'subject_id': subject_id,
'binary_label': binary_label
})
chunk_index += 1
start_index += stride
return generated_chunks_info
except Exception as e:
print(
f"Warning: Error processing file {os.path.basename(file_path)}: {e}. Skipping.")
return []
def create_kfold_dataset():
"""
【已修改】: 主流程函数现在包含一个基于受试者比例筛选数据的步骤。
"""
print("--- Generating Dataset for K-Fold Cross-Validation ---")
# --- 1. 创建输出目录 (保持不变) ---
output_dataset_path = os.path.join(OUTPUT_BASE_PATH, OUTPUT_DATASET_NAME)
output_samples_root = os.path.join(
output_dataset_path, OUTPUT_SAMPLES_SUBFOLDER)
# if os.path.exists(output_dataset_path):
# print(f"Output directory '{output_dataset_path}' already exists. Removing it.")
# shutil.rmtree(output_dataset_path)
os.makedirs(output_samples_root, exist_ok=True)
print(f"Created new output directory at: {output_dataset_path}")
# --- 2. 收集所有原始文件路径 (保持不变) ---
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
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 original files to process.")
# --- 3. 并行处理和分段所有文件 (保持不变) ---
all_generated_chunks = []
with concurrent.futures.ThreadPoolExecutor() as executor:
results_list = list(tqdm(executor.map(process_and_segment_file, all_file_paths),
total=len(all_file_paths),
desc="Processing and segmenting files"))
for sublist in results_list:
all_generated_chunks.extend(sublist)
if not all_generated_chunks:
raise ValueError(
"Processing completed, but no valid chunks were generated.")
# --- 4. 【核心修改】: 根据比例筛选受试者 ---
print(
f"\nTotal chunks generated before filtering: {len(all_generated_chunks)}")
all_subject_ids = sorted(
list({chunk['subject_id'] for chunk in all_generated_chunks}))
print(f"Found {len(all_subject_ids)} total unique subjects.")
final_chunks_for_finetune = []
if FINETUNE_SUBJECT_FRACTION < 1.0:
if not (0.0 < FINETUNE_SUBJECT_FRACTION <= 1.0):
raise ValueError(
"FINETUNE_SUBJECT_FRACTION must be between 0.0 and 1.0.")
# 计算需要选择的受试者数量
num_subjects_to_select = int(
len(all_subject_ids) * FINETUNE_SUBJECT_FRACTION)
if num_subjects_to_select == 0 and len(all_subject_ids) > 0:
num_subjects_to_select = 1 # 至少选择一个
print(
f"Filtering dataset to {FINETUNE_SUBJECT_FRACTION * 100:.1f}% of subjects...")
print(
f"Selecting {num_subjects_to_select} out of {len(all_subject_ids)} subjects.")
# 使用固定的随机种子进行抽样,保证可复现
random.seed(RANDOM_STATE)
selected_subjects = set(random.sample(
all_subject_ids, num_subjects_to_select))
# 只保留被选中的受试者的样本
final_chunks_for_finetune = [
chunk for chunk in all_generated_chunks if chunk['subject_id'] in selected_subjects
]
print(
f"Filtered down to {len(final_chunks_for_finetune)} chunks from {len(selected_subjects)} selected subjects.")
else:
# 如果比例为1.0,则使用所有数据
print("Using 100% of subjects for fine-tuning.")
final_chunks_for_finetune = all_generated_chunks
# --- 5. 统计并生成最终的划分文件 (使用筛选后的数据) ---
print(f"\nFinal dataset generation:")
print(
f"Total chunks to be included in the final JSON: {len(final_chunks_for_finetune)}")
subject_ids_final = {chunk['subject_id']
for chunk in final_chunks_for_finetune}
labels_final = [chunk['binary_label']
for chunk in final_chunks_for_finetune]
print(
f"Total unique subjects in the final dataset: {len(subject_ids_final)}")
if labels_final:
print(
f"Final label distribution (0=Control, 1=Positive): {dict(np.array(np.unique(labels_final, return_counts=True)).T)}")
else:
print("Final dataset is empty.")
final_split_data = {
'dataset_name': OUTPUT_DATASET_NAME,
'description': f'Dataset prepared for Group K-Fold CV, using {len(subject_ids_final)} subjects ({FINETUNE_SUBJECT_FRACTION*100:.1f}% of total).',
'samples': final_chunks_for_finetune
}
final_split_path = os.path.join(output_dataset_path, FINAL_SPLIT_FILENAME)
with open(final_split_path, 'w') as f:
json.dump(final_split_data, f, indent=2)
print(f"\nFinal split file with group info created at: {final_split_path}")
# ==============================================================================
# --- 6. MAIN EXECUTION BLOCK ---
# ==============================================================================
if __name__ == "__main__":
try:
create_kfold_dataset()
print("\n🎉 K-Fold dataset generation finished successfully!")
except Exception as e:
print(f"\nAn error occurred during the pipeline: {e}")