format pep8

This commit is contained in:
yilv committed 2025-10-30 17:52:46 +08:00
1 parent 5d53c85e4d
commit 62fe936d35
27 files changed
+1432 -962

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
{
"editor.gotoLocation.alternativeDeclarationCommand": "editor.action.revealDefinition",
"editor.gotoLocation.alternativeDefinitionCommand": "editor.action.revealDefinition",
"editor.gotoLocation.alternativeTypeDefinitionCommand": "editor.action.revealDefinition",
"editor.selectionHighlight": false,
"files.autoSave": "onFocusChange",
"editor.suggest.snippetsPreventQuickSuggestions": false,
"editor.quickSuggestions": {
"other": "on",
"comments": "off",
"strings": "on"
}
}
+54 -34
View File
@@ -6,7 +6,7 @@ import sys
from typing import Iterable, Optional
import torch
import sklearn
import pandas as pd # <-- [ADDED] Import pandas for saving CSV
import pandas as pd
import numpy as np
import os
@@ -23,7 +23,8 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
args=None):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
metric_logger.add_meter('lr', misc.SmoothedValue(
window_size=1, fmt='{value:.6f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
accum_iter = args.accum_iter if args else 1
@@ -38,7 +39,8 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
# Note: The original code had a check for lr_sched, which is good practice.
if lr_sched:
current_progress = data_iter_step / len(data_loader) + epoch
lr_sched.adjust_learning_rate(optimizer, current_progress, args)
lr_sched.adjust_learning_rate(
optimizer, current_progress, args)
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
samples_1d = batch['input_1d'].to(device, non_blocking=True)
@@ -49,16 +51,17 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
loss_value = loss.item()
if not math.isfinite(loss_value):
print(f"Loss is {loss_value}, stopping training at Epoch {epoch}, Step {data_iter_step}")
print(
f"Loss is {loss_value}, stopping training at Epoch {epoch}, Step {data_iter_step}")
sys.exit(1)
loss_to_scale = loss / accum_iter
# Using the callable NativeScaler for cleaner code
loss_scaler(
loss_to_scale,
optimizer,
clip_grad=max_norm,
loss_to_scale,
optimizer,
clip_grad=max_norm,
parameters=model.parameters(),
update_grad=(data_iter_step + 1) % accum_iter == 0
)
@@ -71,7 +74,8 @@ def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
metric_logger.update(lr=current_lr)
if log_writer is not None and (data_iter_step + 1) % accum_iter == 0:
epoch_1000x = int((data_iter_step / len(data_loader) + epoch) * 1000)
epoch_1000x = int(
(data_iter_step / len(data_loader) + epoch) * 1000)
log_writer.add_scalar('train/loss', loss_value, epoch_1000x)
log_writer.add_scalar('train/lr', current_lr, epoch_1000x)
@@ -87,7 +91,7 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
analyzer = analysis.Analyzer(print_conf_mat=print_analyzer)
except (NameError, AttributeError):
analyzer = None
metric_logger = misc.MetricLogger(delimiter=" ")
header = 'Test:'
model.eval()
@@ -123,11 +127,13 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
if misc.is_dist_avail_and_initialized():
dist.barrier()
predictions_list = [torch.zeros_like(predictions_cat) for _ in range(misc.get_world_size())]
targets_list = [torch.zeros_like(targets_cat) for _ in range(misc.get_world_size())]
predictions_list = [torch.zeros_like(
predictions_cat) for _ in range(misc.get_world_size())]
targets_list = [torch.zeros_like(targets_cat)
for _ in range(misc.get_world_size())]
dist.all_gather(predictions_list, predictions_cat)
dist.all_gather(targets_list, targets_cat)
session_ids_list = [None] * misc.get_world_size()
sample_ids_list = [None] * misc.get_world_size()
dist.all_gather_object(session_ids_list, all_session_ids)
@@ -136,8 +142,10 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
if misc.is_main_process():
predictions_np = torch.cat(predictions_list, dim=0).cpu().numpy()
targets_np = torch.cat(targets_list, dim=0).cpu().numpy()
all_session_ids = [item for sublist in session_ids_list for item in sublist]
all_sample_ids = [item for sublist in sample_ids_list for item in sublist]
all_session_ids = [
item for sublist in session_ids_list for item in sublist]
all_sample_ids = [
item for sublist in sample_ids_list for item in sublist]
else:
return {'loss': epoch_loss}, {}
else:
@@ -153,39 +161,46 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
predictions_np = predictions_np[:num_samples]
all_session_ids = all_session_ids[:num_samples]
all_sample_ids = all_sample_ids[:num_samples]
metrics_dict = {'loss': epoch_loss}
per_sample_results = {}
if args.task == 'cls' and args.num_classes == 2:
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
probs_np = torch.nn.functional.softmax(
torch.from_numpy(predictions_np), dim=1).cpu().numpy()
positive_probs = probs_np[:, 1]
best_f1 = 0.0
best_threshold = 0.5
thresholds = np.arange(0.05, 0.96, 0.01)
for threshold in thresholds:
pred_labels_at_thresh = (positive_probs >= threshold).astype(int)
f1 = sklearn.metrics.f1_score(targets_np, pred_labels_at_thresh, pos_label=1, zero_division=0)
f1 = sklearn.metrics.f1_score(
targets_np, pred_labels_at_thresh, pos_label=1, zero_division=0)
if f1 > best_f1:
best_f1 = f1
best_threshold = threshold
print(f"[*] Optimal threshold search: Best F1-score = {best_f1:.4f} at threshold = {best_threshold:.2f}")
print(
f"[*] Optimal threshold search: Best F1-score = {best_f1:.4f} at threshold = {best_threshold:.2f}")
pred_labels_np = (positive_probs >= best_threshold).astype(int)
accuracy = sklearn.metrics.accuracy_score(targets_np, pred_labels_np)
precision = sklearn.metrics.precision_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
recall = sklearn.metrics.recall_score(targets_np, pred_labels_np, pos_label=1, zero_division=0)
precision = sklearn.metrics.precision_score(
targets_np, pred_labels_np, pos_label=1, zero_division=0)
recall = sklearn.metrics.recall_score(
targets_np, pred_labels_np, pos_label=1, zero_division=0)
f1 = best_f1
unique_targets = np.unique(targets_np)
roc_auc, ap = 0.0, 0.0
if len(unique_targets) > 1:
try:
roc_auc = sklearn.metrics.roc_auc_score(targets_np, positive_probs)
ap = sklearn.metrics.average_precision_score(targets_np, positive_probs)
roc_auc = sklearn.metrics.roc_auc_score(
targets_np, positive_probs)
ap = sklearn.metrics.average_precision_score(
targets_np, positive_probs)
except ValueError as e:
print(f"Warning: Could not compute AUC/AP: {e}")
@@ -194,9 +209,11 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
'precision': precision, 'recall': recall, 'f1_score': f1,
'best_threshold': best_threshold
})
print(f"* Test Metrics (Optimal Threshold): Loss {metrics_dict['loss']:.4f}, Accuracy {accuracy:.4f}, ROC_AUC {roc_auc:.4f}, AP {ap:.4f}")
print(f"* Precision {precision:.4f}, Recall {recall:.4f}, F1-Score {f1:.4f}")
print(
f"* Test Metrics (Optimal Threshold): Loss {metrics_dict['loss']:.4f}, Accuracy {accuracy:.4f}, ROC_AUC {roc_auc:.4f}, AP {ap:.4f}")
print(
f"* Precision {precision:.4f}, Recall {recall:.4f}, F1-Score {f1:.4f}")
per_sample_results = {
'session_id': all_session_ids, 'sample_id': all_sample_ids,
@@ -205,14 +222,16 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
}
if analyzer:
classification_metrics = analyzer.analyze_classification(pred_labels_np, targets_np, np.arange(args.num_classes))
classification_metrics = analyzer.analyze_classification(
pred_labels_np, targets_np, np.arange(args.num_classes))
metrics_dict.update(classification_metrics)
elif args.task == 'cls':
probs_np = torch.nn.functional.softmax(torch.from_numpy(predictions_np), dim=1).cpu().numpy()
probs_np = torch.nn.functional.softmax(
torch.from_numpy(predictions_np), dim=1).cpu().numpy()
pred_labels_np = np.argmax(probs_np, axis=1)
metrics_dict['accuracy'] = np.mean(pred_labels_np == targets_np)
elif args.task == 'reg':
# Assuming predictions_np is the output for regression
mae = sklearn.metrics.mean_absolute_error(targets_np, predictions_np)
@@ -224,11 +243,12 @@ def evaluate(args, data_loader, model, device, criterion, print_analyzer=True, e
'true_label': targets_np,
'positive_prob': positive_probs
})
raw_output_path = os.path.join(plot_save_dir, f'raw_predictions_epoch_{epoch}.csv')
raw_output_path = os.path.join(
plot_save_dir, f'raw_predictions_epoch_{epoch}.csv')
raw_df.to_csv(raw_output_path, index=False)
print(f"[*] Saved RAW per-sample predictions to {raw_output_path}")
# --- [OPTIMIZED END] ---
return metrics_dict, per_sample_results
# --- END OF FILE engine_finetune (1).py (MODIFIED) ---
# --- END OF FILE engine_finetune (1).py (MODIFIED) ---
+68 -50
View File
@@ -12,18 +12,15 @@ import json
from NormWear.modules.normwear import NormWear
from NormWear.modules.custom_blocks import OneD_CNN_Extractor
# 导入您最终的微调模型类 (FinetuneModel 或 FusionModel)
from NormWear.downstream_pipeline.main_finetune import FinetuneModel
from NormWear.downstream_pipeline.main_finetune import FinetuneModel
# 导入数据预处理函数
from NormWear.pretrain_pipeline.dataset import cwt_wrap, ricker_wavelet, cwt_ricker
# --------------------------------------------------------------------------
# 推理器类 (此类完全没有修改)
# --------------------------------------------------------------------------
class Predictor:
def __init__(self, checkpoint_path, args):
self.device = torch.device(args.device)
self.args = args
# 1. 实例化一个与微调时完全相同的模型结构
print("Instantiating model...")
backbone = NormWear(
@@ -38,7 +35,7 @@ class Predictor:
decoder_num_heads=args.decoder_num_heads,
nvar=args.n_vars
)
self.model = FinetuneModel(
backbone=backbone,
num_channel=args.n_vars,
@@ -49,21 +46,21 @@ class Predictor:
# 2. 加载微调好的模型权重
print(f"Loading fine-tuned checkpoint from: {checkpoint_path}")
checkpoint = torch.load(checkpoint_path, map_location='cpu')
# 兼容DDP和非DDP保存的权重
state_dict = checkpoint['model']
new_state_dict = {}
for k, v in state_dict.items():
if k.startswith('module.'):
new_state_dict[k[7:]] = v # remove `module.`
new_state_dict[k[7:]] = v # remove `module.`
else:
new_state_dict[k] = v
msg = self.model.load_state_dict(new_state_dict, strict=True)
print("Model loading message:", msg)
self.model.eval()
# 3. 初始化CWT参数
self.cwt_scales = torch.arange(1, 65 + 1).to(self.device)
@@ -73,9 +70,10 @@ class Predictor:
long_signal: [n_vars, L_long]
"""
n_vars, L_long = long_signal.shape
if L_long < self.args.window_size:
print(f"Warning: Signal length ({L_long}) is shorter than window size ({self.args.window_size}). Padding signal.")
print(
f"Warning: Signal length ({L_long}) is shorter than window size ({self.args.window_size}). Padding signal.")
pad_size = self.args.window_size - L_long
pad_values = long_signal[:, 0:1].expand(-1, pad_size)
long_signal = torch.cat((pad_values, long_signal), dim=1)
@@ -83,14 +81,14 @@ class Predictor:
windows = []
start_indices = []
num_windows = (L_long - self.args.window_size) // self.args.stride + 1
for i in range(num_windows):
start = i * self.args.stride
end = start + self.args.window_size
windows.append(long_signal[:, start:end])
start_indices.append(start)
return windows, start_indices
def _preprocess_window(self, signal_window):
@@ -105,8 +103,9 @@ class Predictor:
processed_signal_1d = (signal_1d - mean) / (std + 1e-8)
# 2. CWT变换
cwt_image = cwt_wrap(processed_signal_1d.to(self.device), scales=self.cwt_scales)
cwt_image = cwt_wrap(processed_signal_1d.to(
self.device), scales=self.cwt_scales)
return cwt_image, processed_signal_1d.to(self.device)
@torch.no_grad()
@@ -118,25 +117,27 @@ class Predictor:
# 【修改】在循环中打印文件名,而不是在这里
with open(pkl_file_path, 'rb') as f:
data = pickle.load(f)
uid = data.get('uid', os.path.splitext(os.path.basename(pkl_file_path))[0])
uid = data.get('uid', os.path.splitext(
os.path.basename(pkl_file_path))[0])
long_signal = torch.from_numpy(data['data']).float()
# 确保变量数与模型期望的一致
if long_signal.shape[0] != self.args.n_vars:
raise ValueError(f"Input signal has {long_signal.shape[0]} variables, but model expects {self.args.n_vars}.")
raise ValueError(
f"Input signal has {long_signal.shape[0]} variables, but model expects {self.args.n_vars}.")
# 2. 创建滑动窗口
windows, start_indices = self._create_windows(long_signal)
# 3. 批量推理
results = []
batch_size = self.args.batch_size
# 【修改】为tqdm添加更具体的文件名描述
for i in tqdm(range(0, len(windows), batch_size), desc=f"Inferencing on {uid}", leave=False):
batch_windows = windows[i:i+batch_size]
# 预处理当前batch
batch_cwt = []
batch_1d = []
@@ -144,17 +145,17 @@ class Predictor:
cwt_image, signal_1d = self._preprocess_window(window)
batch_cwt.append(cwt_image)
batch_1d.append(signal_1d)
# 堆叠成batch张量
batch_cwt_tensor = torch.stack(batch_cwt)
batch_1d_tensor = torch.stack(batch_1d)
# 模型推理
logits, _ = self.model(batch_cwt_tensor, batch_1d_tensor)
# 计算概率
probabilities = F.softmax(logits, dim=1)
# 收集结果
for j, prob in enumerate(probabilities):
window_start = start_indices[i+j]
@@ -164,38 +165,49 @@ class Predictor:
'end_index': window_end,
'probabilities': prob.cpu().numpy().tolist()
})
return {'uid': uid, 'predictions': results}
# --------------------------------------------------------------------------
# 参数解析器 (已修改)
# --------------------------------------------------------------------------
def get_args_parser():
# 【修改】更新脚本描述
parser = argparse.ArgumentParser('NormWear Batch Inference Script', add_help=False)
parser = argparse.ArgumentParser(
'NormWear Batch Inference Script', add_help=False)
# --- 核心参数 (已修改) ---
# 将 --input_file 改为 --input_dir
parser.add_argument('--input_dir', required=True, type=str, help='Path to the directory containing .pkl files.')
parser.add_argument('--checkpoint', required=True, type=str, help='Path to the fine-tuned model checkpoint.')
parser.add_argument('--output_file', required=True, type=str, help='Path to save the single JSON output file with all predictions.')
parser.add_argument('--input_dir', required=True, type=str,
help='Path to the directory containing .pkl files.')
parser.add_argument('--checkpoint', required=True, type=str,
help='Path to the fine-tuned model checkpoint.')
parser.add_argument('--output_file', required=True, type=str,
help='Path to save the single JSON output file with all predictions.')
# --- 滑动窗口参数 (保持不变) ---
parser.add_argument('--window_size', default=387, type=int, help='Length of the sliding window.')
parser.add_argument('--stride', default=100, type=int, help='Stride of the sliding window.')
parser.add_argument('--window_size', default=387,
type=int, help='Length of the sliding window.')
parser.add_argument('--stride', default=100, type=int,
help='Stride of the sliding window.')
# --- 模型架构参数 (保持不变) ---
parser.add_argument('--n_vars', type=int, required=True, help='Number of variables in the data.')
parser.add_argument('--num_classes', type=int, required=True, help='Number of output classes for the fine-tuned model.')
parser.add_argument('--n_vars', type=int, required=True,
help='Number of variables in the data.')
parser.add_argument('--num_classes', type=int, required=True,
help='Number of output classes for the fine-tuned model.')
parser.add_argument('--embed_dim', type=int, default=768)
parser.add_argument('--depth', type=int, default=12)
parser.add_argument('--num_heads', type=int, default=12)
parser.add_argument('--decoder_embed_dim', type=int, default=512)
parser.add_argument('--decoder_depth', type=int, default=8)
parser.add_argument('--decoder_num_heads', type=int, default=16)
# --- 运行参数 (保持不变) ---
parser.add_argument('--batch_size', default=128, type=int, help='Batch size for inference.')
parser.add_argument('--batch_size', default=128,
type=int, help='Batch size for inference.')
parser.add_argument('--device', default='cuda', help='Device to use.')
return parser
@@ -203,23 +215,26 @@ def get_args_parser():
# --------------------------------------------------------------------------
# 主函数 (已修改为批处理逻辑)
# --------------------------------------------------------------------------
def main(args):
# 1. 创建推理器实例 (此部分不变)
predictor = Predictor(args.checkpoint, args)
# 2. 查找输入文件夹中的所有 .pkl 文件
if not os.path.isdir(args.input_dir):
print(f"Error: Input directory not found at '{args.input_dir}'")
return
pkl_files = [os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir) if f.lower().endswith('.pkl')]
pkl_files = [os.path.join(args.input_dir, f) for f in os.listdir(
args.input_dir) if f.lower().endswith('.pkl')]
if not pkl_files:
print(f"No .pkl files found in '{args.input_dir}'.")
return
print(f"Found {len(pkl_files)} .pkl files to process.")
# 3. 循环对每个文件进行预测,并收集结果
all_results = []
# 使用tqdm显示总体进度
@@ -230,16 +245,19 @@ def main(args):
all_results.append(result)
except Exception as e:
# 如果单个文件处理失败,打印错误并继续
print(f"\n!!!!!! Failed to process file: {os.path.basename(pkl_file_path)} !!!!!!")
print(
f"\n!!!!!! Failed to process file: {os.path.basename(pkl_file_path)} !!!!!!")
print(f"Error: {e}")
print("Skipping this file and continuing...")
# 4. 将所有结果保存到一个JSON文件中
print(f"\nSaving all {len(all_results)} prediction results to {args.output_file}...")
print(
f"\nSaving all {len(all_results)} prediction results to {args.output_file}...")
with open(args.output_file, 'w') as f:
json.dump(all_results, f, indent=4)
print("Done!")
if __name__ == '__main__':
args = get_args_parser().parse_args()
main(args)
main(args)
+4 -2
View File
@@ -2,11 +2,13 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""
A flexible Focal Loss implementation.
Can be used for both binary and multi-class classification.
"""
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
"""
Args:
@@ -25,7 +27,7 @@ class FocalLoss(nn.Module):
self.alpha = torch.tensor(alpha, dtype=torch.float)
else:
self.alpha = None
self.gamma = gamma
self.reduction = reduction
@@ -61,4 +63,4 @@ class FocalLoss(nn.Module):
elif self.reduction == 'sum':
return focal_loss.sum()
else:
return focal_loss
return focal_loss
+166 -101
View File
@@ -26,15 +26,17 @@ import NormWear.pretrain_pipeline.misc as misc
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
from NormWear.pretrain_pipeline.dataset import dataset_class
from peft import LoraConfig, get_peft_model, TaskType
class FinetuneModel(nn.Module):
def __init__(self, backbone, num_channel, embed_dim, num_classes):
super().__init__()
# backbone 是完整的、预训练好的、可能被LoRA包装的 NormWear 模型
self.backbone = backbone
self.backbone = backbone
# 分类头,输入维度基于CLS Token
head_input_dim = num_channel * embed_dim
self.finetune_head = nn.Sequential(
nn.Linear(head_input_dim, head_input_dim // 2),
nn.BatchNorm1d(head_input_dim // 2),
@@ -46,26 +48,35 @@ class FinetuneModel(nn.Module):
def forward(self, x_cwt, x_1d):
# 1. 直接调用统一的融合推理接口
z = self.backbone.get_signal_embedding(x_cwt, x_1d)
# 2. 从特征中提取CLS Token进行分类
# z 形状: [bs, n_vars, num_patches+1, embed_dim]
cls_tokens = z[:, :, 0, :] # [bs, n_vars, embed_dim]
cls_tokens = z[:, :, 0, :] # [bs, n_vars, embed_dim]
# 3. 展平并送入分类头
flat_features = cls_tokens.flatten(1) # [bs, n_vars * embed_dim]
flat_features = cls_tokens.flatten(1) # [bs, n_vars * embed_dim]
logits = self.finetune_head(flat_features)
return logits, flat_features
def str2bool(v):
if isinstance(v, bool): return v
if v.lower() in ('yes', 'true', 't', 'y', '1'): return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False
else: raise argparse.ArgumentTypeError('Boolean value expected.')
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def parse_tuple(arg_str):
if arg_str.startswith('(') and arg_str.endswith(')'): arg_str = arg_str[1:-1]
if arg_str.startswith('(') and arg_str.endswith(')'):
arg_str = arg_str[1:-1]
return tuple(map(int, arg_str.split(',')))
class FocalLoss(nn.Module):
# ... (FocalLoss class remains unchanged) ...
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
@@ -73,45 +84,62 @@ class FocalLoss(nn.Module):
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, inputs, targets):
ce_loss = F.cross_entropy(inputs, targets, reduction='none')
pt = torch.exp(-ce_loss)
focal_term = (1 - pt).pow(self.gamma)
loss = focal_term * ce_loss
if self.alpha is not None:
if self.alpha.device != loss.device: self.alpha = self.alpha.to(loss.device)
if self.alpha.device != loss.device:
self.alpha = self.alpha.to(loss.device)
alpha_t = self.alpha.gather(0, targets)
loss = alpha_t * loss
if self.reduction == 'mean': return loss.mean()
elif self.reduction == 'sum': return loss.sum()
else: return loss
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else:
return loss
def get_args_parser():
# ... (get_args_parser function remains unchanged) ...
parser = argparse.ArgumentParser('NormWear Fine-tuning', add_help=False)
#dataset args
parser.add_argument('--checkpoint', default='../data/results/model_moco_amp_float16/run_14/checkpoint-199.pth', type=str, help='model checkpoint for fine-tuning')
parser.add_argument('--ds_name', default='ecg_binary8', type=str, help='dataset name')
parser.add_argument('--data_dir', default='../data', type=str, help='dataset path')
parser.add_argument('--output_dir', default='../data/results_finetune', help='path where to save, empty for no saving')
parser.add_argument('--log_dir', default='../data/results_finetune/logs', help='path where to tensorboard log')
parser.add_argument('--device', default='cuda', help='device to use for training / testing')
parser.add_argument('--eval', action='store_true', help='Perform evaluation only')
#model args
parser.add_argument('--embed_dim', type=int, default=768, help='Embedding dimension of the backbone')
parser.add_argument('--depth', type=int, default=12, help='Depth of the transformer backbone')
parser.add_argument('--num_heads', type=int, default=12, help='Number of attention heads in the backbone')
parser.add_argument('--decoder_embed_dim', type=int, default=512,
# dataset args
parser.add_argument('--checkpoint', default='../data/results/model_moco_amp_float16/run_14/checkpoint-199.pth',
type=str, help='model checkpoint for fine-tuning')
parser.add_argument('--ds_name', default='ecg_binary8',
type=str, help='dataset name')
parser.add_argument('--data_dir', default='../data',
type=str, help='dataset path')
parser.add_argument('--output_dir', default='../data/results_finetune',
help='path where to save, empty for no saving')
parser.add_argument('--log_dir', default='../data/results_finetune/logs',
help='path where to tensorboard log')
parser.add_argument('--device', default='cuda',
help='device to use for training / testing')
parser.add_argument('--eval', action='store_true',
help='Perform evaluation only')
# model args
parser.add_argument('--embed_dim', type=int, default=768,
help='Embedding dimension of the backbone')
parser.add_argument('--depth', type=int, default=12,
help='Depth of the transformer backbone')
parser.add_argument('--num_heads', type=int, default=12,
help='Number of attention heads in the backbone')
parser.add_argument('--decoder_embed_dim', type=int, default=512,
help='Decoder embedding dimension')
parser.add_argument('--decoder_depth', type=int, default=8,
parser.add_argument('--decoder_depth', type=int, default=8,
help='Decoder depth')
parser.add_argument('--decoder_num_heads', type=int, default=16,
parser.add_argument('--decoder_num_heads', type=int, default=16,
help='Number of attention heads in decoder')
#finetune args
parser.add_argument('--use_meanpooling', type=int, default=0, help='meanpooling cls fusion in backbone')
# finetune args
parser.add_argument('--use_meanpooling', type=int,
default=0, help='meanpooling cls fusion in backbone')
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--epochs', default=100, type=int)
parser.add_argument('--accum_iter', default=1, type=int)
@@ -120,12 +148,17 @@ def get_args_parser():
parser.add_argument('--weight_decay', type=float, default=0.05)
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
parser.add_argument('--use_focal_loss', action='store_true', help='Use Focal Loss for classification')
parser.add_argument('--focal_gamma', type=float, default=2.0, help='Gamma for Focal Loss')
parser.add_argument('--use_amp', action='store_true', help='Enable Automatic Mixed Precision (AMP) training.')
parser.add_argument('--no_amp', action='store_false', dest='use_amp', help='Disable Automatic Mixed Precision (AMP) training.')
parser.add_argument('--use_focal_loss', action='store_true',
help='Use Focal Loss for classification')
parser.add_argument('--focal_gamma', type=float,
default=2.0, help='Gamma for Focal Loss')
parser.add_argument('--use_amp', action='store_true',
help='Enable Automatic Mixed Precision (AMP) training.')
parser.add_argument('--no_amp', action='store_false', dest='use_amp',
help='Disable Automatic Mixed Precision (AMP) training.')
parser.set_defaults(use_amp=True)
parser.add_argument('--remark', default='finetune_moco', help='A remark for the run')
parser.add_argument('--remark', default='finetune_moco',
help='A remark for the run')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=4, type=int)
parser.add_argument('--pin_mem', action='store_true')
@@ -135,15 +168,23 @@ def get_args_parser():
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--dist_on_itp', action='store_true')
parser.add_argument('--dist_url', default='env://')
#用于控制架构和数据量的参数
parser.add_argument('--use_lora', action='store_true', help='Set this flag to enable LoRA for fine-tuning.')
parser.add_argument('--lora_r', type=int, default=16, help='The rank of the LoRA update matrices.')
parser.add_argument('--lora_alpha', type=int, default=32, help='The alpha scaling factor for LoRA.')
parser.add_argument('--lora_dropout', type=float, default=0.1, help='Dropout for the LoRA layers.')
parser.add_argument('--use_hybrid_embed', action='store_true', help='Set this flag to use the Hybrid (CNN+Transformer) embedding architecture.')
parser.add_argument('--subset_fraction', type=float, default=1.0, help='Fraction of the training data to use (e.g., 0.1 for 10%).')
# 用于控制架构和数据量的参数
parser.add_argument('--use_lora', action='store_true',
help='Set this flag to enable LoRA for fine-tuning.')
parser.add_argument('--lora_r', type=int, default=16,
help='The rank of the LoRA update matrices.')
parser.add_argument('--lora_alpha', type=int, default=32,
help='The alpha scaling factor for LoRA.')
parser.add_argument('--lora_dropout', type=float,
default=0.1, help='Dropout for the LoRA layers.')
parser.add_argument('--use_hybrid_embed', action='store_true',
help='Set this flag to use the Hybrid (CNN+Transformer) embedding architecture.')
parser.add_argument('--subset_fraction', type=float, default=1.0,
help='Fraction of the training data to use (e.g., 0.1 for 10%).')
return parser
def save_prediction_summary(per_sample_results, output_dir, epoch):
"""
Aggregates per-sample results, calculates statistics, and saves to a CSV file.
@@ -175,9 +216,9 @@ def save_prediction_summary(per_sample_results, output_dir, epoch):
'negative_rate': '阴性率',
'label': '真实标签'
})
final_df = summary_df[[
'人物唯一ID_时间戳', '真实标签', '正例样本数',
'人物唯一ID_时间戳', '真实标签', '正例样本数',
'负例样本数', '阳性率', '阴性率'
]]
@@ -186,6 +227,7 @@ def save_prediction_summary(per_sample_results, output_dir, epoch):
print(f"Saved aggregated prediction summary to {csv_path}")
# --- [OPTIMIZED END] ---
def main(args):
misc.init_distributed_mode(args)
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
@@ -205,18 +247,20 @@ def main(args):
run_name = f"{args.remark}_{args.ds_name}_{datetime.datetime.now().strftime('%Y%m%d-%H%M%S')}"
args.output_dir = os.path.join(args.output_dir, run_name)
args.log_dir = os.path.join(args.output_dir, 'logs')
os.makedirs(args.output_dir, exist_ok=True)
os.makedirs(args.log_dir, exist_ok=True)
log_writer = SummaryWriter(log_dir=args.log_dir)
# Directory for raw per-sample data (for accurate plotting)
plot_save_dir = os.path.join(args.output_dir, 'raw_predictions_per_epoch')
plot_save_dir = os.path.join(
args.output_dir, 'raw_predictions_per_epoch')
os.makedirs(plot_save_dir, exist_ok=True)
# Directory for aggregated summary CSVs
summary_save_dir = os.path.join(args.output_dir, 'prediction_summary_csv')
summary_save_dir = os.path.join(
args.output_dir, 'prediction_summary_csv')
os.makedirs(summary_save_dir, exist_ok=True)
dataset_config = DATASET_CONFIG[args.ds_name]
@@ -226,28 +270,32 @@ def main(args):
args.max_len = dataset_config.get("max_len", 390)
args.img_size = (args.max_len - 2, 65)
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
train_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
is_train=True,
max_len=args.max_len,
use_spec=True,
augmentations=train_augmentations,
train_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
is_train=True,
max_len=args.max_len,
use_spec=True,
augmentations=train_augmentations,
img_size=args.img_size,
subset_fraction=args.subset_fraction)
test_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
test_dataset = dataset_class(data_dir=os.path.join(args.data_dir, args.ds_name),
is_train=False,
max_len=args.max_len,
use_spec=True,
augmentations=None,
max_len=args.max_len,
use_spec=True,
augmentations=None,
img_size=args.img_size,
subset_fraction=args.subset_fraction)
if args.distributed:
sampler_train = torch.utils.data.DistributedSampler(train_dataset, shuffle=True)
sampler_val = torch.utils.data.DistributedSampler(test_dataset, shuffle=False)
sampler_train = torch.utils.data.DistributedSampler(
train_dataset, shuffle=True)
sampler_val = torch.utils.data.DistributedSampler(
test_dataset, shuffle=False)
else:
sampler_train = torch.utils.data.RandomSampler(train_dataset)
sampler_val = torch.utils.data.SequentialSampler(test_dataset)
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train,
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val,
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
# === Model Loading and Weight Extraction ===
print(f"Loading pre-trained MoCo checkpoint from: {args.checkpoint}")
@@ -278,7 +326,7 @@ def main(args):
# 冻结所有原始参数
for param in backbone.parameters():
param.requires_grad = False
lora_config = LoraConfig(
r=args.lora_r,
lora_alpha=args.lora_alpha,
@@ -301,20 +349,25 @@ def main(args):
# ... (This section remains unchanged) ...
model_without_ddp = model
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.gpu], find_unused_parameters=True)
model_without_ddp = model.module
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
n_parameters = sum(p.numel()
for p in model.parameters() if p.requires_grad)
print('Number of trainable params: %.2f M' % (n_parameters / 1.e6))
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
if args.lr is None: args.lr = args.blr * eff_batch_size / 256
if args.lr is None:
args.lr = args.blr * eff_batch_size / 256
print("LR: %.2e" % args.lr)
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
optimizer = torch.optim.AdamW(
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
loss_scaler = NativeScaler()
if args.task == 'cls':
criterion = FocalLoss(gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
criterion = FocalLoss(
gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
else:
criterion = torch.nn.L1Loss()
print("Using criterion:", str(criterion))
@@ -329,13 +382,16 @@ def main(args):
if args.distributed:
train_loader.sampler.set_epoch(epoch)
train_stats = train_one_epoch(model, criterion, train_loader, optimizer, device, epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
test_stats, per_sample_results = evaluate(args, test_loader, model, device, criterion, print_analyzer=False, epoch=epoch, plot_save_dir=plot_save_dir)
train_stats = train_one_epoch(model, criterion, train_loader, optimizer,
device, epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
test_stats, per_sample_results = evaluate(
args, test_loader, model, device, criterion, print_analyzer=False, epoch=epoch, plot_save_dir=plot_save_dir)
if misc.is_main_process():
# --- [OPTIMIZED] Call the new function to save the aggregated summary ---
save_prediction_summary(per_sample_results, summary_save_dir, epoch)
save_prediction_summary(
per_sample_results, summary_save_dir, epoch)
if args.task == 'cls':
current_metric = test_stats.get('roc_auc', 0.0)
@@ -351,20 +407,25 @@ def main(args):
f"F1: {test_stats.get('f1_score', 0):.4f}, "
f"Accuracy: {test_stats.get('accuracy', 0):.4f}"
)
if current_metric > max_metric:
max_metric = current_metric
best_epoch = epoch
if args.output_dir:
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch="best")
print(f'Max {metric_name}: {abs(max_metric):.4f} at epoch {best_epoch}')
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp,
optimizer=optimizer, loss_scaler=loss_scaler, epoch="best")
print(
f'Max {metric_name}: {abs(max_metric):.4f} at epoch {best_epoch}')
if log_writer is not None:
log_writer.add_scalar(f'perf/test_{metric_name}', abs(current_metric), epoch)
log_writer.add_scalar('perf/test_loss', test_stats.get('loss', 0.0), epoch)
log_writer.add_scalar('train/loss', train_stats.get('loss', 0.0), epoch)
log_writer.add_scalar(
f'perf/test_{metric_name}', abs(current_metric), epoch)
log_writer.add_scalar(
'perf/test_loss', test_stats.get('loss', 0.0), epoch)
log_writer.add_scalar(
'train/loss', train_stats.get('loss', 0.0), epoch)
if args.distributed:
dist.barrier()
@@ -372,22 +433,26 @@ def main(args):
# ... (This section remains unchanged) ...
if misc.is_main_process():
print('\n####### Loading the best model for final evaluation ######')
best_model_path = os.path.join(args.output_dir, 'checkpoint-best.pth') # Corrected filename based on misc.save_model
# Corrected filename based on misc.save_model
best_model_path = os.path.join(args.output_dir, 'checkpoint-best.pth')
if os.path.exists(best_model_path):
print(f'Loading best model from epoch {best_epoch}')
checkpoint = torch.load(best_model_path, map_location='cpu')
model_without_ddp.load_state_dict(checkpoint['model'])
final_plot_dir = os.path.join(args.output_dir, 'final_plots')
os.makedirs(final_plot_dir, exist_ok=True)
test_stats_best, _ = evaluate(args, test_loader, model, device, criterion, print_analyzer=True, epoch="best", plot_save_dir=final_plot_dir)
print(f"\n--- Final Evaluation (Best Model from Epoch {best_epoch}) ---")
test_stats_best, _ = evaluate(args, test_loader, model, device, criterion,
print_analyzer=True, epoch="best", plot_save_dir=final_plot_dir)
print(
f"\n--- Final Evaluation (Best Model from Epoch {best_epoch}) ---")
for metric, value in test_stats_best.items():
print(f" {metric.capitalize()}: {value:.5f}")
else:
print(f"Warning: Best model checkpoint {best_model_path} not found. Skipping final evaluation.")
print(
f"Warning: Best model checkpoint {best_model_path} not found. Skipping final evaluation.")
total_time = time.time() - start_time
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
@@ -395,8 +460,8 @@ def main(args):
print('Training time {}'.format(total_time_str))
print('Done!')
if __name__ == '__main__':
args = get_args_parser()
args = args.parse_args()
main(args)
+105 -66
View File
@@ -24,17 +24,18 @@ from NormWear.modules.head import RegressionHead, MLPClassificationHead, Classif
from .engine_finetune import train_one_epoch, evaluate
import NormWear.pretrain_pipeline.misc as misc
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount as NativeScaler
from NormWear.pretrain_pipeline.dataset import dataset_class,KFoldDataset
from NormWear.pretrain_pipeline.dataset import dataset_class, KFoldDataset
from peft import LoraConfig, get_peft_model, TaskType
# ==============================================================================
# --- 2. 模型和辅助函数定义 (保持不变) ---
# ==============================================================================
class FinetuneModel(nn.Module):
def __init__(self, backbone, num_channel, embed_dim, num_classes):
super().__init__()
self.backbone = backbone
self.backbone = backbone
head_input_dim = num_channel * embed_dim
self.finetune_head = nn.Sequential(
nn.Linear(head_input_dim, head_input_dim // 2),
@@ -51,41 +52,55 @@ class FinetuneModel(nn.Module):
logits = self.finetune_head(flat_features)
return logits, flat_features
class FocalLoss(nn.Module):
def __init__(self, alpha=None, gamma=2.0, reduction='mean'):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
def forward(self, inputs, targets):
ce_loss = F.cross_entropy(inputs, targets, reduction='none')
pt = torch.exp(-ce_loss)
focal_term = (1 - pt).pow(self.gamma)
loss = focal_term * ce_loss
if self.alpha is not None:
if self.alpha.device != loss.device: self.alpha = self.alpha.to(loss.device)
if self.alpha.device != loss.device:
self.alpha = self.alpha.to(loss.device)
alpha_t = self.alpha.gather(0, targets)
loss = alpha_t * loss
if self.reduction == 'mean': return loss.mean()
elif self.reduction == 'sum': return loss.sum()
else: return loss
if self.reduction == 'mean':
return loss.mean()
elif self.reduction == 'sum':
return loss.sum()
else:
return loss
# ==============================================================================
# --- 3. 参数解析器 ---
# ==============================================================================
def get_args_parser():
parser = argparse.ArgumentParser('NormWear K-Fold Fine-tuning', add_help=False)
parser = argparse.ArgumentParser(
'NormWear K-Fold Fine-tuning', add_help=False)
# --- 数据集和路径 ---
parser.add_argument('--checkpoint', required=True, type=str, help='Path to the pre-trained model checkpoint.')
parser.add_argument('--ds_name', required=True, type=str, help='Dataset name (e.g., ppg_for_kfold).')
parser.add_argument('--data_dir', default='../data', type=str, help='Root directory of datasets.')
parser.add_argument('--output_dir', default='../data/results_finetune_kfold', help='Path to save results.')
parser.add_argument('--log_dir', default=None, help='Path for Tensorboard logs. Defaults to output_dir/logs.')
parser.add_argument('--checkpoint', required=True, type=str,
help='Path to the pre-trained model checkpoint.')
parser.add_argument('--ds_name', required=True, type=str,
help='Dataset name (e.g., ppg_for_kfold).')
parser.add_argument('--data_dir', default='../data',
type=str, help='Root directory of datasets.')
parser.add_argument(
'--output_dir', default='../data/results_finetune_kfold', help='Path to save results.')
parser.add_argument('--log_dir', default=None,
help='Path for Tensorboard logs. Defaults to output_dir/logs.')
# --- K-Fold 配置 ---
parser.add_argument('--n_splits', type=int, default=5, help='Number of splits for Group K-Fold cross-validation.')
parser.add_argument('--n_splits', type=int, default=5,
help='Number of splits for Group K-Fold cross-validation.')
# --- 模型参数 (与预训练保持一致) ---
parser.add_argument('--embed_dim', type=int, default=768)
@@ -99,12 +114,15 @@ def get_args_parser():
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--epochs', default=100, type=int)
parser.add_argument('--accum_iter', default=1, type=int)
parser.add_argument('--blr', type=float, default=1e-4, metavar='LR', help='Base learning rate.')
parser.add_argument('--lr', type=float, default=None, metavar='LR', help='Actual learning rate, calculated if not set.')
parser.add_argument('--blr', type=float, default=1e-4,
metavar='LR', help='Base learning rate.')
parser.add_argument('--lr', type=float, default=None, metavar='LR',
help='Actual learning rate, calculated if not set.')
parser.add_argument('--weight_decay', type=float, default=0.05)
parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N')
parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR')
parser.add_argument('--use_focal_loss', action='store_true', help='Use Focal Loss for classification.')
parser.add_argument('--use_focal_loss', action='store_true',
help='Use Focal Loss for classification.')
parser.add_argument('--focal_gamma', type=float, default=2.0)
parser.add_argument('--use_amp', action='store_true', default=True)
parser.add_argument('--no_amp', action='store_false', dest='use_amp')
@@ -116,27 +134,29 @@ def get_args_parser():
parser.add_argument('--lora_dropout', type=float, default=0.1)
# --- 运行环境 ---
parser.add_argument('--remark', default='finetune_kfold', help='A remark for the run.')
parser.add_argument('--remark', default='finetune_kfold',
help='A remark for the run.')
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--num_workers', default=4, type=int)
parser.add_argument('--pin_mem', action='store_true', default=True)
parser.add_argument('--device', default='cuda')
# --- 分布式训练 (K-Fold通常在单机多卡上运行) ---
parser.add_argument('--world_size', default=1, type=int)
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--dist_on_itp', action='store_true')
parser.add_argument('--dist_url', default='env://')
return parser
# ==============================================================================
# --- 4. 主函数 ---
# ==============================================================================
def main(args):
misc.init_distributed_mode(args)
device = torch.device(args.device)
seed = args.seed + misc.get_rank()
torch.manual_seed(seed)
@@ -163,16 +183,18 @@ def main(args):
args.img_size = (args.max_len - 2, 65)
dataset_root_path = os.path.join(args.data_dir, args.ds_name)
split_file_path = os.path.join(dataset_root_path, 'kfold_split_with_groups.json')
split_file_path = os.path.join(
dataset_root_path, 'kfold_split_with_groups.json')
with open(split_file_path, 'r') as f:
all_samples_info = json.load(f)['samples']
all_samples_info_np = np.array(all_samples_info)
all_labels = np.array([s['binary_label'] for s in all_samples_info])
all_groups = np.array([s['subject_id'] for s in all_samples_info])
if misc.is_main_process():
print(f"Loaded {len(all_samples_info)} total samples for {len(np.unique(all_groups))} subjects.")
print(
f"Loaded {len(all_samples_info)} total samples for {len(np.unique(all_groups))} subjects.")
# --- 3. K-Fold 交叉验证主循环 ---
gkf = GroupKFold(n_splits=args.n_splits)
@@ -187,28 +209,32 @@ def main(args):
# --- a. 为当前折创建数据集 ---
train_samples_info = all_samples_info_np[train_idx].tolist()
test_samples_info = all_samples_info_np[test_idx].tolist()
train_augmentations = {'noise_std': 0.01, 'scale_range': (0.9, 1.1)}
train_dataset = KFoldDataset(data_root_dir=dataset_root_path,
train_dataset = KFoldDataset(data_root_dir=dataset_root_path,
samples_info=train_samples_info,
is_train=True,
augmentations=train_augmentations,
max_len=args.max_len,
use_spec=True,
img_size=args.img_size)
test_dataset = KFoldDataset(data_root_dir=dataset_root_path,
test_dataset = KFoldDataset(data_root_dir=dataset_root_path,
samples_info=test_samples_info,
is_train=False,
max_len=args.max_len,
use_spec=True,
img_size=args.img_size)
sampler_train = torch.utils.data.DistributedSampler(train_dataset, shuffle=True) if args.distributed else torch.utils.data.RandomSampler(train_dataset)
sampler_val = torch.utils.data.DistributedSampler(test_dataset, shuffle=False) if args.distributed else torch.utils.data.SequentialSampler(test_dataset)
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
sampler_train = torch.utils.data.DistributedSampler(
train_dataset, shuffle=True) if args.distributed else torch.utils.data.RandomSampler(train_dataset)
sampler_val = torch.utils.data.DistributedSampler(
test_dataset, shuffle=False) if args.distributed else torch.utils.data.SequentialSampler(test_dataset)
train_loader = DataLoader(train_dataset, batch_size=args.batch_size, sampler=sampler_train,
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True)
test_loader = DataLoader(test_dataset, batch_size=args.batch_size, sampler=sampler_val,
num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False)
# --- b. 重新初始化模型和优化器 ---
backbone = NormWear(
@@ -219,7 +245,8 @@ def main(args):
)
checkpoint = torch.load(args.checkpoint, map_location='cpu')
msg = backbone.load_state_dict(checkpoint['model'], strict=False)
if misc.is_main_process(): print("Backbone loading message:", msg)
if misc.is_main_process():
print("Backbone loading message:", msg)
if args.use_lora:
# ... (LoRA init logic) ...
@@ -229,20 +256,25 @@ def main(args):
backbone=backbone, num_channel=args.num_channel,
embed_dim=args.embed_dim, num_classes=args.num_classes
).to(device)
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
model_without_ddp = model.module if args.distributed else model
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
if args.lr is None: args.lr = args.blr * eff_batch_size / 256
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
loss_scaler = NativeScaler()
criterion = FocalLoss(gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
log_writer = SummaryWriter(log_dir=os.path.join(args.log_dir, f"fold_{fold+1}")) if misc.is_main_process() else None
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.gpu], find_unused_parameters=True)
model_without_ddp = model.module if args.distributed else model
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
if args.lr is None:
args.lr = args.blr * eff_batch_size / 256
optimizer = torch.optim.AdamW(
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
loss_scaler = NativeScaler()
criterion = FocalLoss(
gamma=args.focal_gamma) if args.use_focal_loss else torch.nn.CrossEntropyLoss()
log_writer = SummaryWriter(log_dir=os.path.join(
args.log_dir, f"fold_{fold+1}")) if misc.is_main_process() else None
# --- c. 训练和评估当前折 ---
max_metric = -float('inf')
@@ -252,25 +284,28 @@ def main(args):
if args.distributed:
train_loader.sampler.set_epoch(epoch)
train_one_epoch(model, criterion, train_loader, optimizer, device, epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
train_one_epoch(model, criterion, train_loader, optimizer, device,
epoch, loss_scaler, max_norm=1.0, log_writer=log_writer, args=args)
# 只在主进程上进行评估,以避免冗余计算和文件写入
if misc.is_main_process():
test_stats, _ = evaluate(args, test_loader, model, device, criterion, print_analyzer=False)
test_stats, _ = evaluate(
args, test_loader, model, device, criterion, print_analyzer=False)
current_metric = test_stats.get('roc_auc', 0.0)
if current_metric > max_metric:
max_metric = current_metric
best_epoch_stats = test_stats
# 保存当前折的最佳模型
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp,
misc.save_model(args=args, model=model, model_without_ddp=model_without_ddp,
optimizer=optimizer, loss_scaler=loss_scaler, epoch=f"fold_{fold+1}_best")
if args.distributed:
dist.barrier() # 等待所有进程完成当前epoch
dist.barrier() # 等待所有进程完成当前epoch
if misc.is_main_process():
print(f"\n--- Best Result for Fold {fold + 1} (AUC: {max_metric:.4f}) ---")
print(
f"\n--- Best Result for Fold {fold + 1} (AUC: {max_metric:.4f}) ---")
print(pd.Series(best_epoch_stats))
fold_results.append(best_epoch_stats)
if log_writer:
@@ -281,41 +316,45 @@ def main(args):
print("\n" + "="*80)
print(" CROSS-VALIDATION FINAL RESULTS")
print("="*80)
if not fold_results:
print("No fold results to summarize. Exiting.")
else:
results_df = pd.DataFrame(fold_results)
# --- 【核心修复】 ---
# 在调用 .mean() 和 .std() 之前,先选择只包含数值类型的列。
# numeric_only=True 参数会自动帮你完成这件事。
final_summary_mean = results_df.mean(numeric_only=True)
final_summary_std = results_df.std(numeric_only=True)
# --- [修复结束] ---
# 将均值和标准差合并到一个DataFrame中以便美观地打印
summary_df = pd.DataFrame({'mean': final_summary_mean, 'std': final_summary_std})
summary_df = pd.DataFrame(
{'mean': final_summary_mean, 'std': final_summary_std})
print("--- Performance Summary (mean ± std) across all folds ---")
# 使用 to_string() 可以确保打印所有行和列
print(summary_df.to_string())
# 保存详细的每折结果 (包括非数值列)
summary_path = os.path.join(args.output_dir, "cv_summary_results.csv")
summary_path = os.path.join(
args.output_dir, "cv_summary_results.csv")
try:
results_df.to_csv(summary_path, index_label="fold")
print(f"\nSaved detailed fold results to {summary_path}")
except Exception as e:
print(f"\nCould not save detailed results to CSV due to non-serializable data: {e}")
print(
f"\nCould not save detailed results to CSV due to non-serializable data: {e}")
# 如果保存失败,可以尝试只保存数值部分
results_df.select_dtypes(include=np.number).to_csv(summary_path, index_label="fold")
results_df.select_dtypes(include=np.number).to_csv(
summary_path, index_label="fold")
print(f"Saved only numeric fold results to {summary_path}")
print('Done!')
if __name__ == '__main__':
args = get_args_parser()
args = args.parse_args()
main(args)
main(args)
+22 -17
View File
@@ -6,6 +6,7 @@ from timm.models.layers import DropPath, Mlp
# 以确保与您项目中其他部分兼容
from timm.models.vision_transformer import Attention
class OneD_CNN_Extractor(nn.Module):
"""
一个从1D原始信号中提取特征的CNN模块。
@@ -14,11 +15,12 @@ class OneD_CNN_Extractor(nn.Module):
2. 通过多层卷积进行降采样,使其输出序列长度 L_out 与2D CWT图像的时间维度Patch数匹配。
3. 将特征维度提升到 embed_dim。
"""
def __init__(self, input_len, in_channels, embed_dim, num_downsamples=3):
super().__init__()
layers = []
current_channels = in_channels
# 构建一个多层的1D CNN,逐步降采样并增加特征维度
for i in range(num_downsamples):
out_channels = embed_dim // (2**(num_downsamples - 1 - i))
@@ -26,15 +28,15 @@ class OneD_CNN_Extractor(nn.Module):
current_channels,
out_channels,
kernel_size=3,
stride=2, # 每次将序列长度减半
stride=2, # 每次将序列长度减半
padding=1
))
layers.append(nn.BatchNorm1d(out_channels))
layers.append(nn.GELU())
current_channels = out_channels
self.cnn_layers = nn.Sequential(*layers)
# 动态计算输出序列长度,以确保与2D部分匹配
with torch.no_grad():
dummy_input = torch.randn(1, in_channels, input_len)
@@ -43,13 +45,15 @@ class OneD_CNN_Extractor(nn.Module):
def forward(self, x):
# x 形状: [Batch, in_channels, sequence_length]
return self.cnn_layers(x) # 输出形状: [Batch, embed_dim, self.output_len]
return self.cnn_layers(x) # 输出形状: [Batch, embed_dim, self.output_len]
class ConvEnhancedBlock(nn.Module):
"""
一个增强版的Transformer块,在标准的自注意力(Attention)和MLP层之外,
并联了一个卷积模块来增强局部特征提取能力。
"""
def __init__(
self,
dim,
@@ -61,7 +65,7 @@ class ConvEnhancedBlock(nn.Module):
drop_path=0.,
act_layer=nn.GELU,
norm_layer=nn.LayerNorm,
conv_kernel_size=7, # [新增] 卷积核大小
conv_kernel_size=7, # [新增] 卷积核大小
):
super().__init__()
self.norm1 = norm_layer(dim)
@@ -72,7 +76,8 @@ class ConvEnhancedBlock(nn.Module):
attn_drop=attn_drop,
proj_drop=drop
)
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.drop_path = DropPath(
drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(
@@ -92,8 +97,8 @@ class ConvEnhancedBlock(nn.Module):
in_channels=dim,
out_channels=dim,
kernel_size=conv_kernel_size,
padding=conv_kernel_size // 2, # 'same' padding
groups=dim, # 这是深度卷积的关键
padding=conv_kernel_size // 2, # 'same' padding
groups=dim, # 这是深度卷积的关键
bias=False,
),
# 3. 批归一化 (BatchNorm)
@@ -112,25 +117,25 @@ class ConvEnhancedBlock(nn.Module):
def forward(self, x):
# x 形状: [Batch, Num_Patches, Embed_Dim]
# --- 第一部分:自注意力 ---
# 残差连接 + 自注意力
x = x + self.drop_path(self.attn(self.norm1(x)))
# --- 第二部分:MLP + 卷积 ---
# 准备卷积输入
x_normed = self.norm2(x)
# MLP路径
x_mlp = self.mlp(x_normed)
# 卷积路径
# 调整形状以适应Conv1d: [B, L, D] -> [B, D, L]
x_conv = x_normed.transpose(1, 2)
x_conv = self.conv_module(x_conv)
x_conv = x_conv.transpose(1, 2) # 调整回 [B, L, D]
x_conv = x_conv.transpose(1, 2) # 调整回 [B, L, D]
# 残差连接,将自注意力的输出与MLP和卷积的输出相加
x = x + self.drop_path(x_mlp) + self.drop_path(x_conv)
return x
return x
+79 -55
View File
@@ -1,17 +1,21 @@
#head.py
# head.py
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
class SigmoidRange(nn.Module):
def __init__(self, low, high):
super().__init__()
self.low, self.high = low, high
# self.low, self.high = ranges
def forward(self, x):
self.low, self.high = low, high
# self.low, self.high = ranges
def forward(self, x):
# return sigmoid_range(x, self.low, self.high)
return torch.sigmoid(x) * (self.high - self.low) + self.low
class RegressionHead(nn.Module):
def __init__(self, n_vars, d_model, output_dim, head_dropout=0.1, y_range=None):
super().__init__()
@@ -19,17 +23,18 @@ class RegressionHead(nn.Module):
self.flatten = nn.Flatten(start_dim=1)
self.dropout = nn.Dropout(head_dropout)
self.linear = nn.Linear(n_vars*d_model, output_dim)
def forward(self, x):
"""
x: [bs x nvars x num_patch x d_model]
output: [bs x output_dim]
"""
x = x[:,:,0,:] # only consider the cls_token, x: bs x nvars x d_model
x = x[:, :, 0, :] # only consider the cls_token, x: bs x nvars x d_model
x = self.flatten(x) # x: bs x nvars * d_model
x = self.dropout(x) # 128 x 3072
y = self.linear(x) # y: bs x output_dim
if self.y_range: y = SigmoidRange(*self.y_range)(y)
if self.y_range:
y = SigmoidRange(*self.y_range)(y)
return y.squeeze()
@@ -45,24 +50,26 @@ class ClassificationHead(nn.Module):
x: [bs x nvars x num_patch x d_model]
output: [bs x n_classes]
"""
x = x[:,:,0,:] # only consider the cls_token, x: bs x nvars x d_model
x = x[:, :, 0, :] # only consider the cls_token, x: bs x nvars x d_model
x = self.flatten(x) # x: bs x nvars * d_model
x = self.dropout(x)
y = self.linear(x) # y: bs x n_classes
return y
class MLPClassificationHead(nn.Module):
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3):
super().__init__()
self.flatten = nn.Flatten(start_dim=1)
input_dim = n_vars * d_model
hidden_dim = input_dim // hidden_dim_multiplier # 或者一个固定的值,例如 512, 1024
hidden_dim = input_dim // hidden_dim_multiplier # 或者一个固定的值,例如 512, 1024
self.fc_stack = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.BatchNorm1d(hidden_dim), # 可选,但常用于MLP
nn.ReLU(), # 或者 nn.GELU()
nn.BatchNorm1d(hidden_dim), # 可选,但常用于MLP
nn.ReLU(), # 或者 nn.GELU()
nn.Dropout(head_dropout),
nn.Linear(hidden_dim, n_classes)
)
@@ -72,15 +79,17 @@ class MLPClassificationHead(nn.Module):
x: [bs x nvars x num_patch x d_model]
output: [bs x n_classes]
"""
x = x[:,:,0,:] # 仍然只考虑 cls_token
x = x[:, :, 0, :] # 仍然只考虑 cls_token
x = self.flatten(x) # x: bs x nvars * d_model
y = self.fc_stack(x)
return y
class MLPClassificationHeadWithMeanPatchPooling(nn.Module):
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3):
super().__init__()
self.flatten_vars = nn.Flatten(start_dim=1) # 用于最后拼接不同变量的池化特征
self.flatten_vars = nn.Flatten(start_dim=1) # 用于最后拼接不同变量的池化特征
# 输入到 MLP 的维度是 n_vars * d_model,因为每个变量的补丁池化后得到一个 d_model 维向量
input_dim_to_mlp = n_vars * d_model
hidden_dim = input_dim_to_mlp // hidden_dim_multiplier
@@ -101,57 +110,64 @@ class MLPClassificationHeadWithMeanPatchPooling(nn.Module):
# 1. 对每个变量的 num_patch 维度进行平均池化
# x 的形状是 [bs, n_vars, num_patch, d_model]
# 我们想在 dim=2 (num_patch 维度) 上进行平均池化
pooled_patch_features_per_var = torch.mean(x, dim=2) # 结果形状: [bs, n_vars, d_model]
pooled_patch_features_per_var = torch.mean(
x, dim=2) # 结果形状: [bs, n_vars, d_model]
# 2. 展平/拼接不同变量的池化特征
# pooled_patch_features_per_var 已经是 [bs, n_vars, d_model]
# flatten_vars 会将其变为 [bs, n_vars * d_model]
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
flattened_aggregated_features = self.flatten_vars(
pooled_patch_features_per_var)
# 3. 通过 MLP 分类器
y = self.fc_stack(flattened_aggregated_features)
return y
class AttentionPatchPooling(nn.Module):
def __init__(self, d_model, num_heads=4):
super().__init__()
# 使用一个简单的线性层作为查询,或者一个可学习的参数
self.query = nn.Parameter(torch.randn(1, d_model))
self.query = nn.Parameter(torch.randn(1, d_model))
# 或者更复杂的,例如一个小型MLP来生成查询
# self.attention = nn.MultiheadAttention(d_model, num_heads, batch_first=True)
# self.attention = nn.MultiheadAttention(d_model, num_heads, batch_first=True)
# MultiheadAttention 可能对于单个变量内的补丁池化来说过于复杂,
# 可以用更简单的点积注意力或加性注意力。
# 简化的加性注意力或缩放点积注意力
self.W_k = nn.Linear(d_model, d_model, bias=False)
self.W_q = nn.Linear(d_model, d_model, bias=False) # 如果查询是动态生成的
self.W_q = nn.Linear(d_model, d_model, bias=False) # 如果查询是动态生成的
self.W_v = nn.Linear(d_model, d_model, bias=False)
self.temperature = np.sqrt(d_model)
def forward(self, patches_per_var):
# patches_per_var: [bs, num_patch, d_model]
bs, num_p, d = patches_per_var.shape
q = self.query.unsqueeze(0).expand(bs, -1, -1) # [bs, 1, d_model]
q = self.query.unsqueeze(0).expand(bs, -1, -1) # [bs, 1, d_model]
# 或者 q = self.W_q(some_context_vector)
k = self.W_k(patches_per_var) # [bs, num_patch, d_model]
v = self.W_v(patches_per_var) # [bs, num_patch, d_model]
k = self.W_k(patches_per_var) # [bs, num_patch, d_model]
v = self.W_v(patches_per_var) # [bs, num_patch, d_model]
attn_scores = torch.bmm(q, k.transpose(1, 2)) / self.temperature # [bs, 1, num_patch]
attn_weights = F.softmax(attn_scores, dim=-1) # [bs, 1, num_patch]
context_vector = torch.bmm(attn_weights, v).squeeze(1) # [bs, d_model]
attn_scores = torch.bmm(q, k.transpose(1, 2)) / \
self.temperature # [bs, 1, num_patch]
attn_weights = F.softmax(attn_scores, dim=-1) # [bs, 1, num_patch]
context_vector = torch.bmm(attn_weights, v).squeeze(1) # [bs, d_model]
return context_vector
class MLPClassificationHeadWithAttentionPatchPooling(nn.Module):
def __init__(self, n_vars, d_model, n_classes, hidden_dim_multiplier=2, head_dropout=0.3, num_attn_heads_patch=1):
super().__init__()
self.n_vars = n_vars
self.patch_poolers = nn.ModuleList(
[AttentionPatchPooling(d_model, num_heads=num_attn_heads_patch) for _ in range(n_vars)]
[AttentionPatchPooling(d_model, num_heads=num_attn_heads_patch)
for _ in range(n_vars)]
)
self.flatten_vars = nn.Flatten(start_dim=1)
input_dim_to_mlp = n_vars * d_model
hidden_dim = input_dim_to_mlp // hidden_dim_multiplier
@@ -168,36 +184,39 @@ class MLPClassificationHeadWithAttentionPatchPooling(nn.Module):
bs = x.size(0)
pooled_features_list = []
for i in range(self.n_vars):
var_patches = x[:, i, :, :] # [bs, num_patch, d_model]
var_patches = x[:, i, :, :] # [bs, num_patch, d_model]
pooled_features_list.append(self.patch_poolers[i](var_patches))
concatenated_features = torch.stack(pooled_features_list, dim=1) # [bs, n_vars, d_model]
flattened_aggregated_features = self.flatten_vars(concatenated_features) # [bs, n_vars * d_model]
concatenated_features = torch.stack(
pooled_features_list, dim=1) # [bs, n_vars, d_model]
flattened_aggregated_features = self.flatten_vars(
concatenated_features) # [bs, n_vars * d_model]
y = self.fc_stack(flattened_aggregated_features)
return y
class DeeperMLPClassificationHeadWithMeanPatchPooling(nn.Module):
def __init__(self, n_vars, d_model, n_classes,
hidden_dims=[512, 256], # 定义多个隐藏层维度
def __init__(self, n_vars, d_model, n_classes,
hidden_dims=[512, 256], # 定义多个隐藏层维度
head_dropout=0.3, use_batchnorm=True):
super().__init__()
self.flatten_vars = nn.Flatten(start_dim=1)
input_dim_to_mlp = n_vars * d_model
layers = []
current_dim = input_dim_to_mlp
for h_dim in hidden_dims:
layers.append(nn.Linear(current_dim, h_dim))
if use_batchnorm:
layers.append(nn.BatchNorm1d(h_dim))
layers.append(nn.ReLU()) # 或者 nn.GELU()
layers.append(nn.ReLU()) # 或者 nn.GELU()
layers.append(nn.Dropout(head_dropout))
current_dim = h_dim
layers.append(nn.Linear(current_dim, n_classes)) # 最后的输出层
layers.append(nn.Linear(current_dim, n_classes)) # 最后的输出层
self.fc_stack = nn.Sequential(*layers)
def forward(self, x):
@@ -206,27 +225,31 @@ class DeeperMLPClassificationHeadWithMeanPatchPooling(nn.Module):
output: [bs, n_classes]
"""
pooled_patch_features_per_var = torch.mean(x, dim=2)
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
flattened_aggregated_features = self.flatten_vars(
pooled_patch_features_per_var)
y = self.fc_stack(flattened_aggregated_features)
return y
class MLPClassificationHeadWithMeanPatchPoolingAdjustable(nn.Module):
def __init__(self, n_vars, d_model, n_classes,
def __init__(self, n_vars, d_model, n_classes,
hidden_dim=768, # 直接指定隐藏层维度
head_dropout=0.3 # 直接指定 Dropout 率
):
):
super().__init__()
self.flatten_vars = nn.Flatten(start_dim=1)
input_dim_to_mlp = n_vars * d_model
# 确保 hidden_dim 是一个合理的值,例如,如果太小可能没有意义
if hidden_dim <= 0:
print(f"Warning: hidden_dim ({hidden_dim}) is not positive. Setting to a default value (e.g., 128 or input_dim_to_mlp // 4).")
hidden_dim = max(128, input_dim_to_mlp // 4) # 示例默认值
print(
f"Warning: hidden_dim ({hidden_dim}) is not positive. Setting to a default value (e.g., 128 or input_dim_to_mlp // 4).")
hidden_dim = max(128, input_dim_to_mlp // 4) # 示例默认值
self.fc_stack = nn.Sequential(
nn.Linear(input_dim_to_mlp, hidden_dim),
nn.BatchNorm1d(hidden_dim), # 考虑是否保留 BatchNorm
nn.BatchNorm1d(hidden_dim), # 考虑是否保留 BatchNorm
nn.ReLU(),
nn.Dropout(head_dropout),
nn.Linear(hidden_dim, n_classes)
@@ -234,6 +257,7 @@ class MLPClassificationHeadWithMeanPatchPoolingAdjustable(nn.Module):
def forward(self, x):
pooled_patch_features_per_var = torch.mean(x, dim=2)
flattened_aggregated_features = self.flatten_vars(pooled_patch_features_per_var)
flattened_aggregated_features = self.flatten_vars(
pooled_patch_features_per_var)
y = self.fc_stack(flattened_aggregated_features)
return y
+4 -2
View File
@@ -6,13 +6,15 @@
import math
def adjust_learning_rate(optimizer, epoch, args):
"""Decay the learning rate with half-cycle cosine after warmup"""
if epoch < args.warmup_epochs:
lr = args.lr * epoch / args.warmup_epochs
lr = args.lr * epoch / args.warmup_epochs
else:
lr = args.min_lr + (args.lr - args.min_lr) * 0.5 * \
(1. + math.cos(math.pi * (epoch - args.warmup_epochs) / (args.epochs - args.warmup_epochs)))
(1. + math.cos(math.pi * (epoch - args.warmup_epochs) /
(args.epochs - args.warmup_epochs)))
for param_group in optimizer.param_groups:
if "lr_scale" in param_group:
param_group["lr"] = lr * param_group["lr_scale"]
+122 -76
View File
@@ -10,6 +10,8 @@ from .patch_embed import HybridPatchEmbed
# --------------------------------------------------------------------------
# MAE 辅助函数 (保持不变)
# --------------------------------------------------------------------------
def random_masking(x, mask_ratio):
N, L, D = x.shape
len_keep = int(L * (1.0 - mask_ratio))
@@ -17,7 +19,8 @@ def random_masking(x, mask_ratio):
ids_shuffle = torch.argsort(noise, dim=1)
ids_restore = torch.argsort(ids_shuffle, dim=1)
ids_keep = ids_shuffle[:, :len_keep]
x_masked = torch.gather(x, dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, D))
x_masked = torch.gather(
x, dim=1, index=ids_keep.unsqueeze(-1).expand(-1, -1, D))
mask = torch.ones([N, L], device=x.device)
mask[:, :len_keep] = 0
mask = torch.gather(mask, dim=1, index=ids_restore)
@@ -26,18 +29,20 @@ def random_masking(x, mask_ratio):
# --------------------------------------------------------------------------
# 最终的 NormWear 类 (多模态重建MAE版本)
# --------------------------------------------------------------------------
class NormWear(nn.Module):
def __init__(self, img_size=(387,65), patch_size=(9,5), in_chans=3,
def __init__(self, img_size=(387, 65), patch_size=(9, 5), in_chans=3,
embed_dim=768, depth=12, num_heads=12,
decoder_embed_dim=512, decoder_depth=8, decoder_num_heads=16,
mlp_ratio=4., norm_layer=nn.LayerNorm,
loss_weight_1d_token=0.3, # [修改] 权重参数重命名
loss_weight_1d_signal=0.3, # [新增] 新的1D信号重建损失权重
loss_weight_1d_token=0.3, # [修改] 权重参数重命名
loss_weight_1d_signal=0.3, # [新增] 新的1D信号重建损失权重
modality_dropout_prob=0.0,
nvar=4,
**kwargs):
super().__init__()
self.patch_size = patch_size
# [修改] 初始化新的权重参数
self.loss_weight_1d_token = loss_weight_1d_token
@@ -47,70 +52,86 @@ class NormWear(nn.Module):
self.modality_dropout_prob = modality_dropout_prob
self.num_modalities = 2
# --- 编码器输入部分 (1D+2D) ---
self.patch_embed = HybridPatchEmbed(img_size, in_chans=in_chans, embed_dim=embed_dim)
self.patch_embed = HybridPatchEmbed(
img_size, in_chans=in_chans, embed_dim=embed_dim)
num_patches = self.patch_embed.num_patches
self.cnn_1d_extractor = OneD_CNN_Extractor(
input_len=img_size[0], in_channels=1, embed_dim=embed_dim, num_downsamples=3
)
assert self.cnn_1d_extractor.output_len == self.patch_embed.patch_hw[0], \
f"Seq len mismatch: 1D CNN ({self.cnn_1d_extractor.output_len}) vs 2D Embed ({self.patch_embed.patch_hw[0]})"
self.norm_cwt_tokens = nn.LayerNorm(embed_dim)
self.norm_1d_tokens = nn.LayerNorm(embed_dim)
self.fusion_gate = nn.Parameter(torch.zeros(1))
# --- 编码器主体 (保持不变) ---
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim), requires_grad=False)
self.pos_embed = nn.Parameter(torch.zeros(
1, num_patches + 1, embed_dim), requires_grad=False)
self.encoder_blocks = nn.ModuleList([
ConvEnhancedBlock(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, norm_layer=norm_layer)
ConvEnhancedBlock(dim=embed_dim, num_heads=num_heads,
mlp_ratio=mlp_ratio, norm_layer=norm_layer)
for _ in range(depth)])
self.norm = norm_layer(embed_dim)
# --- 解码器 (保持不变) ---
self.decoder_embed = nn.Linear(embed_dim, decoder_embed_dim, bias=True)
self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_embed_dim))
self.decoder_pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, decoder_embed_dim), requires_grad=False)
self.decoder_pos_embed = nn.Parameter(torch.zeros(
1, num_patches + 1, decoder_embed_dim), requires_grad=False)
from timm.models.vision_transformer import Block
self.decoder_blocks = nn.ModuleList([
Block(dim=decoder_embed_dim, num_heads=decoder_num_heads, mlp_ratio=mlp_ratio, norm_layer=norm_layer)
Block(dim=decoder_embed_dim, num_heads=decoder_num_heads,
mlp_ratio=mlp_ratio, norm_layer=norm_layer)
for _ in range(decoder_depth)])
self.decoder_norm = norm_layer(decoder_embed_dim)
# --- [核心修改] 三路重建头 ---
# 1. CWT像素重建头 (保持不变)
self.decoder_pred_cwt = nn.Sequential(
nn.ConvTranspose2d(decoder_embed_dim, decoder_embed_dim // 2, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.ConvTranspose2d(decoder_embed_dim, decoder_embed_dim //
2, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.GELU(),
nn.ConvTranspose2d(decoder_embed_dim // 2, decoder_embed_dim // 4, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.ConvTranspose2d(decoder_embed_dim // 2, decoder_embed_dim //
4, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.GELU(),
nn.ConvTranspose2d(decoder_embed_dim // 4, in_chans, kernel_size=3, stride=2, padding=1, output_padding=1)
nn.ConvTranspose2d(decoder_embed_dim // 4, in_chans,
kernel_size=3, stride=2, padding=1, output_padding=1)
)
# 2. 1D Token重建头 (保持不变)
self.decoder_pred_1d_token = nn.Linear(decoder_embed_dim, embed_dim, bias=True)
self.decoder_pred_1d_token = nn.Linear(
decoder_embed_dim, embed_dim, bias=True)
# 3. [新增] 1D 原始信号重建头
# 这个头将学习一个近似的逆小波变换
# HybridPatchEmbed 降采样了 2*2*2=8 倍,所以我们需要上采样8倍
self.decoder_pred_1d_signal = nn.Sequential(
nn.ConvTranspose1d(decoder_embed_dim, decoder_embed_dim // 4, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.ConvTranspose1d(decoder_embed_dim, decoder_embed_dim //
4, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.GELU(),
nn.ConvTranspose1d(decoder_embed_dim // 4, decoder_embed_dim // 16, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.ConvTranspose1d(decoder_embed_dim // 4, decoder_embed_dim //
16, kernel_size=3, stride=2, padding=1, output_padding=1),
nn.GELU(),
nn.ConvTranspose1d(decoder_embed_dim // 16, 1, kernel_size=3, stride=2, padding=1, output_padding=1)
nn.ConvTranspose1d(decoder_embed_dim // 16, 1,
kernel_size=3, stride=2, padding=1, output_padding=1)
)
self.initialize_weights()
# --- [修改] 重命名 decoder_pred_1d -> decoder_pred_1d_token ---
def initialize_weights(self):
pos_embed = get_2d_sincos_pos_embed_flexible(self.pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))
decoder_pos_embed = get_2d_sincos_pos_embed_flexible(self.decoder_pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
self.decoder_pos_embed.data.copy_(torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
pos_embed = get_2d_sincos_pos_embed_flexible(
self.pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
self.pos_embed.data.copy_(
torch.from_numpy(pos_embed).float().unsqueeze(0))
decoder_pos_embed = get_2d_sincos_pos_embed_flexible(
self.decoder_pos_embed.shape[-1], self.patch_embed.patch_hw, cls_token=True)
self.decoder_pos_embed.data.copy_(
torch.from_numpy(decoder_pos_embed).float().unsqueeze(0))
torch.nn.init.normal_(self.cls_token, std=.02)
torch.nn.init.normal_(self.mask_token, std=.02)
self.apply(self._init_weights)
@@ -123,7 +144,8 @@ class NormWear(nn.Module):
elif isinstance(m, (nn.LayerNorm, nn.BatchNorm1d, nn.BatchNorm2d)):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
elif isinstance(m, (nn.Conv1d, nn.Conv2d, nn.ConvTranspose1d, nn.ConvTranspose2d)): # [修改] 增加 ConvTranspose1d
# [修改] 增加 ConvTranspose1d
elif isinstance(m, (nn.Conv1d, nn.Conv2d, nn.ConvTranspose1d, nn.ConvTranspose2d)):
torch.nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
@@ -131,18 +153,22 @@ class NormWear(nn.Module):
# --- 其他辅助函数 (保持不变) ---
def _forward_features(self, x_cwt, x_1d):
cwt_tokens = self.patch_embed(x_cwt)
cnn_1d_features = self.cnn_1d_extractor(x_1d.unsqueeze(1)).transpose(1, 2)
cnn_1d_features = self.cnn_1d_extractor(
x_1d.unsqueeze(1)).transpose(1, 2)
num_freq_patches = self.patch_embed.patch_hw[1]
cnn_1d_tokens = cnn_1d_features.unsqueeze(2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
cnn_1d_tokens = cnn_1d_features.unsqueeze(
2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
cwt_tokens_normed = self.norm_cwt_tokens(cwt_tokens)
cnn_1d_tokens_normed = self.norm_1d_tokens(cnn_1d_tokens)
gate = torch.sigmoid(self.fusion_gate)
fused_tokens = (cwt_tokens_normed * gate) + (cnn_1d_tokens_normed * (1 - gate))
fused_tokens = (cwt_tokens_normed * gate) + \
(cnn_1d_tokens_normed * (1 - gate))
return fused_tokens, cwt_tokens, cnn_1d_tokens
def forward_encoder(self, fused_tokens, mask_ratio):
tokens_with_pos = fused_tokens + self.pos_embed[:, 1:, :]
tokens_masked, mask, ids_restore = random_masking(tokens_with_pos, mask_ratio)
tokens_masked, mask, ids_restore = random_masking(
tokens_with_pos, mask_ratio)
cls_token = self.cls_token + self.pos_embed[:, :1, :]
cls_tokens = cls_token.expand(tokens_masked.shape[0], -1, -1)
x = torch.cat((cls_tokens, tokens_masked), dim=1)
@@ -153,9 +179,11 @@ class NormWear(nn.Module):
def forward_decoder(self, x, ids_restore):
x = self.decoder_embed(x)
mask_tokens = self.mask_token.repeat(x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
mask_tokens = self.mask_token.repeat(
x.shape[0], ids_restore.shape[1] + 1 - x.shape[1], 1)
x_ = torch.cat([x[:, 1:, :], mask_tokens], dim=1)
x_ = torch.gather(x_, dim=1, index=ids_restore.unsqueeze(-1).expand(-1, -1, x.shape[2]))
x_ = torch.gather(
x_, dim=1, index=ids_restore.unsqueeze(-1).expand(-1, -1, x.shape[2]))
x = torch.cat([x[:, :1, :], x_], dim=1)
x = x + self.decoder_pos_embed
for blk in self.decoder_blocks:
@@ -164,50 +192,59 @@ class NormWear(nn.Module):
return x
# --- [核心修改] forward_loss 函数,计算三路损失 ---
def forward_loss(self,
pred_cwt_imgs, x_cwt_orig,
pred_1d_tokens, cnn_1d_tokens_orig,
def forward_loss(self,
pred_cwt_imgs, x_cwt_orig,
pred_1d_tokens, cnn_1d_tokens_orig,
pred_1d_signal, x_1d_orig,
mask):
"""
计算三路重建损失。
"""
# 1. CWT重建损失 (在像素空间)
pred_cwt_imgs = pred_cwt_imgs[:, :, :x_cwt_orig.shape[2], :x_cwt_orig.shape[3]]
pred_cwt_imgs = pred_cwt_imgs[:, :,
:x_cwt_orig.shape[2], :x_cwt_orig.shape[3]]
loss_cwt = (pred_cwt_imgs - x_cwt_orig) ** 2
loss_cwt = loss_cwt.mean(dim=1, keepdim=True)
mask_pixel = mask.reshape(shape=(mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1]))
mask_pixel = mask_pixel.unsqueeze(1).repeat_interleave(self.patch_size[0], dim=2).repeat_interleave(self.patch_size[1], dim=3)
mask_pixel = mask.reshape(shape=(
mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1]))
mask_pixel = mask_pixel.unsqueeze(1).repeat_interleave(
self.patch_size[0], dim=2).repeat_interleave(self.patch_size[1], dim=3)
if mask_pixel.shape[2:] != x_cwt_orig.shape[2:]:
mask_pixel = torch.nn.functional.interpolate(mask_pixel.float(), size=x_cwt_orig.shape[2:], mode='nearest')
mask_pixel = torch.nn.functional.interpolate(
mask_pixel.float(), size=x_cwt_orig.shape[2:], mode='nearest')
loss_cwt = (loss_cwt * mask_pixel).sum() / (mask_pixel.sum() + 1e-8)
# 2. 1D Token重建损失 (在特征空间)
loss_1d_token = ((pred_1d_tokens - cnn_1d_tokens_orig) ** 2).mean(dim=-1)
loss_1d_token = ((pred_1d_tokens - cnn_1d_tokens_orig)
** 2).mean(dim=-1)
loss_1d_token = (loss_1d_token * mask).sum() / (mask.sum() + 1e-8)
# 3. [新增] 1D 原始信号重建损失 (在信号空间)
# 创建一个与原始信号长度匹配的掩码
mask_signal = mask.reshape(mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1])
mask_signal = mask.reshape(
mask.shape[0], self.patch_embed.patch_hw[0], self.patch_embed.patch_hw[1])
# 我们只关心时间维度的掩码
mask_signal = mask_signal[:, :, 0] # Shape: [B, H_patches]
mask_signal = mask_signal.unsqueeze(-1).repeat_interleave(self.patch_size[0], dim=-1).flatten(1,2)
mask_signal = mask_signal[:, :x_1d_orig.shape[1]] # 裁剪到精确长度
mask_signal = mask_signal[:, :, 0] # Shape: [B, H_patches]
mask_signal = mask_signal.unsqueeze(-1).repeat_interleave(
self.patch_size[0], dim=-1).flatten(1, 2)
mask_signal = mask_signal[:, :x_1d_orig.shape[1]] # 裁剪到精确长度
loss_1d_signal = (pred_1d_signal - x_1d_orig) ** 2
loss_1d_signal = (loss_1d_signal * mask_signal).sum() / (mask_signal.sum() + 1e-8)
if torch.rand(1) < 0.01: # 每1%的概率打印一次,避免刷屏
print(f"\n[Loss Debug] CWT: {loss_cwt.item():.4f}, Token: {loss_1d_token.item():.4f}, Signal: {loss_1d_signal.item():.4f}")
loss_1d_signal = (loss_1d_signal * mask_signal).sum() / \
(mask_signal.sum() + 1e-8)
if torch.rand(1) < 0.01: # 每1%的概率打印一次,避免刷屏
print(
f"\n[Loss Debug] CWT: {loss_cwt.item():.4f}, Token: {loss_1d_token.item():.4f}, Signal: {loss_1d_signal.item():.4f}")
# 4. 加权总损失
loss_cwt_weight = 1 - self.loss_weight_1d_token - self.loss_weight_1d_signal
total_loss = (loss_cwt_weight * loss_cwt +
self.loss_weight_1d_token * loss_1d_token +
total_loss = (loss_cwt_weight * loss_cwt +
self.loss_weight_1d_token * loss_1d_token +
self.loss_weight_1d_signal * loss_1d_signal)
return total_loss, loss_cwt, loss_1d_token, loss_1d_signal
# --- [核心修改] 主 forward 函数 ---
@@ -218,10 +255,12 @@ class NormWear(nn.Module):
# --- 步骤 1: 计算所有原始目标 ---
with torch.no_grad():
orig_cnn_1d_features = self.cnn_1d_extractor(x_1d_reshaped.unsqueeze(1)).transpose(1, 2)
orig_cnn_1d_features = self.cnn_1d_extractor(
x_1d_reshaped.unsqueeze(1)).transpose(1, 2)
num_freq_patches = self.patch_embed.patch_hw[1]
cnn_1d_tokens_orig_target = orig_cnn_1d_features.unsqueeze(2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
cnn_1d_tokens_orig_target = orig_cnn_1d_features.unsqueeze(
2).expand(-1, -1, num_freq_patches, -1).flatten(1, 2)
# 原始1D信号本身就是目标
x_1d_orig_target = x_1d_reshaped
@@ -236,29 +275,35 @@ class NormWear(nn.Module):
x_1d_for_encoder = torch.zeros_like(x_1d_reshaped)
# --- 步骤 3: 特征提取和融合 ---
fused_tokens, _, _ = self._forward_features(x_cwt_for_encoder, x_1d_for_encoder)
fused_tokens, _, _ = self._forward_features(
x_cwt_for_encoder, x_1d_for_encoder)
# --- 步骤 4: 编码、解码 ---
latent, mask, ids_restore = self.forward_encoder(fused_tokens, mask_ratio)
latent, mask, ids_restore = self.forward_encoder(
fused_tokens, mask_ratio)
decoded_features = self.forward_decoder(latent, ids_restore)
# --- 步骤 5: 三路重建 ---
decoded_patches = decoded_features[:, 1:, :]
h_patch, w_patch = self.patch_embed.patch_hw
decoded_feature_map = decoded_patches.reshape(decoded_patches.shape[0], h_patch, w_patch, -1).permute(0, 3, 1, 2)
decoded_feature_map = decoded_patches.reshape(
decoded_patches.shape[0], h_patch, w_patch, -1).permute(0, 3, 1, 2)
# 5.1 CWT 图像重建
pred_cwt_imgs = self.decoder_pred_cwt(decoded_feature_map)
pred_cwt_imgs = pred_cwt_imgs[:, :, :L, :F_]
# 5.2 1D Token 重建
pred_1d_tokens = self.decoder_pred_1d_token(decoded_features)[:, 1:, :]
# 5.3 [新增] 1D 原始信号重建
# 我们需要从2D特征图解码,所以先对频率维度做平均池化,得到时间序列特征
decoded_features_for_1d_signal = torch.mean(decoded_feature_map, dim=3) # Shape: [B, D_decoder, H_patch]
pred_1d_signal_unshaped = self.decoder_pred_1d_signal(decoded_features_for_1d_signal)
pred_1d_signal = pred_1d_signal_unshaped.squeeze(1)[:, :L] # Shape: [B, L]
decoded_features_for_1d_signal = torch.mean(
decoded_feature_map, dim=3) # Shape: [B, D_decoder, H_patch]
pred_1d_signal_unshaped = self.decoder_pred_1d_signal(
decoded_features_for_1d_signal)
pred_1d_signal = pred_1d_signal_unshaped.squeeze(
1)[:, :L] # Shape: [B, L]
# --- 步骤 6: 计算损失 ---
loss, _, _, _ = self.forward_loss(
@@ -266,16 +311,16 @@ class NormWear(nn.Module):
x_cwt_orig=x_cwt_reshaped,
pred_1d_tokens=pred_1d_tokens,
cnn_1d_tokens_orig=cnn_1d_tokens_orig_target,
pred_1d_signal=pred_1d_signal, # <-- 新增
pred_1d_signal=pred_1d_signal, # <-- 新增
x_1d_orig=x_1d_orig_target, # <-- 新增
mask=mask
)
# --- 步骤 7: 返回值 ---
pred_pixels_unshaped = pred_cwt_imgs.view(N, nvar, ch, L, F_)
pred_signal_unshaped = pred_1d_signal.view(N, nvar, L) # [新增]
pred_signal_unshaped = pred_1d_signal.view(N, nvar, L) # [新增]
mask_unshaped = mask.view(N, nvar, -1)
# [修改] 返回值中可以加入重建的信号,方便可视化
return loss, pred_pixels_unshaped, pred_signal_unshaped, mask_unshaped
@@ -286,19 +331,20 @@ class NormWear(nn.Module):
N, nvar, ch, L, F_ = x_cwt.shape
x_cwt_reshaped = x_cwt.reshape(N * nvar, ch, L, F_)
x_1d_reshaped = x_1d.reshape(N * nvar, L)
fused_tokens, _, _ = self._forward_features(x_cwt_reshaped, x_1d_reshaped)
fused_tokens, _, _ = self._forward_features(
x_cwt_reshaped, x_1d_reshaped)
pos_embed = self.pos_embed
tokens_with_pos = fused_tokens + pos_embed[:, 1:, :]
cls_token = self.cls_token + pos_embed[:, :1, :]
cls_tokens = cls_token.expand(tokens_with_pos.shape[0], -1, -1)
x = torch.cat((cls_tokens, tokens_with_pos), dim=1)
for blk in self.encoder_blocks:
x = blk(x)
x = self.norm(x)
BN, P, E = x.shape
final_features = torch.reshape(x, (N, nvar, P, E))
return final_features
return final_features
+36 -26
View File
@@ -4,13 +4,15 @@ from .pos_embed import tAPE
from torch.cuda.amp import autocast
from timm.models.layers import to_2tuple
class PatchEmbed_new(nn.Module):
""" Flexible Image to Patch Embedding
"""
def __init__(self, img_size=224,
patch_size=16,
in_chans=3,
embed_dim=768,
def __init__(self, img_size=224,
patch_size=16,
in_chans=3,
embed_dim=768,
stride=16,
dropout=0.1,
scale_factor=1.0,
@@ -20,26 +22,27 @@ class PatchEmbed_new(nn.Module):
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
stride = to_2tuple(stride)
self.use_tAPE = use_tAPE
self.img_size = img_size
self.patch_size = patch_size
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride)
self.proj = nn.Conv2d(in_chans, embed_dim,
kernel_size=patch_size, stride=stride)
_, _, h, w = self.get_output_shape(img_size)
self.patch_hw = (h, w)
self.num_patches = h*w
if use_tAPE:
self.time_pos_embed = tAPE(d_model=embed_dim, max_len=h,
dropout=dropout,scale_factor=scale_factor)
self.time_pos_embed = tAPE(d_model=embed_dim, max_len=h,
dropout=dropout, scale_factor=scale_factor)
def get_output_shape(self, img_size, device=torch.device('cpu')):
return self.proj(torch.randn(1,3,img_size[0],img_size[1]).to(device)).shape
return self.proj(torch.randn(1, 3, img_size[0], img_size[1]).to(device)).shape
def forward(self, x):
B, C, H, W = x.shape
# [修复] 强制在 float32 下执行卷积以保证数值稳定性
# 即使外部的 autocast 上下文是 float16,这个内部的上下文也会覆盖它。
with autocast(enabled=True, dtype=torch.float32):
@@ -52,60 +55,67 @@ class PatchEmbed_new(nn.Module):
x = x.transpose(1, 2)
return x
class HybridPatchEmbed(nn.Module):
"""
使用一个小型CNN作为Stem来提取局部特征,然后再进行Patch嵌入。
"""
def __init__(self, img_size=224, in_chans=3, embed_dim=768):
super().__init__()
img_size = to_2tuple(img_size)
self.img_size = img_size
self.stem = nn.Sequential(
nn.Conv2d(in_chans, embed_dim // 4, kernel_size=3, stride=2, padding=1),
nn.Conv2d(in_chans, embed_dim // 4,
kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(embed_dim // 4),
nn.GELU(),
nn.Conv2d(embed_dim // 4, embed_dim // 2, kernel_size=3, stride=2, padding=1),
nn.Conv2d(embed_dim // 4, embed_dim // 2,
kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(embed_dim // 2),
nn.GELU(),
nn.Conv2d(embed_dim // 2, embed_dim, kernel_size=3, stride=2, padding=1),
nn.Conv2d(embed_dim // 2, embed_dim,
kernel_size=3, stride=2, padding=1),
nn.BatchNorm2d(embed_dim),
)
with torch.no_grad():
dummy_input = torch.randn(1, in_chans, img_size[0], img_size[1])
output_shape = self.stem(dummy_input).shape
self.patch_hw = (output_shape[2], output_shape[3])
self.num_patches = self.patch_hw[0] * self.patch_hw[1]
def forward(self, x):
# [修复] 同样,强制在 float32 下执行整个 stem 网络
with autocast(enabled=True, dtype=torch.float32):
x = self.stem(x.float())
x = x.flatten(2)
x = x.transpose(1, 2)
return x
class PatchEmbed_ts(nn.Module):
# ... (这个类暂时不需要修改,因为它处理1D数据,但加上保护也是好的) ...
def __init__(self, ts_len=387,
patch_size=9,
embed_dim=768,
def __init__(self, ts_len=387,
patch_size=9,
embed_dim=768,
stride=9,
dropout=0.1,
scale_factor=1.0,):
super().__init__()
self.ts_len = ts_len
self.patch_size = patch_size
self.proj = nn.Conv1d(in_channels=1,out_channels=embed_dim,kernel_size=patch_size,stride=patch_size)
self.proj = nn.Conv1d(in_channels=1, out_channels=embed_dim,
kernel_size=patch_size, stride=patch_size)
bs, E, P = self.get_output_shape(ts_len)
self.patch_hw = patch_size
self.num_patches = P
def get_output_shape(self, ts_len):
return self.proj(torch.randn(1,1,ts_len)).shape
return self.proj(torch.randn(1, 1, ts_len)).shape
def forward(self, x):
bs, L = x.shape
@@ -116,4 +126,4 @@ class PatchEmbed_ts(nn.Module):
x = x.permute(0, 2, 1)
return x
# ... (if __name__ == '__main__': 部分保持不变) ...
# ... (if __name__ == '__main__': 部分保持不变) ...
+34 -21
View File
@@ -15,13 +15,16 @@ class tAPE(nn.Module):
self.dropout = nn.Dropout(p=dropout)
pe = torch.zeros(max_len, d_model) # positional encoding
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
div_term = torch.exp(torch.arange(
0, d_model, 2).float() * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin((position * div_term)*(d_model/max_len))
pe[:, 1::2] = torch.cos((position * div_term)*(d_model/max_len))
pe[:, 1::2] = torch.cos((position * div_term)*(d_model/max_len))
pe = scale_factor * pe.unsqueeze(0).unsqueeze(-1).permute(0, 2, 1, 3) # pe: L,E -> 1,E,1,L
self.register_buffer('pe', pe) # this stores the variable in the state_dict (used for non-trainable variables)
# pe: L,E -> 1,E,1,L
pe = scale_factor * pe.unsqueeze(0).unsqueeze(-1).permute(0, 2, 1, 3)
# this stores the variable in the state_dict (used for non-trainable variables)
self.register_buffer('pe', pe)
def forward(self, x):
"""Inputs of forward function
@@ -32,7 +35,7 @@ class tAPE(nn.Module):
output: [batch size*nvars, embed_dim, time length, frequency length]
"""
x = x + self.pe[:, :, :x.size(2), :]
x = x + self.pe[:, :, :x.size(2), :]
return self.dropout(x)
@@ -51,19 +54,24 @@ def get_2d_sincos_pos_embed_flexible(embed_dim, grid_size, cls_token=False):
grid = grid.reshape([2, 1, grid_size[0], grid_size[1]])
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
if cls_token:
pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
pos_embed = np.concatenate(
[np.zeros([1, embed_dim]), pos_embed], axis=0)
return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb_h = get_1d_sincos_pos_embed_from_grid(
embed_dim // 2, grid[0]) # (H*W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid(
embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
"""
embed_dim: output dimension for each position
@@ -78,13 +86,14 @@ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
pos = pos.reshape(-1) # (M,)
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2)
emb_cos = np.cos(out) # (M, D/2)
emb_sin = np.sin(out) # (M, D/2)
emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
return emb
def interpolate_pos_embed(model, checkpoint_model,orig_size=(43,13),new_size=(43,13)):
def interpolate_pos_embed(model, checkpoint_model, orig_size=(43, 13), new_size=(43, 13)):
'''
Input: model: the class is definging for downstream
checkpoint_model: pre-train weight
@@ -92,21 +101,25 @@ def interpolate_pos_embed(model, checkpoint_model,orig_size=(43,13),new_size=(43
'''
if 'pos_embed' in checkpoint_model:
pos_embed_checkpoint = checkpoint_model['pos_embed'] # 1 x 560 x 768 (1 x num_patches x E)
embedding_size = pos_embed_checkpoint.shape[-1] # 768
# 1 x 560 x 768 (1 x num_patches x E)
pos_embed_checkpoint = checkpoint_model['pos_embed']
embedding_size = pos_embed_checkpoint.shape[-1] # 768
# number of special tokens (e.g. in this case num_extra_tokens = 1 for the cls token)
num_patches = model.patch_embed.num_patches
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
num_patches = model.patch_embed.num_patches
num_extra_tokens = model.pos_embed.shape[-2] - num_patches
if orig_size != new_size:
print("Position interpolate from %dx%d to %dx%d" % (orig_size[0], orig_size[1], new_size[0], new_size[1]))
print("Position interpolate from %dx%d to %dx%d" %
(orig_size[0], orig_size[1], new_size[0], new_size[1]))
extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
# only the position tokens are interpolated
pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] # old positions
pos_tokens = pos_tokens.reshape(-1, orig_size[0], orig_size[1], embedding_size).permute(0, 3, 1, 2)
pos_tokens = pos_embed_checkpoint[:,
num_extra_tokens:] # old positions
pos_tokens = pos_tokens.reshape(
-1, orig_size[0], orig_size[1], embedding_size).permute(0, 3, 1, 2)
pos_tokens = torch.nn.functional.interpolate(
pos_tokens, size=(new_size[0], new_size[1]), mode='bicubic', align_corners=False)
pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
checkpoint_model['pos_embed'] = new_pos_embed
checkpoint_model['pos_embed'] = new_pos_embed
+137 -103
View File
@@ -13,12 +13,14 @@ import json
import numpy as np
from torchvision import transforms
from functools import partial
class LinearProbDataset(Dataset):
def __init__(self,fnames,task):
#self.dataset_path = os.path.join(data_dir,dataset_name,'samples')
def __init__(self, fnames, task):
# self.dataset_path = os.path.join(data_dir,dataset_name,'samples')
self.fnames = fnames
self.max_L = 387 # fix length
self.max_L = 387 # fix length
self.task = task
def __len__(self):
@@ -30,39 +32,40 @@ class LinearProbDataset(Dataset):
with open(f_path, 'rb') as f:
data_dict = pickle.load(f)
#x = torch.from_numpy(data_dict['cwt']).permute(0, 3, 1, 2) # n_var, 3, L, 65
# x = torch.from_numpy(data_dict['cwt']).permute(0, 3, 1, 2) # n_var, 3, L, 65
x = torch.from_numpy(data_dict['cwt']) # n_var, 3, L, 65
'''
在使用cwt_wrap函数时已经进行了变换
'''
if torch.isnan(x).any():
return None # Ignore the sample with NaN values
n_var, n_channels, L, H = x.size()
padded_inputs = torch.zeros((n_var, n_channels, self.max_L, H))
if L < self.max_L:
padded_inputs[:, :, -L:, :] = x
else:
padded_inputs = x[:, :, -self.max_L:, :]
label = data_dict['label']
if isinstance(label, dict):
values = [label[key] for key in label.keys()]
label = values
if self.task == "reg":
label = torch.tensor(label).float()
else:
label = torch.tensor(label).long()
return {
'input':padded_inputs,
'label':label,
'input': padded_inputs,
'label': label,
}
def linprob_collate_fn(batch):
batch = [b for b in batch if b is not None]
return default_collate(batch)
@@ -71,18 +74,20 @@ def linprob_collate_fn(batch):
########################################################################################################################################################
########################################################################################################################################################
########################################################################################################################################################
class PretrainDataset(Dataset):
# [修改] 增加 subset_fraction 参数
def __init__(self, data_dir, dataset_names, is_test=0,
def __init__(self, data_dir, dataset_names, is_test=0,
window_size=387,
stride=100,
img_size=(387, 65),
cache_name: str = None,
subset_fraction: float = 0.15): # [新增] 控制数据量的参数
subset_fraction: float = 0.15): # [新增] 控制数据量的参数
self.window_size = window_size
self.stride = stride
# --- [修改] 缓存逻辑 ---
# 1. 如果手动指定了缓存名,则直接使用它,这是最优先、最稳定的方式。
if cache_name:
@@ -90,7 +95,8 @@ class PretrainDataset(Dataset):
if not cache_name.endswith('.pkl'):
cache_name += '.pkl'
cache_path = os.path.join(data_dir, cache_name)
print(f"Attempting to load from manually specified cache: {cache_path}")
print(
f"Attempting to load from manually specified cache: {cache_path}")
else:
# 2. 如果没有手动指定,则使用稳定的方法生成文件名 (不再使用不稳定的 hash)
# 将数据集名称排序并用'-'连接,这比哈希更稳定
@@ -108,15 +114,16 @@ class PretrainDataset(Dataset):
if is_test:
print("Running in test mode, bypassing cache...")
else:
print(f"No cache found at '{cache_path}'. Preprocessing dataset (this will happen only once for this configuration)...")
print(
f"No cache found at '{cache_path}'. Preprocessing dataset (this will happen only once for this configuration)...")
fnames = [
os.path.join(data_dir, dataset_name, fn)
for dataset_name in dataset_names
for fn in sorted(os.listdir(os.path.join(data_dir, dataset_name)))
if fn[0] != "."
]
if is_test == 1:
]
if is_test == 1:
fnames = fnames[:20]
self.windows = []
@@ -124,7 +131,7 @@ class PretrainDataset(Dataset):
try:
with open(fname, 'rb') as f:
data_dict = pickle.load(f)
_, L = torch.from_numpy(data_dict['data']).float().shape
if L < self.window_size:
@@ -136,52 +143,58 @@ class PretrainDataset(Dataset):
except Exception as e:
# print(f"Warning: Could not process file {fname}. Error: {e}")
continue
# 5. 如果不是测试模式,将计算结果保存到缓存文件
if not is_test:
print(f"Saving computed windows to cache for future use: {cache_path}")
print(
f"Saving computed windows to cache for future use: {cache_path}")
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
with open(cache_path, 'wb') as f:
pickle.dump(self.windows, f)
# [新增] 根据 subset_fraction 参数对数据进行子集采样
if subset_fraction < 1.0:
if not (0.0 < subset_fraction <= 1.0):
raise ValueError("subset_fraction must be between 0.0 and 1.0")
num_samples = int(len(self.windows) * subset_fraction)
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
rng = random.Random(42)
rng.shuffle(self.windows)
self.windows = self.windows[:num_samples]
print(f"[INFO] Pre-training with a subset of {len(self.windows)} windows ({subset_fraction * 100:.1f}% of the total).")
print(
f"[INFO] Pre-training with a subset of {len(self.windows)} windows ({subset_fraction * 100:.1f}% of the total).")
print(f"Dataset initialized with {len(self.windows)} windows.")
# --- CWT 和数据增强部分保持不变 ---
self.cwt_scales = torch.arange(1, img_size[1] + 1)
self.transform = transforms.Compose([
transforms.RandomResizedCrop(size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
transforms.RandomHorizontalFlip(), # 水平翻转对于时频谱图是有效增强
transforms.RandomResizedCrop(
size=(img_size[1], img_size[0]), scale=(0.5, 1.0), antialias=True),
transforms.RandomHorizontalFlip(), # 水平翻转对于时频谱图是有效增强
])
def __len__(self):
return len(self.windows)
def __getitem__(self, idx):
try:
fname, start_idx = self.windows[idx]
with open(fname, 'rb') as f:
data_dict = pickle.load(f)
full_signal = torch.from_numpy(data_dict['data']).float()
raw_signal_window = full_signal[:, start_idx : start_idx + self.window_size]
raw_signal_window = full_signal[:,
start_idx: start_idx + self.window_size]
# 清理和标准化1D信号
if not torch.all(torch.isfinite(raw_signal_window)):
raw_signal_window = torch.nan_to_num(raw_signal_window, nan=0.0)
raw_signal_window = torch.nan_to_num(
raw_signal_window, nan=0.0)
mean = torch.mean(raw_signal_window, dim=1, keepdim=True)
std = torch.std(raw_signal_window, dim=1, keepdim=True)
std[std == 0] = 1.0
@@ -191,7 +204,7 @@ class PretrainDataset(Dataset):
cwt_images = cwt_wrap(processed_signal_1d, self.cwt_scales)
if not torch.all(torch.isfinite(cwt_images)):
return None
# 3. 对CWT图像进行数据增强,作为模型的输入
cwt_images_permuted = cwt_images.permute(0, 1, 3, 2)
augmented_cwt_permuted = self.transform(cwt_images_permuted)
@@ -199,7 +212,7 @@ class PretrainDataset(Dataset):
return {
'input_cwt': augmented_cwt,
'input_1d': processed_signal_1d, # 预测目标
'input_1d': processed_signal_1d, # 预测目标
}
except Exception as e:
# print(f"Error processing window at index {idx}: {e}. Skipping.")
@@ -217,6 +230,7 @@ def ricker_wavelet(points, scale):
gauss = torch.exp(-xsq / (2 * wsq))
return A * mod * gauss
def cwt_ricker(x, scales, wavelet_len):
"""
Compute the CWT using the Ricker wavelet.
@@ -227,16 +241,19 @@ def cwt_ricker(x, scales, wavelet_len):
"""
batch_size, sequence_length = x.shape
x = x.unsqueeze(1) # -> (batch, 1, sequence_length)
num_scales = scales.shape[0]
scales = scales.to(x.device)
effective_wavelet_len = min(wavelet_len, sequence_length)
wavelets = torch.stack([ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
wavelets = wavelets.view(num_scales, 1, -1) # -> (num_scales, 1, wavelet_len)
wavelets = torch.stack(
[ricker_wavelet(effective_wavelet_len, scale) for scale in scales])
# -> (num_scales, 1, wavelet_len)
wavelets = wavelets.view(num_scales, 1, -1)
cwt_output = F.conv1d(x, wavelets, padding='same')
return cwt_output # -> (batch, num_scales, sequence_length)
return cwt_output # -> (batch, num_scales, sequence_length)
def cwt_wrap(x, scales):
"""
@@ -259,22 +276,26 @@ def cwt_wrap(x, scales):
d2_padded = F.pad(d2, (2, 0), 'replicate')
# 3. Stack the aligned signals
stacked_x = torch.stack([original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
stacked_x = torch.stack(
[original_x, d1_padded, d2_padded], dim=1) # -> (n_var, 3, L)
n_var, n_channels, L_stacked = stacked_x.shape
flat_x = stacked_x.reshape(n_var * n_channels, L_stacked)
# 4. Compute CWT
wavelet_len = 257 # A fixed reasonable length
cwt_res = cwt_ricker(flat_x, scales, wavelet_len) # -> (n_var * 3, num_scales, L)
wavelet_len = 257 # A fixed reasonable length
# -> (n_var * 3, num_scales, L)
cwt_res = cwt_ricker(flat_x, scales, wavelet_len)
_, n_scales, _ = cwt_res.shape
# 5. Reshape to final format
final_cwt = cwt_res.reshape(n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
final_cwt = cwt_res.reshape(
n_var, n_channels, n_scales, L_stacked).permute(0, 1, 3, 2)
return final_cwt
def collate_fn(batch, pad_nvar=5):
"""
一个为MAE预训练设计的collate_fn。
@@ -283,10 +304,10 @@ def collate_fn(batch, pad_nvar=5):
- 对每个样本的变量数量(n_vars)进行填充或采样,使其在batch内保持一致。
"""
# --- 1. 过滤和处理无效样本 (与MoCo版本相同,非常鲁棒) ---
# 过滤掉在__getitem__中返回None的样本
batch = [b for b in batch if b is not None]
# 如果过滤后整个batch为空,则返回None,让训练循环处理
if not batch:
return None
@@ -297,41 +318,44 @@ def collate_fn(batch, pad_nvar=5):
# 这里我们假设batch不为空,因为上面已经检查过了。
# --- 2. 对每个样本的变量数量(n_vars)进行填充或采样 ---
processed_batch = []
for item in batch:
# 获取当前样本的变量数
# 我们以CWT输入的第一个维度为准
n_var = item['input_cwt'].size(0)
# 如果变量数与目标填充数相同,则不做任何处理
if n_var == pad_nvar:
processed_batch.append(item)
continue
new_item = {}
# 如果变量数大于目标数,则随机采样
if n_var > pad_nvar:
indices = random.sample(range(n_var), pad_nvar)
indices = torch.tensor(indices)
new_item['input_cwt'] = item['input_cwt'][indices]
new_item['input_1d'] = item['input_1d'][indices]
# 如果变量数小于目标数,则进行填充
elif n_var < pad_nvar:
# 复制最后一个有效变量来进行填充
last_cwt = item['input_cwt'][-1:].expand(pad_nvar - n_var, -1, -1, -1)
last_cwt = item['input_cwt'][-1:].expand(
pad_nvar - n_var, -1, -1, -1)
last_1d = item['input_1d'][-1:].expand(pad_nvar - n_var, -1)
new_item['input_cwt'] = torch.cat([item['input_cwt'], last_cwt], dim=0)
new_item['input_1d'] = torch.cat([item['input_1d'], last_1d], dim=0)
new_item['input_cwt'] = torch.cat(
[item['input_cwt'], last_cwt], dim=0)
new_item['input_1d'] = torch.cat(
[item['input_1d'], last_1d], dim=0)
processed_batch.append(new_item)
# --- 3. 使用PyTorch默认的collate函数进行最终的批处理 ---
# default_collate会将字典列表 [{k1:v1, k2:v2}, ...]
# default_collate会将字典列表 [{k1:v1, k2:v2}, ...]
# 转换为一个字典 {k1:[v1, ...], k2:[v2, ...]} 并将值堆叠成张量
return default_collate(processed_batch)
# --- 3. 返回一个包含所有处理好数据的字典 ---
@@ -348,30 +372,32 @@ class dataset_class(Dataset):
- Includes robust padding and error handling.
"""
# [修改] 增加 subset_fraction 参数
def __init__(self, data_dir, is_train=True, max_len=390, use_spec=False, augmentations=None, img_size=(387, 65), subset_fraction: float = 1.0):
super(dataset_class, self).__init__()
self.data_dir = data_dir
self.is_train = is_train
# 1. 加载数据集划分
with open(os.path.join(self.data_dir, 'train_test_split.json'), 'r') as file:
split = json.load(file)
self.file_list = split['train'] if self.is_train else split['test']
# [新增] 根据 subset_fraction 参数对训练数据进行子集采样
# 注意:只对训练集进行采样,测试集应保持完整以进行公正评估
if self.is_train and subset_fraction < 1.0:
if not (0.0 < subset_fraction <= 1.0):
raise ValueError("subset_fraction must be between 0.0 and 1.0")
num_samples = int(len(self.file_list) * subset_fraction)
# 使用固定的种子来确保每次采样的子集是相同的,保证实验可复现
rng = random.Random(42)
rng.shuffle(self.file_list)
self.file_list = self.file_list[:num_samples]
print(f"[INFO] Fine-tuning with a subset of {len(self.file_list)} files ({subset_fraction * 100:.1f}% of the original training set).")
print(
f"[INFO] Fine-tuning with a subset of {len(self.file_list)} files ({subset_fraction * 100:.1f}% of the original training set).")
# 2. 明确定义标签映射
# 0: 健康 (Negative class)
@@ -381,14 +407,15 @@ class dataset_class(Dataset):
2: 1, # 原始标签2是'有病',映射为索引1
}
if is_train:
print(f"Using predefined label map for fine-tuning: {self.label_map}")
print(
f"Using predefined label map for fine-tuning: {self.label_map}")
self.max_len = max_len
self.use_spec = use_spec
# 3. 初始化 CWT scales
if not isinstance(img_size, tuple) or len(img_size) != 2:
img_size = (max_len - 2, 65)
img_size = (max_len - 2, 65)
self.cwt_scales = torch.arange(1, img_size[1] + 1)
# 4. 初始化数据增强
@@ -406,12 +433,13 @@ class dataset_class(Dataset):
sample_id = os.path.splitext(curr_fn)[0]
parts = sample_id.split('_')
session_id = f"{parts[0]}_{parts[1]}" if len(parts) >= 2 else parts[0]
session_id = f"{parts[0]}_{parts[1]}" if len(
parts) >= 2 else parts[0]
# 1. 加载并清理1D信号
tss = torch.from_numpy(data['data']).float()
tss = torch.nan_to_num(tss, 0.0)
original_label = data['label'][0]['class']
if original_label not in self.label_map:
return None
@@ -421,9 +449,11 @@ class dataset_class(Dataset):
# 2. [训练时] 应用1D数据增强
if self.augmentations:
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
tss = tss + torch.randn_like(tss) * self.augmentations['noise_std']
tss = tss + \
torch.randn_like(tss) * self.augmentations['noise_std']
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
scale = torch.rand(1).item() * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
scale = torch.rand(1).item(
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
tss = tss * scale
# 3. 序列长度处理 (填充或裁剪)
@@ -434,13 +464,13 @@ class dataset_class(Dataset):
pad_size = self.max_len - current_L
pad_values = tss[:, 0:1].expand(-1, pad_size)
tss = torch.cat((pad_values, tss), dim=1)
# --- [核心修改] ---
# 4. 标准化1D信号,这将作为1D CNN的输入
mean = torch.mean(tss, dim=1, keepdim=True)
std = torch.std(tss, dim=1, keepdim=True)
std[std == 0] = 1.0 # 增加保护
std[std == 0] = 1.0 # 增加保护
processed_signal_1d = (tss - mean) / (std + 1e-8)
# 5. 构建包含所有需要信息的返回字典
@@ -448,7 +478,7 @@ class dataset_class(Dataset):
'label': label,
'session_id': session_id,
'sample_id': sample_id,
'input_1d': processed_signal_1d, # <-- [新增] 返回处理好的1D信号
'input_1d': processed_signal_1d, # <-- [新增] 返回处理好的1D信号
}
# 6. 如果需要,计算CWT并添加到字典中
@@ -457,11 +487,11 @@ class dataset_class(Dataset):
if not torch.all(torch.isfinite(cwt)):
# print(f"Warning: NaN in CWT for {curr_fn}. Skipping.")
return None
output_dict['input_cwt'] = cwt # <-- [修改] 键名改为 'input_cwt'
output_dict['input_cwt'] = cwt # <-- [修改] 键名改为 'input_cwt'
else:
# 如果不使用CWT,为了兼容性,可以把1D信号也放入'input'键
output_dict['input'] = processed_signal_1d
return output_dict
except Exception as e:
@@ -470,19 +500,21 @@ class dataset_class(Dataset):
def __len__(self):
return len(self.file_list)
class KFoldDataset(Dataset):
"""
一个为分组K折交叉验证设计的专用数据集类。
它直接从一个包含样本信息的列表中初始化,而不是从磁盘读取划分文件。
"""
def __init__(self,
data_root_dir: str,
samples_info: list,
def __init__(self,
data_root_dir: str,
samples_info: list,
is_train: bool,
max_len: int = 390,
use_spec: bool = True,
augmentations: dict = None,
max_len: int = 390,
use_spec: bool = True,
augmentations: dict = None,
img_size: tuple = (387, 65)):
"""
初始化 KFoldDataset。
@@ -501,12 +533,12 @@ class KFoldDataset(Dataset):
self.samples_dir = os.path.join(data_root_dir, 'samples')
self.samples_info = samples_info
self.is_train = is_train
# --- 其他配置 (与您原来的 dataset_class 保持一致) ---
self.max_len = max_len
self.use_spec = use_spec
self.cwt_scales = torch.arange(1, img_size[1] + 1)
# 只有在 is_train 为 True 时才应用数据增强
self.augmentations = augmentations if self.is_train else None
@@ -517,11 +549,11 @@ class KFoldDataset(Dataset):
try:
# 1. 从列表中获取当前样本的信息
sample_meta = self.samples_info[idx]
filename = sample_meta['filename']
label = torch.tensor(sample_meta['binary_label'], dtype=torch.long)
subject_id = sample_meta['subject_id']
# 2. 加载并处理数据文件
file_path = os.path.join(self.samples_dir, filename)
with open(file_path, 'rb') as file:
@@ -533,13 +565,15 @@ class KFoldDataset(Dataset):
# 3. 加载并清理1D信号
tss = torch.from_numpy(data['data']).float()
tss = torch.nan_to_num(tss, 0.0)
# 4. [训练时] 应用1D数据增强
if self.augmentations:
if 'noise_std' in self.augmentations and torch.rand(1).item() < 0.5:
tss = tss + torch.randn_like(tss) * self.augmentations['noise_std']
tss = tss + \
torch.randn_like(tss) * self.augmentations['noise_std']
if 'scale_range' in self.augmentations and torch.rand(1).item() < 0.5:
scale = torch.rand(1).item() * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
scale = torch.rand(1).item(
) * (self.augmentations['scale_range'][1] - self.augmentations['scale_range'][0]) + self.augmentations['scale_range'][0]
tss = tss * scale
# 5. 序列长度处理 (填充或裁剪) - 与原来逻辑一致
@@ -550,7 +584,7 @@ class KFoldDataset(Dataset):
pad_size = self.max_len - current_L
pad_values = tss[:, 0:1].expand(-1, pad_size)
tss = torch.cat((pad_values, tss), dim=1)
# 6. 标准化1D信号
mean = torch.mean(tss, dim=1, keepdim=True)
std = torch.std(tss, dim=1, keepdim=True)
@@ -560,7 +594,7 @@ class KFoldDataset(Dataset):
# 7. 构建返回字典
output_dict = {
'label': label,
'session_id': subject_id, # 使用 subject_id 作为 session_id
'session_id': subject_id, # 使用 subject_id 作为 session_id
'sample_id': sample_id,
'input_1d': processed_signal_1d,
}
@@ -568,14 +602,14 @@ class KFoldDataset(Dataset):
# 8. 如果需要,计算CWT
if self.use_spec:
# 假设 cwt_wrap 函数在您的项目中可用
from .dataset import cwt_wrap # 或者其他正确的导入路径
from .dataset import cwt_wrap # 或者其他正确的导入路径
cwt = cwt_wrap(processed_signal_1d, scales=self.cwt_scales)
if not torch.all(torch.isfinite(cwt)):
return None
output_dict['input_cwt'] = cwt
return output_dict
except Exception as e:
# print(f"Error processing sample at index {idx} (file: {self.samples_info[idx]['filename']}): {e}. Skipping.")
return None
return None
+72 -47
View File
@@ -4,7 +4,7 @@ import math
import sys
from typing import Iterable, Optional
import torch
from torch.amp.autocast_mode import autocast
from torch.amp.autocast_mode import autocast
import matplotlib.pyplot as plt
import numpy as np
import os
@@ -18,6 +18,8 @@ import NormWear.modules.lr_sched as lr_sched
# --------------------------------------------------------------------------
# [新增] CWT 与 1D 信号配对可视化函数
# --------------------------------------------------------------------------
def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, epoch, step):
"""
将1D原始信号及其对应的CWT图像一起可视化,以检查它们之间的关系。
@@ -29,11 +31,13 @@ def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, ep
# 只可视化第一个变量和第一个通道
sig_1d = original_signal[0]
img_cwt = cwt_image[0, 0] # 取第一个通道的CWT
img_cwt = cwt_image[0, 0] # 取第一个通道的CWT
# --- 绘图 ---
fig, axs = plt.subplots(2, 1, figsize=(15, 6), sharex=True, gridspec_kw={'height_ratios': [1, 2]})
fig.suptitle(f'1D Signal and its CWT (Epoch {epoch}, Step {step})', fontsize=16)
fig, axs = plt.subplots(2, 1, figsize=(
15, 6), sharex=True, gridspec_kw={'height_ratios': [1, 2]})
fig.suptitle(
f'1D Signal and its CWT (Epoch {epoch}, Step {step})', fontsize=16)
# 上方子图: 1D 信号
axs[0].plot(sig_1d)
@@ -49,10 +53,11 @@ def save_cwt_signal_pair_visualization(original_signal, cwt_image, save_path, ep
axs[1].set_ylabel('CWT Scales')
fig.colorbar(im, ax=axs[1], label='Magnitude')
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # 调整布局以适应主标题
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # 调整布局以适应主标题
os.makedirs(save_path, exist_ok=True)
plt.savefig(os.path.join(save_path, f'cwt_signal_pair_epoch_{epoch}_step_{step}.png'))
plt.savefig(os.path.join(
save_path, f'cwt_signal_pair_epoch_{epoch}_step_{step}.png'))
plt.close(fig)
@@ -73,14 +78,15 @@ def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch
h_patches, w_patches = patch_hw
p_h, p_w = patch_size
mask_pixel = mask_patches.reshape((h_patches, w_patches))
mask_pixel = np.repeat(np.repeat(mask_pixel, p_h, axis=0), p_w, axis=1)
target_h, target_w = img_orig.shape
mask_pixel = np.pad(mask_pixel, ((0, max(0, target_h - mask_pixel.shape[0])), (0, max(0, target_w - mask_pixel.shape[1]))), 'constant', constant_values=0)
mask_pixel = np.pad(mask_pixel, ((0, max(0, target_h - mask_pixel.shape[0])), (0, max(
0, target_w - mask_pixel.shape[1]))), 'constant', constant_values=0)
mask_pixel = mask_pixel[:target_h, :target_w]
img_masked = img_orig * (1 - mask_pixel)
def normalize_for_vis(img):
@@ -88,27 +94,35 @@ def save_mae_image_reconstruction(original_img, pred_img, mask, save_path, epoch
return (img - img_min) / (img_max - img_min + 1e-6)
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
fig.suptitle(f'MAE CWT Reconstruction (Epoch {epoch}, Step {step})', fontsize=16)
fig.suptitle(
f'MAE CWT Reconstruction (Epoch {epoch}, Step {step})', fontsize=16)
axs[0].imshow(normalize_for_vis(img_orig), cmap='viridis', aspect='auto', origin='lower')
axs[0].imshow(normalize_for_vis(img_orig), cmap='viridis',
aspect='auto', origin='lower')
axs[0].set_title('Original')
axs[0].axis('off')
axs[1].imshow(normalize_for_vis(img_masked), cmap='viridis', aspect='auto', origin='lower')
axs[1].set_title(f'Masked ({mask_patches.sum() / mask_patches.size * 100:.1f}% removed)')
axs[1].imshow(normalize_for_vis(img_masked),
cmap='viridis', aspect='auto', origin='lower')
axs[1].set_title(
f'Masked ({mask_patches.sum() / mask_patches.size * 100:.1f}% removed)')
axs[1].axis('off')
axs[2].imshow(normalize_for_vis(img_pred), cmap='viridis', aspect='auto', origin='lower')
axs[2].imshow(normalize_for_vis(img_pred), cmap='viridis',
aspect='auto', origin='lower')
axs[2].set_title('Reconstructed')
axs[2].axis('off')
os.makedirs(save_path, exist_ok=True)
plt.savefig(os.path.join(save_path, f'reconstruction_cwt_epoch_{epoch}_step_{step}.png'))
plt.savefig(os.path.join(
save_path, f'reconstruction_cwt_epoch_{epoch}_step_{step}.png'))
plt.close(fig)
# --------------------------------------------------------------------------
# [已存在] 1D原始信号重建可视化函数
# --------------------------------------------------------------------------
def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path, epoch, step, patch_size, patch_hw):
"""
将MAE的1D信号重建结果可视化并保存。
@@ -130,43 +144,51 @@ def save_mae_signal_reconstruction(original_signal, pred_signal, mask, save_path
visible_indices = np.where(mask_signal == 0)[0]
fig, axs = plt.subplots(3, 1, figsize=(15, 9), sharex=True)
fig.suptitle(f'MAE 1D Signal Reconstruction (Epoch {epoch}, Step {step})', fontsize=16)
fig.suptitle(
f'MAE 1D Signal Reconstruction (Epoch {epoch}, Step {step})', fontsize=16)
axs[0].plot(sig_orig)
axs[0].set_title('Original Signal')
axs[0].grid(True)
axs[1].plot(sig_masked)
axs[1].set_title(f'Masked Signal ({mask_patches.sum() / mask_patches.size * 100:.1f}% removed)')
axs[1].set_title(
f'Masked Signal ({mask_patches.sum() / mask_patches.size * 100:.1f}% removed)')
axs[1].grid(True)
axs[2].plot(sig_orig, label='Original', alpha=0.5)
axs[2].plot(sig_pred, label='Reconstructed', linestyle='--')
axs[2].scatter(visible_indices, sig_orig[visible_indices], color='red', s=10, zorder=5, label='Visible Patches')
axs[2].scatter(visible_indices, sig_orig[visible_indices],
color='red', s=10, zorder=5, label='Visible Patches')
axs[2].set_title('Original vs. Reconstructed')
axs[2].legend()
axs[2].grid(True)
os.makedirs(save_path, exist_ok=True)
plt.savefig(os.path.join(save_path, f'reconstruction_signal_epoch_{epoch}_step_{step}.png'))
plt.savefig(os.path.join(
save_path, f'reconstruction_signal_epoch_{epoch}_step_{step}.png'))
plt.close(fig)
# --------------------------------------------------------------------------
# 修改后的 train_one_epoch 函数
# --------------------------------------------------------------------------
def train_one_epoch(model: torch.nn.Module,
data_loader: Iterable,
data_loader: Iterable,
optimizer: torch.optim.Optimizer,
device: torch.device,
epoch: int,
device: torch.device,
epoch: int,
loss_scaler: Optional[misc.NativeScalerWithGradNormCount],
log_writer=None,
args=None,
dtype: torch.dtype = torch.bfloat16):
model.train(True)
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.6f}'))
metric_logger.add_meter('grad_norm', misc.SmoothedValue(window_size=1, fmt='{value:.2f}'))
metric_logger.add_meter('lr', misc.SmoothedValue(
window_size=1, fmt='{value:.6f}'))
metric_logger.add_meter('grad_norm', misc.SmoothedValue(
window_size=1, fmt='{value:.2f}'))
header = 'Epoch: [{}]'.format(epoch)
print_freq = 20
@@ -185,31 +207,32 @@ def train_one_epoch(model: torch.nn.Module,
for data_iter_step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)):
if (data_iter_step) % accum_iter == 0:
lr_sched.adjust_learning_rate(optimizer, data_iter_step / len(data_loader) + epoch, args)
lr_sched.adjust_learning_rate(
optimizer, data_iter_step / len(data_loader) + epoch, args)
if batch is None:
continue
samples_cwt = batch['input_cwt'].to(device, non_blocking=True)
samples_1d = batch['input_1d'].to(device, non_blocking=True)
with torch.amp.autocast(device_type=device.type, dtype=dtype):
loss, pred_pixels, pred_signal, mask = model(
x_cwt=samples_cwt,
x_cwt=samples_cwt,
x_1d=samples_1d,
mask_ratio=args.mask_ratio
)
loss = loss / accum_iter
loss_value = loss.item()
if not math.isfinite(loss_value):
print(f"Loss is {loss_value}, skipping update.")
optimizer.zero_grad(set_to_none=True)
continue
# --- [核心修复:增加防御性检查和清晰的逻辑分支] ---
grad_norm = None
is_update_step = (data_iter_step + 1) % accum_iter == 0
@@ -218,11 +241,12 @@ def train_one_epoch(model: torch.nn.Module,
# 这是一个防御性检查,确保我们不会调用一个 None 对象
if data_iter_step == 0 and misc.is_main_process():
print(">>> Training with FP16 NativeScaler.")
grad_norm = loss_scaler(
loss, optimizer, parameters=model.parameters(),
update_grad=is_update_step,
clip_grad=args.clip_grad if hasattr(args, 'clip_grad') else None
loss, optimizer, parameters=model.parameters(),
update_grad=is_update_step,
clip_grad=args.clip_grad if hasattr(
args, 'clip_grad') else None
)
# 在非更新步骤,loss_scaler 会返回 None,这是正常的
if is_update_step and grad_norm is None:
@@ -234,16 +258,17 @@ def train_one_epoch(model: torch.nn.Module,
else:
if data_iter_step == 0 and misc.is_main_process():
print(">>> Training without NativeScaler (BF16/FP32 mode).")
# 直接反向传播
loss.backward()
if is_update_step:
# 在更新步骤,我们手动计算梯度范数并更新优化器
parameters = [p for p in model.parameters() if p.requires_grad]
if hasattr(args, 'clip_grad') and args.clip_grad is not None:
grad_norm = torch.nn.utils.clip_grad_norm_(parameters, max_norm=args.clip_grad)
grad_norm = torch.nn.utils.clip_grad_norm_(
parameters, max_norm=args.clip_grad)
else:
# 手动计算总梯度范unorm
total_norm = 0.0
@@ -255,24 +280,24 @@ def train_one_epoch(model: torch.nn.Module,
optimizer.step()
optimizer.zero_grad(set_to_none=True)
torch.cuda.synchronize()
# 记录未缩放的loss
metric_logger.update(loss=loss_value * accum_iter)
metric_logger.update(loss=loss_value * accum_iter)
lr = optimizer.param_groups[0]["lr"]
metric_logger.update(lr=lr)
# 只有在计算了 grad_norm 的步骤才更新它
if grad_norm is not None:
metric_logger.update(grad_norm=grad_norm.item() if hasattr(grad_norm, 'item') else grad_norm)
metric_logger.update(grad_norm=grad_norm.item(
) if hasattr(grad_norm, 'item') else grad_norm)
# --- [核心修改] 可视化逻辑,现在调用三个可视化函数 ---
if misc.is_main_process() and (data_iter_step % vis_freq == 0):
# 1. [新增] 可视化 CWT 与 1D 信号的配对关系
save_cwt_signal_pair_visualization(
original_signal=samples_1d[0], # 这是原始的1D信号
original_signal=samples_1d[0], # 这是原始的1D信号
cwt_image=samples_cwt[0], # 这是原始的CWT图像
save_path=vis_save_path,
epoch=epoch,
@@ -307,7 +332,7 @@ def train_one_epoch(model: torch.nn.Module,
metric_logger.update(loss=loss_value)
lr = optimizer.param_groups[0]["lr"]
metric_logger.update(lr=lr)
metric_logger.synchronize_between_processes()
print("Averaged stats:", metric_logger)
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
return {k: meter.global_avg for k, meter in metric_logger.meters.items()}
@@ -3,6 +3,7 @@ import argparse
import pandas as pd
import os
def analyze_and_save_to_csv(json_file_path, output_csv_path):
"""
读取预测JSON文件,计算统计数据(不含平均值),并将结果保存到CSV文件。
@@ -29,7 +30,7 @@ def analyze_and_save_to_csv(json_file_path, output_csv_path):
# 2. 遍历每个样本 (uid) 并计算统计数据
analysis_results = []
prob1_idx = 0
prob2_idx = 1
@@ -51,12 +52,12 @@ def analyze_and_save_to_csv(json_file_path, output_csv_path):
all_probabilities = [p['probabilities'] for p in predictions]
df_probs = pd.DataFrame(all_probabilities)
# 计算统计指标 (最大值和最小值)
num_samples = len(df_probs)
max_prob1 = df_probs[prob1_idx].max()
min_prob1 = df_probs[prob1_idx].min()
max_prob2 = df_probs[prob2_idx].max()
min_prob2 = df_probs[prob2_idx].min()
@@ -77,15 +78,15 @@ def analyze_and_save_to_csv(json_file_path, output_csv_path):
return
final_df = pd.DataFrame(analysis_results)
# 定义最终CSV文件的列顺序
column_order = [
'UID', 'Sample数量',
'UID', 'Sample数量',
'概率1最大值', '概率1最小值',
'概率2最大值', '概率2最小值'
]
final_df = final_df[column_order]
try:
# 将DataFrame写入CSV文件
# index=False 表示不将DataFrame的行索引写入文件
@@ -98,18 +99,20 @@ def analyze_and_save_to_csv(json_file_path, output_csv_path):
def get_args_parser():
"""设置命令行参数解析器。"""
parser = argparse.ArgumentParser(description='Analyze prediction JSON and save statistics to a CSV file.')
parser.add_argument('--input_file', required=True, type=str,
parser = argparse.ArgumentParser(
description='Analyze prediction JSON and save statistics to a CSV file.')
parser.add_argument('--input_file', required=True, type=str,
help='Path to the input JSON file with prediction results.')
# 新增一个可选的输出文件参数
parser.add_argument('--output_file', type=str,
parser.add_argument('--output_file', type=str,
help='(Optional) Path to save the output CSV file. '
'If not provided, it will be saved next to the input file.')
return parser
if __name__ == '__main__':
args = get_args_parser().parse_args()
# 决定输出文件的路径
if args.output_file:
# 如果用户指定了输出路径,则使用它
@@ -118,5 +121,5 @@ if __name__ == '__main__':
# 如果用户未指定,则根据输入文件名自动生成
base_name, _ = os.path.splitext(args.input_file)
output_path = f"{base_name}_analysis.csv"
analyze_and_save_to_csv(args.input_file, output_path)
analyze_and_save_to_csv(args.input_file, output_path)
+70 -42
View File
@@ -4,6 +4,7 @@ import pickle
import numpy as np
from tqdm import tqdm
def check_pkl_file_integrity(filepath):
"""
Checks a single .pkl file for format and data integrity.
@@ -16,14 +17,15 @@ def check_pkl_file_integrity(filepath):
"""
errors = []
warnings = []
data_has_inf = False # Flag to indicate if 'data' contains Inf values
data_has_inf = False # Flag to indicate if 'data' contains Inf values
try:
with open(filepath, 'rb') as f:
data_dict = pickle.load(f)
except Exception as e:
errors.append(f"Failed to load pickle file: {e}")
return errors, warnings, data_has_inf # Return False for data_has_inf on load failure
# Return False for data_has_inf on load failure
return errors, warnings, data_has_inf
# 1. Check top-level keys
expected_keys = {"uid", "data", "sampling_rate", "label"}
@@ -39,39 +41,46 @@ def check_pkl_file_integrity(filepath):
# 2. Check 'uid'
if "uid" in data_dict:
if not isinstance(data_dict["uid"], str):
errors.append(f"'uid' is not a string (type: {type(data_dict['uid'])}). Value: {data_dict['uid']}")
errors.append(
f"'uid' is not a string (type: {type(data_dict['uid'])}). Value: {data_dict['uid']}")
# No 'else' needed here as missing key is caught above
# 3. Check 'data'
if "data" in data_dict:
sensor_data = data_dict["data"]
if not isinstance(sensor_data, np.ndarray):
errors.append(f"'data' is not a numpy.ndarray (type: {type(sensor_data)}).")
errors.append(
f"'data' is not a numpy.ndarray (type: {type(sensor_data)}).")
else:
if sensor_data.dtype != np.float16:
warnings.append(f"'data' dtype is {sensor_data.dtype}, expected np.float16.")
warnings.append(
f"'data' dtype is {sensor_data.dtype}, expected np.float16.")
if sensor_data.ndim != 2:
errors.append(f"'data' has {sensor_data.ndim} dimensions, expected 2. Shape: {sensor_data.shape}")
errors.append(
f"'data' has {sensor_data.ndim} dimensions, expected 2. Shape: {sensor_data.shape}")
else:
num_channels, sequence_length = sensor_data.shape
if num_channels == 0: errors.append("'data' has 0 channels.")
if sequence_length == 0: errors.append("'data' has 0 sequence length.")
if num_channels == 0:
errors.append("'data' has 0 channels.")
if sequence_length == 0:
errors.append("'data' has 0 sequence length.")
if np.isnan(sensor_data).any():
nan_count = np.isnan(sensor_data).sum()
errors.append(f"'data' contains {nan_count} NaN values.")
if np.isinf(sensor_data).any():
inf_count = np.isinf(sensor_data).sum()
errors.append(f"'data' contains {inf_count} Inf values.")
data_has_inf = True # Set the flag
data_has_inf = True # Set the flag
# No 'else' needed here
# 4. Check 'sampling_rate'
if "sampling_rate" in data_dict:
sr = data_dict["sampling_rate"]
if not isinstance(sr, (int, float)):
errors.append(f"'sampling_rate' is not a number (type: {type(sr)}). Value: {sr}")
errors.append(
f"'sampling_rate' is not a number (type: {type(sr)}). Value: {sr}")
elif sr <= 0:
errors.append(f"'sampling_rate' is not positive. Value: {sr}")
# No 'else' needed here
@@ -82,30 +91,38 @@ def check_pkl_file_integrity(filepath):
if not isinstance(labels, list):
errors.append(f"'label' is not a list (type: {type(labels)}).")
else:
if not labels: warnings.append("'label' list is empty.")
if not labels:
warnings.append("'label' list is empty.")
for i, label_item in enumerate(labels):
if not isinstance(label_item, dict):
errors.append(f"Item {i} in 'label' list is not a dict (type: {type(label_item)}).")
errors.append(
f"Item {i} in 'label' list is not a dict (type: {type(label_item)}).")
continue
if len(label_item) != 1:
errors.append(f"Item {i} in 'label' dict does not have exactly one key. Keys: {list(label_item.keys())}")
errors.append(
f"Item {i} in 'label' dict does not have exactly one key. Keys: {list(label_item.keys())}")
continue
task_type, label_value = list(label_item.items())[0]
if task_type not in ["class", "reg"]:
errors.append(f"Item {i} in 'label' dict has invalid task type '{task_type}'.")
errors.append(
f"Item {i} in 'label' dict has invalid task type '{task_type}'.")
if task_type == "class" and not isinstance(label_value, (int, np.integer)):
warnings.append(f"Label for 'class' task (item {i}) is not an integer. Value: {label_value}")
warnings.append(
f"Label for 'class' task (item {i}) is not an integer. Value: {label_value}")
elif task_type == "reg" and not isinstance(label_value, (int, float, np.number)):
warnings.append(f"Label for 'reg' task (item {i}) is not a number. Value: {label_value}")
warnings.append(
f"Label for 'reg' task (item {i}) is not a number. Value: {label_value}")
if label_value is None:
errors.append(f"Label value for task '{task_type}' (item {i}) is None.")
errors.append(
f"Label value for task '{task_type}' (item {i}) is None.")
# No 'else' needed here
return errors, warnings, data_has_inf
def main():
target_directory = input("Enter the directory containing .pkl files: ")
@@ -114,10 +131,12 @@ def main():
return
# --- 新增:确认是否删除文件 ---
confirm_delete = input("Do you want to DELETE files where 'data' contains Inf values? (yes/no): ").strip().lower()
confirm_delete = input(
"Do you want to DELETE files where 'data' contains Inf values? (yes/no): ").strip().lower()
if confirm_delete == 'yes':
print("\n!!! WARNING: Files with Inf values in 'data' will be PERMANENTLY DELETED. !!!")
final_confirm = input("Are you absolutely sure? This cannot be undone. (yes/no): ").strip().lower()
final_confirm = input(
"Are you absolutely sure? This cannot be undone. (yes/no): ").strip().lower()
if final_confirm != 'yes':
print("Deletion cancelled by user.")
confirm_delete = 'no'
@@ -126,25 +145,29 @@ def main():
# --- 结束新增 ---
print(f"\nScanning directory: {target_directory}")
pkl_files = [os.path.join(target_directory, f) for f in os.listdir(target_directory) if f.endswith(".pkl")]
pkl_files = [os.path.join(target_directory, f) for f in os.listdir(
target_directory) if f.endswith(".pkl")]
if not pkl_files:
print("No .pkl files found in the directory.")
return
all_files_ok_initially = True # Tracks if any file had issues before potential deletion
# Tracks if any file had issues before potential deletion
all_files_ok_initially = True
total_errors = 0
total_warnings = 0
files_deleted_count = 0
deleted_files_log = []
for pkl_file_path in tqdm(pkl_files, desc="Checking files"):
errors, warnings, data_has_inf = check_pkl_file_integrity(pkl_file_path)
errors, warnings, data_has_inf = check_pkl_file_integrity(
pkl_file_path)
if errors or warnings:
all_files_ok_initially = False
print(f"\n--- Issues found in: {os.path.basename(pkl_file_path)} ---")
print(
f"\n--- Issues found in: {os.path.basename(pkl_file_path)} ---")
if errors:
total_errors += len(errors)
print(" Errors:")
@@ -155,36 +178,41 @@ def main():
print(" Warnings:")
for warn in warnings:
print(f" - {warn}")
# --- 新增:删除逻辑 ---
if data_has_inf and confirm_delete == 'yes':
try:
os.remove(pkl_file_path)
print(f" DELETED file: {os.path.basename(pkl_file_path)} due to Inf values in 'data'.")
print(
f" DELETED file: {os.path.basename(pkl_file_path)} due to Inf values in 'data'.")
files_deleted_count += 1
deleted_files_log.append(os.path.basename(pkl_file_path))
except OSError as e:
print(f" ERROR: Could not delete file {os.path.basename(pkl_file_path)}: {e}")
print(
f" ERROR: Could not delete file {os.path.basename(pkl_file_path)}: {e}")
# --- 结束新增 ---
print("\n--- Scan Complete ---")
if all_files_ok_initially and files_deleted_count == 0:
print("All .pkl files seem to be in the correct format and have no NaN/Inf in 'data'.")
print(
"All .pkl files seem to be in the correct format and have no NaN/Inf in 'data'.")
else:
print(f"Initial scan found {total_errors} error(s) and {total_warnings} warning(s).")
print(
f"Initial scan found {total_errors} error(s) and {total_warnings} warning(s).")
if files_deleted_count > 0:
print(f"\nSuccessfully deleted {files_deleted_count} file(s) containing Inf values in 'data':")
print(
f"\nSuccessfully deleted {files_deleted_count} file(s) containing Inf values in 'data':")
for fname in deleted_files_log:
print(f" - {fname}")
elif confirm_delete == 'yes':
print("\nNo files were deleted (either no Inf values found or deletion was cancelled).")
if not all_files_ok_initially and files_deleted_count < total_errors and confirm_delete == 'yes': # Check if other errors remain
if not all_files_ok_initially and files_deleted_count < total_errors and confirm_delete == 'yes': # Check if other errors remain
print("\nNote: Some files with other errors (not Inf in data) might still exist.")
elif not all_files_ok_initially and confirm_delete != 'yes':
print("\nPlease review the messages above for files with issues.")
print("\nPlease review the messages above for files with issues.")
if __name__ == "__main__":
main()
main()
+9 -8
View File
@@ -3,6 +3,7 @@ import argparse
import os
from pprint import pprint
def inspect_checkpoint(checkpoint_path):
"""
加载一个PyTorch检查点文件并打印其中保存的args(训练参数)。
@@ -26,11 +27,11 @@ def inspect_checkpoint(checkpoint_path):
# 3. 检查 'args' 键是否存在
if 'args' in checkpoint:
print("\n成功找到已保存的训练参数 (args):")
# 4. 获取args对象并打印
# args对象可能是一个argparse.Namespace对象,也可能是一个字典
args = checkpoint['args']
if isinstance(args, argparse.Namespace):
# 如果是Namespace对象,转换为字典以便更好地打印
args_dict = vars(args)
@@ -40,7 +41,7 @@ def inspect_checkpoint(checkpoint_path):
# 使用pprint进行格式化打印,使其更易读
pprint(args_dict)
else:
print("\n错误: 在此检查点文件中未找到 'args' 键。")
print("这可能是一个旧版本的检查点,或者保存时未包含训练参数。")
@@ -52,7 +53,7 @@ def inspect_checkpoint(checkpoint_path):
if 'model' in checkpoint:
num_keys = len(checkpoint['model'].keys())
print(f"模型状态字典 ('model') 包含 {num_keys} 个参数。")
print("-" * (len(checkpoint_path) + 24))
@@ -62,11 +63,11 @@ if __name__ == "__main__":
description="一个用于检查PyTorch检查点文件中保存的训练参数的工具。"
)
parser.add_argument(
"checkpoint_path",
type=str,
"checkpoint_path",
type=str,
help="需要检查的.pth检查点文件的路径。"
)
args = parser.parse_args()
inspect_checkpoint(args.checkpoint_path)
inspect_checkpoint(args.checkpoint_path)
+34 -15
View File
@@ -1,4 +1,4 @@
#this file is used to combining ppg and ecg signal file
# this file is used to combining ppg and ecg signal file
import os
import pickle
import numpy as np
@@ -18,7 +18,7 @@ OUTPUT_FOLDER = r'/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/dat
TIMESTAMP_LIMIT: Optional[int] = None
CHUNK_SIZE = 20
# 保持较低的进程数以避免内存问题
NUM_PROCESSES: Optional[int] = 2
NUM_PROCESSES: Optional[int] = 2
WORKER_CACHE_SIZE = 10
TIMESTAMP_KEY = 'timestamp'
@@ -27,9 +27,12 @@ DATA_KEY = 'data'
# --- 全局变量 (无变化) ---
worker_index1: Optional[Dict[Any, Tuple[str, int]]] = None
worker_index2: Optional[Dict[Any, Tuple[str, int]]] = None
_worker_file_cache: Optional[collections.OrderedDict[str, List[Dict[str, Any]]]] = None
_worker_file_cache: Optional[collections.OrderedDict[str,
List[Dict[str, Any]]]] = None
# --- 索引构建、读取Timestamp、降采样、Worker初始化、缓存加载函数 (均无变化) ---
def build_timestamp_index(folder_path: str, description: str) -> Dict[Any, Tuple[str, int]]:
timestamp_index: Dict[Any, Tuple[str, int]] = {}
if not os.path.isdir(folder_path):
@@ -51,6 +54,7 @@ def build_timestamp_index(folder_path: str, description: str) -> Dict[Any, Tuple
print(f"索引构建处理文件 {file_path} 时发生错误:{e}", file=sys.stderr)
return timestamp_index
def read_common_timestamps(file_path: str) -> List[Any]:
common_timestamps: List[Any] = []
if not os.path.exists(file_path):
@@ -67,6 +71,7 @@ def read_common_timestamps(file_path: str) -> List[Any]:
print(f"读取共有的 timestamp 文件时发生错误:{e}", file=sys.stderr)
return common_timestamps
def downsample_multidim(data: np.ndarray, target_length: int, axis: int = 0) -> np.ndarray:
current_length = data.shape[axis]
if current_length == target_length:
@@ -76,30 +81,37 @@ def downsample_multidim(data: np.ndarray, target_length: int, axis: int = 0) ->
indices = np.linspace(0, current_length - 1, target_length, dtype=int)
return np.take(data, indices, axis=axis)
def worker_init(idx1: Dict[Any, Tuple[str, int]], idx2: Dict[Any, Tuple[str, int]]):
global worker_index1, worker_index2, _worker_file_cache
worker_index1 = idx1
worker_index2 = idx2
_worker_file_cache = collections.OrderedDict()
def load_data_from_file_cached(file_path: str) -> Optional[List[Dict[str, Any]]]:
global _worker_file_cache, WORKER_CACHE_SIZE
if _worker_file_cache is None: return None
if _worker_file_cache is None:
return None
if file_path in _worker_file_cache:
data_list = _worker_file_cache.pop(file_path)
_worker_file_cache[file_path] = data_list
return data_list
else:
try:
with open(file_path, 'rb') as f: data_list = pickle.load(f)
with open(file_path, 'rb') as f:
data_list = pickle.load(f)
_worker_file_cache[file_path] = data_list
if len(_worker_file_cache) > WORKER_CACHE_SIZE: _worker_file_cache.popitem(last=False)
if len(_worker_file_cache) > WORKER_CACHE_SIZE:
_worker_file_cache.popitem(last=False)
return data_list
except Exception as e:
print(f"Worker缓存加载失败 {file_path}: {e}", file=sys.stderr)
return None
# --- 核心处理函数 (已修改) ---
def process_single_timestamp(ts: Any) -> Optional[Dict[str, Any]]:
global worker_index1, worker_index2
@@ -141,15 +153,16 @@ def process_single_timestamp(ts: Any) -> Optional[Dict[str, Any]]:
# 现在可以安全地假设 ppg_acc_data 的形状是 (length, 4)
ecg_len = len(ecg_data)
ppg_acc_len = ppg_acc_data.shape[0]
target_length = min(ecg_len, ppg_acc_len)
if ecg_len > target_length:
ecg_data = downsample_multidim(ecg_data, target_length, axis=0)
if ppg_acc_len > target_length:
# 降采样是沿着 axis=0 (长度维度) 进行的
ppg_acc_data = downsample_multidim(ppg_acc_data, target_length, axis=0)
ppg_acc_data = downsample_multidim(
ppg_acc_data, target_length, axis=0)
# 分离 PPG 和 ACC (现在这个切片逻辑是安全的)
ppg = ppg_acc_data[:, 0] # 第1列是PPG
@@ -163,15 +176,17 @@ def process_single_timestamp(ts: Any) -> Optional[Dict[str, Any]]:
acc[:, 0].astype(np.float32), # 形状: (target_length,)
acc[:, 1].astype(np.float32), # 形状: (target_length,)
acc[:, 2].astype(np.float32) # 形状: (target_length,)
], axis=0) # axis=0 使它们成为行,最终形状 (5, target_length)
], axis=0) # axis=0 使它们成为行,最终形状 (5, target_length)
return {TIMESTAMP_KEY: ts, DATA_KEY: combined}
except Exception as e:
print(f"处理 {ts} 时发生错误 (文件: {file1_path}, {file2_path}): {e}", file=sys.stderr)
print(f"处理 {ts} 时发生错误 (文件: {file1_path}, {file2_path}): {e}",
file=sys.stderr)
traceback.print_exc()
return None
# --- 主程序 (无变化) ---
if __name__ == '__main__':
print("--- 开始处理 (使用降采样,自动修正数据方向) ---")
@@ -202,7 +217,8 @@ if __name__ == '__main__':
initializer=worker_init,
initargs=(index1, index2)
) as executor:
futures = {executor.submit(process_single_timestamp, ts): ts for ts in valid_ts}
futures = {executor.submit(
process_single_timestamp, ts): ts for ts in valid_ts}
for future in tqdm(concurrent.futures.as_completed(futures), total=len(valid_ts), desc="处理中"):
ts = futures[future]
@@ -211,12 +227,14 @@ if __name__ == '__main__':
if result:
# 验证一下输出形状 (可选,但有助于调试)
if result[DATA_KEY].shape[0] != 5:
print(f"警告:时间戳 {ts} 的输出形状不正确: {result[DATA_KEY].shape}", file=sys.stderr)
print(
f"警告:时间戳 {ts} 的输出形状不正确: {result[DATA_KEY].shape}", file=sys.stderr)
continue
chunk.append(result)
processed += 1
if len(chunk) >= CHUNK_SIZE:
output_path = os.path.join(OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
output_path = os.path.join(
OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
with open(output_path, 'wb') as f:
pickle.dump(chunk, f)
chunk = []
@@ -227,7 +245,8 @@ if __name__ == '__main__':
print("\n错误:进程池已损坏。通常是由于内存不足。请尝试将 NUM_PROCESSES 减小到 1。", file=sys.stderr)
if chunk:
output_path = os.path.join(OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
output_path = os.path.join(
OUTPUT_FOLDER, f"{OUTPUT_BASE_NAME}_part{chunk_num:03d}.pkl")
with open(output_path, 'wb') as f:
pickle.dump(chunk, f)
+35 -26
View File
@@ -4,29 +4,32 @@ import argparse
from tqdm import tqdm
import numpy as np
def get_args_parser():
"""
解析命令行参数。
"""
parser = argparse.ArgumentParser('Finetune Data Preprocessing Script', add_help=False)
parser = argparse.ArgumentParser(
'Finetune Data Preprocessing Script', add_help=False)
parser.add_argument('--input_dir', required=True, type=str,
help='Path to the directory containing the original .pkl sample files (e.g., sample_for_downstream).')
parser.add_argument('--output_dir', required=True, type=str,
help='Path to the directory where the processed .pkl files will be saved.')
parser.add_argument('--target_len', type=int, default=387,
help='The target sequence length to pad or truncate to.')
parser.add_argument('--pad_mode', type=str, default='zero', choices=['zero', 'reflect', 'edge'],
help="Padding mode. 'zero' for zero-padding, 'reflect' for reflection, 'edge' for edge value replication.")
parser.add_argument('--pad_location', type=str, default='front', choices=['front', 'back'],
help="Location to add padding. 'front' pads at the beginning, 'back' pads at the end.")
return parser
def process_file(input_path, output_path, target_len, pad_mode, pad_location):
"""
加载单个.pkl文件,处理其内部'data'字段的长度,并保存到新位置。
@@ -35,18 +38,18 @@ def process_file(input_path, output_path, target_len, pad_mode, pad_location):
# 1. 加载原始数据
with open(input_path, 'rb') as f:
data_dict = pickle.load(f)
# 确保'data'字段存在
if 'data' not in data_dict:
print(f"Warning: 'data' key not found in {input_path}. Skipping.")
return
signal = data_dict['data']
# 确保数据是numpy数组
if not isinstance(signal, np.ndarray):
signal = np.array(signal)
# 确保数据是二维的 [n_vars, length]
if signal.ndim == 1:
signal = np.expand_dims(signal, axis=0)
@@ -60,46 +63,49 @@ def process_file(input_path, output_path, target_len, pad_mode, pad_location):
elif current_len > target_len:
# 长度过长,从末尾裁剪
processed_signal = signal[:, -target_len:]
else: # current_len < target_len
else: # current_len < target_len
# 长度过短,进行填充
pad_size = target_len - current_len
n_vars = signal.shape[0]
if pad_mode == 'zero':
pad_values = np.zeros((n_vars, pad_size), dtype=signal.dtype)
elif pad_mode == 'edge':
# 复制边缘值
if pad_location == 'front':
edge_values = signal[:, 0:1] # 取第一个时间点的值
else: # back
edge_values = signal[:, -1:] # 取最后一个时间点的值
edge_values = signal[:, 0:1] # 取第一个时间点的值
else: # back
edge_values = signal[:, -1:] # 取最后一个时间点的值
pad_values = np.repeat(edge_values, pad_size, axis=1)
elif pad_mode == 'reflect':
# 反射填充是一种更平滑的方式,但实现稍复杂
# 这里我们使用numpy内置的pad函数
if pad_location == 'front':
pad_width = ((0, 0), (pad_size, 0)) # 只在前面填充
else: # back
pad_width = ((0, 0), (0, pad_size)) # 只在后面填充
pad_width = ((0, 0), (pad_size, 0)) # 只在前面填充
else: # back
pad_width = ((0, 0), (0, pad_size)) # 只在后面填充
processed_signal = np.pad(signal, pad_width, mode='reflect')
# np.pad会返回完整数组,所以我们直接进入下一步
# 对于非'reflect'模式,手动拼接
if pad_mode != 'reflect':
if pad_location == 'front':
processed_signal = np.concatenate([pad_values, signal], axis=1)
else: # back
processed_signal = np.concatenate([signal, pad_values], axis=1)
processed_signal = np.concatenate(
[pad_values, signal], axis=1)
else: # back
processed_signal = np.concatenate(
[signal, pad_values], axis=1)
# 3. 更新字典并保存
data_dict['data'] = processed_signal
with open(output_path, 'wb') as f:
pickle.dump(data_dict, f)
except Exception as e:
print(f"Error processing file {input_path}: {e}")
def main(args):
"""
主执行函数。
@@ -117,7 +123,8 @@ def main(args):
# 2. 获取所有输入文件
try:
file_list = [f for f in os.listdir(args.input_dir) if f.endswith('.pkl')]
file_list = [f for f in os.listdir(
args.input_dir) if f.endswith('.pkl')]
if not file_list:
print(f"Error: No .pkl files found in {args.input_dir}")
return
@@ -130,13 +137,15 @@ def main(args):
for filename in tqdm(file_list, desc="Processing files"):
input_path = os.path.join(args.input_dir, filename)
output_path = os.path.join(args.output_dir, filename)
process_file(input_path, output_path, args.target_len, args.pad_mode, args.pad_location)
process_file(input_path, output_path, args.target_len,
args.pad_mode, args.pad_location)
print("-" * 40)
print("Preprocessing finished successfully!")
print(f"Processed data saved to: {args.output_dir}")
if __name__ == '__main__':
args = get_args_parser().parse_args()
main(args)
main(args)
+70 -47
View File
@@ -20,8 +20,8 @@ RAW_DATA_FOLDERS = ['/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/
# 【修改】: 移除 TRAIN_LABELS_TO_KEEP,因为现在是基于二分类标签来选择
# 【修改】: 移除 NUM_TRAIN_SAMPLES 和 NUM_TEST_SAMPLES,替换为新的控制参数
# 【新增】: 控制最终训练集和测试集的总样本数(基于原始文件)
TOTAL_TRAIN_SAMPLES = 20000 # 训练集总样本数
TOTAL_TEST_SAMPLES = 8000 # 测试集总样本数
TOTAL_TRAIN_SAMPLES = 20000 # 训练集总样本数
TOTAL_TEST_SAMPLES = 8000 # 测试集总样本数
# 【新增】: 控制最终训练集和测试集中的患病率(正样本比例)
# 例如,0.05 表示 5% 的患病率
@@ -41,13 +41,15 @@ OVERLAP_RATIO = 0.5
# --- D. 输出路径配置 ---
OUTPUT_BASE_PATH = "/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/"
OUTPUT_DATASET_NAME = "ppg2e4" # 建议用新名字以区分
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文件,提取标签并进行二分类转换。
@@ -56,13 +58,13 @@ def process_file(file_path):
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
@@ -71,7 +73,7 @@ def process_file(file_path):
elif original_label == CONTROL_GROUP_LABEL:
binary_label = 0
else:
return None # 忽略不相关的标签
return None # 忽略不相关的标签
return {
'name': os.path.basename(file_path),
@@ -82,6 +84,8 @@ def process_file(file_path):
except Exception:
# 在并行处理中,静默处理单个文件的错误,避免整个程序崩溃
return None
def get_class_label(file_path):
"""辅助函数:读取pkl文件并返回其'class'标签。"""
try:
@@ -96,12 +100,14 @@ def get_class_label(file_path):
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...")
@@ -113,7 +119,7 @@ def create_initial_split():
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.")
@@ -126,65 +132,72 @@ def create_initial_split():
# executor.map 会将 all_file_paths 中的每个路径传递给 process_file 函数
# 它会自动管理线程,并以与输入相同的顺序返回结果
# tqdm(..., total=...) 用于创建一个美观的进度条
results = list(tqdm(executor.map(process_file, all_file_paths),
total=len(all_file_paths),
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.")
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).")
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.")
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.")
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}")
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. 依次为训练集和测试集抽样
@@ -192,7 +205,7 @@ def create_initial_split():
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"
@@ -206,8 +219,9 @@ def create_initial_split():
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"\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
@@ -224,12 +238,15 @@ def segment_and_finalize_dataset(initial_split_file):
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)
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}")
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)
@@ -242,7 +259,7 @@ def segment_and_finalize_dataset(initial_split_file):
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
@@ -251,26 +268,28 @@ def segment_and_finalize_dataset(initial_split_file):
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]
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)
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:
@@ -280,10 +299,13 @@ def segment_and_finalize_dataset(initial_split_file):
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")
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")
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}")
@@ -292,6 +314,7 @@ def segment_and_finalize_dataset(initial_split_file):
# --- 4. MAIN EXECUTION BLOCK (保持不变) ---
# ==============================================================================
if __name__ == "__main__":
try:
temp_split_file = create_initial_split()
@@ -299,6 +322,6 @@ if __name__ == "__main__":
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}")
+71 -50
View File
@@ -19,9 +19,11 @@ from torch.utils.data import DataLoader, DistributedSampler, RandomSampler
# --------------------------------------------------------------------------
# 主函数和辅助函数
# --------------------------------------------------------------------------
def get_args_parser():
parser = argparse.ArgumentParser('NormWear LR Finder', add_help=False)
# --- 核心参数 ---
parser.add_argument('--resume', type=str, default='',
help='Path to the checkpoint file to resume from (e.g., after warmup).')
@@ -29,19 +31,25 @@ def get_args_parser():
help='Path to save the LR finder plot.')
# --- LR Finder 参数 ---
parser.add_argument('--start_lr', default=1e-7, type=float, help='Starting learning rate for the test.')
parser.add_argument('--end_lr', default=1e-1, type=float, help='Ending learning rate for the test.')
parser.add_argument('--num_iter', default=200, type=int, help='Number of iterations (batches) to run the test.')
parser.add_argument('--start_lr', default=1e-7, type=float,
help='Starting learning rate for the test.')
parser.add_argument('--end_lr', default=1e-1, type=float,
help='Ending learning rate for the test.')
parser.add_argument('--num_iter', default=200, type=int,
help='Number of iterations (batches) to run the test.')
# --- 数据集参数 (必须与训练时一致) ---
parser.add_argument('--data_dir', required=True, type=str, help='Path to the pre-training data directory.')
parser.add_argument('--dataset_names', nargs='+', default=['temp'], help='List of dataset names.')
parser.add_argument('--data_dir', required=True, type=str,
help='Path to the pre-training data directory.')
parser.add_argument('--dataset_names', nargs='+',
default=['temp'], help='List of dataset names.')
parser.add_argument('--window_size', default=387, type=int)
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--num_workers', default=4, type=int)
# --- 模型架构参数 (必须与检查点中的模型一致) ---
parser.add_argument('--n_vars', type=int, required=True, help='Number of variables in the data.')
parser.add_argument('--n_vars', type=int, required=True,
help='Number of variables in the data.')
parser.add_argument('--embed_dim', type=int, default=768)
parser.add_argument('--depth', type=int, default=12)
parser.add_argument('--num_heads', type=int, default=12)
@@ -49,34 +57,39 @@ def get_args_parser():
parser.add_argument('--decoder_depth', type=int, default=8)
parser.add_argument('--decoder_num_heads', type=int, default=16)
parser.add_argument('--mask_ratio', type=float, default=0.75)
#training args
# training args
# --- 分布式训练参数 (可选,但推荐) ---
parser.add_argument('--device', default='cuda', help='Device to use for training / testing.')
parser.add_argument('--world_size', default=1, type=int, help='Number of distributed processes.')
parser.add_argument('--local_rank', default=-1, type=int) # torchrun会自动设置
parser.add_argument('--dist_on_itp', action='store_true', help='Whether to use itp for distributed training.')
parser.add_argument('--dist_url', default='env://', help='URL used to set up distributed training.')
parser.add_argument('--device', default='cuda',
help='Device to use for training / testing.')
parser.add_argument('--world_size', default=1, type=int,
help='Number of distributed processes.')
parser.add_argument('--local_rank', default=-1, type=int) # torchrun会自动设置
parser.add_argument('--dist_on_itp', action='store_true',
help='Whether to use itp for distributed training.')
parser.add_argument('--dist_url', default='env://',
help='URL used to set up distributed training.')
return parser
def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
"""
执行学习率范围测试。
"""
model.train()
gamma = (args.end_lr / args.start_lr) ** (1 / args.num_iter)
lr_scheduler = optim.lr_scheduler.ExponentialLR(optimizer, gamma)
for param_group in optimizer.param_groups:
param_group['lr'] = args.start_lr
losses = []
learning_rates = []
data_iter = iter(data_loader)
print(f"--- Starting LR Finder for {args.num_iter} iterations ---")
for i in tqdm(range(args.num_iter), disable=misc.get_rank() != 0):
try:
batch = next(data_iter)
@@ -88,20 +101,21 @@ def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
samples_1d = batch['input_1d'].to(device, non_blocking=True)
optimizer.zero_grad()
with autocast(dtype=dtype):
loss, _, _ = model(x_cwt=samples_cwt, x_1d=samples_1d, mask_ratio=args.mask_ratio)
loss, _, _ = model(x_cwt=samples_cwt,
x_1d=samples_1d, mask_ratio=args.mask_ratio)
current_lr = optimizer.param_groups[0]['lr']
learning_rates.append(current_lr)
loss_item = loss.item()
if i == 0:
losses.append(loss_item)
else:
smoothed_loss = 0.98 * losses[-1] + 0.02 * loss_item
losses.append(smoothed_loss)
if loss_item > 4 * (min(losses) if losses else 1.0) and i > 10:
print("Loss diverged, stopping LR Finder.")
break
@@ -109,16 +123,16 @@ def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
if loss_scaler is not None:
# 将所有操作合并为一次调用
loss_scaler(
loss,
optimizer,
loss,
optimizer,
parameters=model.parameters(),
# 在LR Finder中,我们每个step都更新梯度
update_grad=True
update_grad=True
)
else:
loss.backward()
optimizer.step()
lr_scheduler.step()
# 只在主进程上绘图和分析
@@ -130,36 +144,38 @@ def find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype):
plt.ylabel("Smoothed Loss")
plt.title("Learning Rate Finder")
plt.grid(True)
os.makedirs(args.output_dir, exist_ok=True)
save_path = os.path.join(args.output_dir, "lr_finder_plot.png")
plt.savefig(save_path)
print(f"\nLR Finder plot saved to: {save_path}")
if len(losses) > 10: # 确保有足够的数据点进行分析
if len(losses) > 10: # 确保有足够的数据点进行分析
rates = np.array(learning_rates)
losses_arr = np.array(losses)
# 找到损失最低点
min_loss_idx = np.argmin(losses_arr)
min_loss_lr = rates[min_loss_idx]
# 找到梯度最陡峭的点 (一个常用的启发式方法)
# 我们通常选择比最低点小一个数量级的学习率
recommended_lr = min_loss_lr / 10
print(f"\n--- LR Finder Results ---")
print(f"Lowest loss found at LR: {min_loss_lr:.2e}")
print(f"Recommended LR for subsequent training (rule of thumb): {recommended_lr:.2e}")
print(
f"Recommended LR for subsequent training (rule of thumb): {recommended_lr:.2e}")
print("-------------------------")
print("Please inspect the plot to make a final decision.")
# in find_lr.py
def main(args):
misc.init_distributed_mode(args)
device = torch.device(args.device)
# --- 数据集 (不变) ---
dataset = PretrainDataset(
data_dir=args.data_dir,
@@ -170,7 +186,7 @@ def main(args):
sampler = DistributedSampler(dataset, shuffle=True)
else:
sampler = RandomSampler(dataset)
data_loader = DataLoader(
dataset,
sampler=sampler,
@@ -196,14 +212,16 @@ def main(args):
nvar=args.n_vars,
target_len=args.window_size
).to(device)
model_without_ddp = model
if misc.is_dist_avail_and_initialized():
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.gpu])
model_without_ddp = model.module
# --- 优化器和AMP (不变) ---
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.start_lr)
optimizer = torch.optim.AdamW(
model_without_ddp.parameters(), lr=args.start_lr)
loss_scaler = NativeScaler()
# --- [核心修复] 整合并简化检查点加载逻辑 ---
@@ -211,25 +229,28 @@ def main(args):
if args.resume and os.path.isfile(args.resume):
print(f"Resuming from checkpoint: {args.resume}")
checkpoint = torch.load(args.resume, map_location='cpu')
# 从检查点中加载模型权重
if 'model' in checkpoint:
state_dict = checkpoint['model']
else:
state_dict = checkpoint # 兼容只保存了state_dict的情况
state_dict = checkpoint # 兼容只保存了state_dict的情况
msg = model_without_ddp.load_state_dict(state_dict, strict=False)
print("Model loading message:", msg)
else:
if args.resume: # 如果提供了路径但文件不存在
print(f"Warning: Checkpoint file not found at '{args.resume}'. Starting from scratch.")
else: # 如果没有提供路径
print("No checkpoint provided. Starting LR Finder from scratch (random initialization).")
if args.resume: # 如果提供了路径但文件不存在
print(
f"Warning: Checkpoint file not found at '{args.resume}'. Starting from scratch.")
else: # 如果没有提供路径
print(
"No checkpoint provided. Starting LR Finder from scratch (random initialization).")
# --- 执行LR Finder ---
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
find_lr(model, data_loader, optimizer, loss_scaler, device, args, dtype)
if __name__ == '__main__':
args = get_args_parser().parse_args()
main(args)
main(args)
+67 -43
View File
@@ -27,14 +27,14 @@ 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_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
FINETUNE_SUBJECT_FRACTION = 0.25
# 用于保证抽样可复现的随机种子
RANDOM_STATE = 42
@@ -44,6 +44,8 @@ RANDOM_STATE = 42
# ==============================================================================
# process_and_segment_file 函数保持不变,因为它处理的是单个文件
def process_and_segment_file(file_path):
# ... (此函数与上一版本完全相同) ...
try:
@@ -58,7 +60,7 @@ def process_and_segment_file(file_path):
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:
@@ -71,47 +73,54 @@ def process_and_segment_file(file_path):
return []
stride = int(TARGET_LENGTH * (1 - OVERLAP_RATIO))
if stride <= 0: stride = 1
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)
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]
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)
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.")
print(
f"Warning: Error processing file {os.path.basename(file_path)}: {e}. Skipping.")
return []
def create_kfold_dataset():
"""
【已修改】: 主流程函数现在包含一个基于受试者比例筛选数据的步骤。
@@ -120,7 +129,8 @@ def create_kfold_dataset():
# --- 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)
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)
@@ -137,7 +147,7 @@ def create_kfold_dataset():
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.")
@@ -145,43 +155,52 @@ def create_kfold_dataset():
# --- 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),
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.")
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"\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.")
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)
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.")
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))
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.")
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.")
@@ -189,13 +208,18 @@ def create_kfold_dataset():
# --- 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)}")
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)}")
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.")
@@ -219,6 +243,6 @@ 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}")
print(f"\nAn error occurred during the pipeline: {e}")
+22 -19
View File
@@ -4,6 +4,7 @@ import pickle
import numpy as np
from tqdm import tqdm
def zscore_normalize(data):
"""
对多变量时间序列进行Z-score归一化。
@@ -22,7 +23,7 @@ def zscore_normalize(data):
# 如果输入是1D数组 (shape: (L,)), 将其重塑为 (1, L) 以便统一处理
if data_np.ndim == 1:
data_np = data_np.reshape(1, -1)
# 检查数据是否为空
if data_np.size == 0:
tqdm.write("警告: 输入数据为空,返回空数组。")
@@ -32,16 +33,17 @@ def zscore_normalize(data):
# keepdims=True 确保结果形状为 (n_channels, 1),这对于广播操作至关重要
mean = np.mean(data_np, axis=1, keepdims=True)
std = np.std(data_np, axis=1, keepdims=True)
# 关键步骤:防止除以零。如果一个通道的标准差为0(例如,信号是常数),
# 我们将其标准差设为1,这样(data - mean) / 1 = 0,避免了NaN。
std[std == 0] = 1.0
# 执行Z-score归一化
normalized_data = (data_np - mean) / std
return normalized_data
def process_folder(input_folder, output_folder=None):
"""
处理文件夹中的所有.pkl文件,对其中的'data'字段进行Z-score归一化,
@@ -55,22 +57,22 @@ def process_folder(input_folder, output_folder=None):
# 如果未指定输出文件夹,则在输入文件夹内创建默认的输出文件夹
if output_folder is None:
output_folder = os.path.join(input_folder, "normalized_data")
# 安全检查:确保输入和输出文件夹不是同一个地方,防止意外覆盖原始数据
if os.path.abspath(input_folder) == os.path.abspath(output_folder):
raise ValueError("致命错误: 输出文件夹不能与输入文件夹相同,以防止数据丢失。")
# 创建输出目录(如果它还不存在)
os.makedirs(output_folder, exist_ok=True)
# 查找所有.pkl文件
pkl_files = glob.glob(os.path.join(input_folder, "*.pkl"))
if not pkl_files:
print(f"警告: 在目录 '{input_folder}' 中没有找到任何.pkl文件。")
return
print(f"找到 {len(pkl_files)} 个.pkl文件,开始处理...")
# 使用tqdm创建进度条,处理文件
for file_path in tqdm(pkl_files, desc="归一化进度", unit="file"):
base_filename = os.path.basename(file_path)
@@ -78,31 +80,32 @@ def process_folder(input_folder, output_folder=None):
# 以二进制读模式打开文件
with open(file_path, "rb") as f:
data_dict = pickle.load(f)
# 检查'data'字段是否存在
if "data" not in data_dict or data_dict["data"] is None:
tqdm.write(f"警告: 文件 '{base_filename}' 中缺少'data'字段或其值为空,已跳过。")
continue
# 执行归一化
normalized_data = zscore_normalize(data_dict["data"])
# 更新字典中的数据
data_dict["data"] = normalized_data
# 定义输出文件的完整路径
output_path = os.path.join(output_folder, base_filename)
# 以二进制写模式保存更新后的字典
# 使用最高的pickle协议以获得效率和兼容性
with open(output_path, "wb") as f:
pickle.dump(data_dict, f, protocol=pickle.HIGHEST_PROTOCOL)
except pickle.UnpicklingError:
tqdm.write(f"错误: 文件 '{base_filename}' 已损坏或不是有效的pickle文件,已跳过。")
except Exception as e:
tqdm.write(f"处理文件 '{base_filename}' 时发生未知错误: {str(e)}")
if __name__ == "__main__":
# --- 使用示例 ---
# 1. 设置输入路径
@@ -111,7 +114,7 @@ if __name__ == "__main__":
# 2. 设置输出路径 (可选)
# 如果注释掉下面这行,程序会在输入路径下自动创建 "normalized_data" 文件夹
output_path = r"/data/coding/data/pretrain/ecg3" # <--- 如果需要,修改为你的自定义输出路径
output_path = r"/data/coding/data/pretrain/ecg3" # <--- 如果需要,修改为你的自定义输出路径
# --- 程序开始 ---
print("=" * 20 + " 数据归一化脚本 " + "=" * 20)
@@ -129,12 +132,12 @@ if __name__ == "__main__":
try:
# 根据 final_output_path 是否是默认值来决定传递什么参数
if 'output_path' in locals() and output_path:
process_folder(input_path, output_path)
process_folder(input_path, output_path)
else:
process_folder(input_path) # 使用默认输出路径
process_folder(input_path) # 使用默认输出路径
print(f"\n处理完成!归一化后的数据已保存在: {os.path.abspath(final_output_path)}")
except ValueError as ve:
print(f"\n程序中止: {str(ve)}")
except Exception as e:
print(f"\n程序意外出错: {str(e)}")
print(f"\n程序意外出错: {str(e)}")
+73 -55
View File
@@ -1,4 +1,12 @@
# main_pretrain.py (or demo.py)
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
from NormWear.modules.normwear import NormWear
from functools import partial
import timm.optim.optim_factory as optim_factory
from NormWear.pretrain_pipeline.misc import get_next_run_number
from NormWear.pretrain_pipeline import misc
import argparse
import datetime
import json
@@ -13,43 +21,42 @@ from torch.utils.tensorboard import SummaryWriter
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
torch.autograd.set_detect_anomaly(True)
from NormWear.pretrain_pipeline import misc
from NormWear.pretrain_pipeline.misc import get_next_run_number
import timm.optim.optim_factory as optim_factory
from functools import partial
from NormWear.modules.normwear import NormWear
from NormWear.pretrain_pipeline.engine_pretrain import train_one_epoch
# [修改] 确保引入的是带窗口化和缓存功能的 PretrainDataset
from NormWear.pretrain_pipeline.dataset import PretrainDataset, collate_fn, DataLoader
from NormWear.pretrain_pipeline.misc import NativeScalerWithGradNormCount
def get_args_parser():
parser = argparse.ArgumentParser('NormWear MAE Pre-training', add_help=False)
parser = argparse.ArgumentParser(
'NormWear MAE Pre-training', add_help=False)
parser.add_argument('--modality_dropout', type=float, default=0.15,
help='Probability of dropping an entire modality during training (e.g., 0.15 for 15%). Set to 0 to disable.')
# --- [新增] 精度选择参数 ---
parser.add_argument('--precision', default='bf16', type=str, choices=['fp32', 'fp16', 'bf16'],
help='Floating point precision for training. bf16 is recommended on supported hardware (A100, H100, RTX 30/40).')
#pretrain args
#MAEargs
parser.add_argument('--blr', type=float, default=1e-3, metavar='LR', help='base learning rate')
parser.add_argument('--mask_ratio', default=0.75, type=float, help='Ratio of patches to mask')
parser.add_argument('--norm_pix_loss', action='store_true', help='Normalize pixels for loss calculation')
# pretrain args
# MAEargs
parser.add_argument('--blr', type=float, default=1e-3,
metavar='LR', help='base learning rate')
parser.add_argument('--mask_ratio', default=0.75,
type=float, help='Ratio of patches to mask')
parser.add_argument('--norm_pix_loss', action='store_true',
help='Normalize pixels for loss calculation')
parser.set_defaults(norm_pix_loss=False)
# [核心新增] 添加用于控制随机模态丢弃的参数
#training args
# training args
parser.add_argument('--reconstruction_prob', type=float, default=0.25,
help='Probability of a variable being chosen as a reconstruction target (e.g., 0.25 for 25%).')
parser.add_argument('--batch_size', default=768, type=int, help='Batch size per GPU')
parser.add_argument('--batch_size', default=768,
type=int, help='Batch size per GPU')
parser.add_argument('--epochs', default=300, type=int)
parser.add_argument('--accum_iter', default=1, type=int)
parser.add_argument('--remark', default='model768', help='model_remark')
parser.add_argument('--save_every_epoch', default=1, type=int)
parser.add_argument('--model', default='moco_normwear_base', type=str, metavar='MODEL')
parser.add_argument(
'--model', default='moco_normwear_base', type=str, metavar='MODEL')
parser.add_argument('--img_size', default=(387, 65), nargs=2, type=int)
parser.add_argument('--patch_size', type=int, default=(9,5), nargs=2)
parser.add_argument('--patch_size', type=int, default=(9, 5), nargs=2)
parser.add_argument('--in_chans', type=int, default=3)
parser.add_argument('--nvar', type=int, default=5)
parser.add_argument('--embed_dim', type=int, default=768)
@@ -57,37 +64,43 @@ def get_args_parser():
parser.add_argument('--num_heads', type=int, default=12)
parser.add_argument('--mlp_ratio', type=float, default=4.0)
parser.add_argument('--fuse_freq', type=int, default=2)
parser.add_argument('--use_cwt',type=bool,default=True)
parser.add_argument('--use_meanpooling',type=int,default=0)
parser.add_argument('--use_cwt', type=bool, default=True)
parser.add_argument('--use_meanpooling', type=int, default=0)
# [新增] MAE解码器参数
parser.add_argument('--decoder_embed_dim', default=512, type=int, help='Dimensionality of decoder embeddings')
parser.add_argument('--decoder_depth', default=8, type=int, help='Number of layers in the decoder')
parser.add_argument('--decoder_num_heads', default=16, type=int, help='Number of attention heads in the decoder')
parser.add_argument('--decoder_embed_dim', default=512,
type=int, help='Dimensionality of decoder embeddings')
parser.add_argument('--decoder_depth', default=8, type=int,
help='Number of layers in the decoder')
parser.add_argument('--decoder_num_heads', default=16,
type=int, help='Number of attention heads in the decoder')
#learning rate schedule args
# learning rate schedule args
parser.add_argument('--weight_decay', type=float, default=0.1)
parser.add_argument('--lr', type=float, default=None, metavar='LR')
parser.add_argument('--min_lr', type=float, default=0., metavar='LR')
parser.add_argument('--warmup_epochs', type=int, default=8, metavar='N')
parser.add_argument('--clip_grad', type=float, default=None,
help='Clip gradient norm (default: None, no clipping)')
#device args
# device args
parser.add_argument('--device', default='cuda', type=str)
parser.add_argument('--seed', default=42, type=int)
parser.add_argument('--resume', default='', type=str)
parser.add_argument('--is_test', default=0, type=int)
parser.add_argument('--start_epoch', default=0, type=int, metavar='N')
#dataset args
parser.add_argument('--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
parser.add_argument('--output_dir', default="/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result", type=str)
parser.add_argument('--log_dir', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result/log', type=str)
# dataset args
parser.add_argument(
'--data_path', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/', type=str)
parser.add_argument(
'--output_dir', default="/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result", type=str)
parser.add_argument(
'--log_dir', default='/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/result/log', type=str)
parser.add_argument('--num_workers', default=4, type=int)
parser.add_argument('--pin_mem', action='store_true')
parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem')
parser.set_defaults(pin_mem=True)
#distribute args
# distribute args
parser.add_argument('--world_size', default=1, type=int)
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--dist_on_itp', action='store_true')
@@ -105,13 +118,14 @@ def main(args):
# --- [修改] 根据选择的精度设置 dtype 和检查硬件支持 ---
if args.precision == 'bf16':
if not torch.cuda.is_bf16_supported():
raise SystemExit("BF16 is not supported on this device, please use --precision fp16 or fp32.")
raise SystemExit(
"BF16 is not supported on this device, please use --precision fp16 or fp32.")
dtype = torch.bfloat16
elif args.precision == 'fp16':
dtype = torch.float16
else:
dtype = torch.float32
if misc.is_main_process():
print(f"Using precision: {args.precision} with dtype: {dtype}")
@@ -122,14 +136,14 @@ def main(args):
# [修改] 创建数据集时传入窗口化参数
dataset_train = PretrainDataset(
data_dir=args.data_path,
dataset_names=["temp"], # 您可以按需修改
data_dir=args.data_path,
dataset_names=["temp"], # 您可以按需修改
is_test=args.is_test,
window_size=args.img_size[0],
# cache_name="pretrain_windows_ds527821_ws387_s100",
stride=150 # 建议将此值也设为命令行参数
# cache_name="pretrain_windows_ds527821_ws387_s100",
stride=150 # 建议将此值也设为命令行参数
)
if args.distributed:
num_tasks = misc.get_world_size()
global_rank = misc.get_rank()
@@ -153,12 +167,12 @@ def main(args):
dataset_train,
sampler=sampler_train,
batch_size=args.batch_size,
collate_fn=lambda x: collate_fn(x, pad_nvar=args.nvar),
collate_fn=lambda x: collate_fn(x, pad_nvar=args.nvar),
num_workers=args.num_workers,
pin_memory=args.pin_mem,
drop_last=True,
)
model = NormWear(
img_size=(387, 65),
patch_size=(9, 5),
@@ -171,15 +185,16 @@ def main(args):
decoder_num_heads=args.decoder_num_heads,
mlp_ratio=4.0,
modality_dropout_prob=args.modality_dropout,
use_hybrid_embed=True, # MAE强依赖HybridEmbed
nvar=args.nvar # 确保传递n_vars
use_hybrid_embed=True, # MAE强依赖HybridEmbed
nvar=args.nvar # 确保传递n_vars
).to(device)
model.to(device)
model_without_ddp = model
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[args.gpu], find_unused_parameters=True)
model_without_ddp = model.module
eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size()
@@ -187,11 +202,12 @@ def main(args):
args.lr = args.blr * eff_batch_size / 256
if misc.is_main_process():
print(f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
print(
f"base lr: {args.blr:.2e}, actual lr: {args.lr:.2e}, effective batch size: {eff_batch_size}")
optimizer = torch.optim.AdamW(
model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
optimizer = torch.optim.AdamW(model_without_ddp.parameters(), lr=args.lr, weight_decay=args.weight_decay)
# --- [修改] 条件性地创建 GradScaler ---
# 只有在 fp16 模式下才需要 GradScaler,bf16 和 fp32 不需要
loss_scaler = NativeScalerWithGradNormCount() if dtype == torch.float16 else None
@@ -201,29 +217,31 @@ def main(args):
else:
print("GradScaler is disabled for BF16/FP32 training.")
misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler)
misc.load_model(args=args, model_without_ddp=model_without_ddp,
optimizer=optimizer, loss_scaler=loss_scaler)
print(f"Start training for {args.epochs} epochs on rank {misc.get_rank()}")
start_time = time.time()
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
data_loader_train.sampler.set_epoch(epoch)
# [修改] 将 dtype 传入训练引擎
train_stats = train_one_epoch(
model, data_loader_train,
optimizer, device, epoch, loss_scaler,
log_writer=log_writer,
args=args,
dtype=dtype # 传入选择的精度
dtype=dtype # 传入选择的精度
)
if args.output_dir and (epoch % args.save_every_epoch == 0 or epoch + 1 == args.epochs):
misc.save_model(
args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer,
loss_scaler=loss_scaler, epoch=epoch) # [修改] 保存当前epoch
loss_scaler=loss_scaler, epoch=epoch) # [修改] 保存当前epoch
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, 'epoch': epoch}
log_stats = {**{f'train_{k}': v for k,
v in train_stats.items()}, 'epoch': epoch}
if args.output_dir and misc.is_main_process():
if log_writer is not None:
+8 -9
View File
@@ -1,22 +1,21 @@
'''
修改点1:
修改数据划分方式,将顺序划分修改为窗口化,
修改点2:华为的数据需要进行时序对齐,连续
'''
import os
import pickle
import numpy as np
from pathlib import Path
def split_and_save_data(input_pkl_path: str,
output_dir: str = "sample_for_downstream",
segment_size: int = 4) -> None: # 参数名改为segment_size
def split_and_save_data(input_pkl_path: str,
output_dir: str = "sample_for_downstream",
segment_size: int = 4) -> None: # 参数名改为segment_size
"""
按固定数据点数分割单通道数据
Args:
input_pkl_path: 输入文件路径 (e.g., "raw_data/S1_ecg.pkl")
output_dir: 输出目录
@@ -35,7 +34,6 @@ def split_and_save_data(input_pkl_path: str,
assert all(k in original_data for k in required_keys), "缺少必要字段"
assert original_data['data'].ndim == 2, "数据应为二维数组"
# 计算分割参数
total_length = original_data['data'].shape[1]
n_segments = total_length // segment_size # 自动舍弃末尾不足4个的数据
@@ -48,19 +46,20 @@ def split_and_save_data(input_pkl_path: str,
for i in range(n_segments):
start_idx = i * segment_size
end_idx = (i + 1) * segment_size
segment_data = {
**original_data, # 继承所有原始字段
"uid": f"{original_data['uid']}_seg{i+1}", # 更简洁的命名
"data": original_data['data'][:, start_idx:end_idx]
}
output_path = os.path.join(output_dir, f"{segment_data['uid']}.pkl")
with open(output_path, 'wb') as f:
pickle.dump(segment_data, f)
print(f"生成 {n_segments} 个片段至 {output_dir}/ (总数据点: {total_length}, 已使用: {n_segments*segment_size})")
if __name__ == "__main__":
split_and_save_data(
input_pkl_path="cleaned_data.pkl",
+21 -16
View File
@@ -1,10 +1,11 @@
import pickle
import os
def split_pkl_file(input_file, output_dir, original_filename_base):
"""
将包含字典列表的单个pkl文件分割成多个pkl文件,并保存到指定的单个目录中。
参数:
input_file (str): 输入的pkl文件路径。
output_dir (str): 所有分割后文件存放的输出目录路径。
@@ -16,7 +17,7 @@ def split_pkl_file(input_file, output_dir, original_filename_base):
data_list = pickle.load(f)
except (pickle.UnpicklingError, EOFError) as e:
print(f"错误: 无法加载或解析文件 {input_file}。跳过。错误信息: {e}")
return 0 # 返回处理的项目数
return 0 # 返回处理的项目数
# 检查输入数据是否是列表
if not isinstance(data_list, list):
@@ -29,22 +30,23 @@ def split_pkl_file(input_file, output_dir, original_filename_base):
if not isinstance(item, dict):
print(f"警告: 文件 {input_file} 中第 {i} 项不是字典,跳过。")
continue
# 使用 "原文件名_序号.pkl" 的格式创建新文件名
output_filename = f'{original_filename_base}_item_{i}.pkl'
output_file_path = os.path.join(output_dir, output_filename)
with open(output_file_path, 'wb') as f:
pickle.dump(item, f)
count += 1
print(f"从 {os.path.basename(input_file)} 中成功分割 {count} 个项目到 {output_dir} 目录。")
return count
def process_directory(input_dir, output_dir):
"""
处理输入目录下的所有pkl文件,将它们分割后的所有独立项保存到同一个输出目录中。
参数:
input_dir (str): 输入的目录路径,包含多个pkl文件。
output_dir (str): 统一的输出目录路径。
@@ -52,35 +54,38 @@ def process_directory(input_dir, output_dir):
# 检查输入目录是否存在
if not os.path.isdir(input_dir):
raise ValueError(f"输入路径 {input_dir} 不是一个有效的目录。")
# 确保输出目录存在
os.makedirs(output_dir, exist_ok=True)
total_items_processed = 0
# 遍历输入目录下的所有文件
file_list = sorted(os.listdir(input_dir)) # 排序以保证处理顺序一致
file_list = sorted(os.listdir(input_dir)) # 排序以保证处理顺序一致
for filename in file_list:
if filename.endswith('.pkl'):
input_file_path = os.path.join(input_dir, filename)
# 获取不带扩展名的原始文件名,用于命名输出文件
original_filename_base = os.path.splitext(filename)[0]
try:
# 调用分割函数,传入统一的输出目录和原始文件名
num_items = split_pkl_file(input_file_path, output_dir, original_filename_base)
num_items = split_pkl_file(
input_file_path, output_dir, original_filename_base)
total_items_processed += num_items
except Exception as e:
print(f"处理文件 {input_file_path} 时发生严重错误: {str(e)}")
print(f"\n处理完成!总共处理了 {total_items_processed} 个项目,并保存到目录: {output_dir}")
# --- 使用示例 ---
if __name__ == "__main__":
# 设置输入和输出目录
input_directory = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/full_data" # 替换为你的输入目录路径
output_directory = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/temp" # 替换为你想要的统一输出目录
# 替换为你想要的统一输出目录
output_directory = r"/home/bml/storage/mnt/v-044d0fb740b04ad3/org/wearable_data/data/temp"
# 执行处理
process_directory(input_directory, output_directory)
+21 -20
View File
@@ -3,6 +3,7 @@ import pickle
import numpy as np
from tqdm import tqdm
def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=True):
"""
检查指定数据集的样本文件中 'data' 字段是否包含 NaN 或 Inf 值,
@@ -34,7 +35,6 @@ def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=
deleted_count = 0
problematic_files_count = 0
file_list = [f for f in os.listdir(root_dir) if f.endswith('.pkl')]
if not file_list:
print("未找到 .pkl 文件。")
@@ -52,14 +52,15 @@ def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=
print(f"警告: 文件 '{filename}' 中缺少 'data' 字段。跳过删除检查。")
files_with_other_issues.append(filename)
is_problematic_current_file = True
continue # 不删除缺少 'data' 字段的文件,除非你明确想这样做
continue # 不删除缺少 'data' 字段的文件,除非你明确想这样做
data_array = sample['data']
if not isinstance(data_array, np.ndarray):
try:
data_array = np.array(data_array, dtype=float)
except Exception as e:
print(f"警告: 文件 '{filename}' 中的 'data' 字段无法转换为 NumPy 数组: {e}。跳过删除检查。")
print(
f"警告: 文件 '{filename}' 中的 'data' 字段无法转换为 NumPy 数组: {e}。跳过删除检查。")
files_with_other_issues.append(filename)
is_problematic_current_file = True
continue
@@ -79,8 +80,8 @@ def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=
action_taken = True
except Exception as e_del:
print(f"删除文件 '{filename}' 失败: {e_del}")
if has_inf and not action_taken: # 如果因为NaN已经删了,就不用再判断Inf了
if has_inf and not action_taken: # 如果因为NaN已经删了,就不用再判断Inf了
files_to_delete_inf.append(filename)
is_problematic_current_file = True
if not dry_run:
@@ -90,24 +91,21 @@ def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=
deleted_count += 1
except Exception as e_del:
print(f"删除文件 '{filename}' 失败: {e_del}")
elif has_inf and action_taken and filename not in files_to_delete_inf: # 如果因为NaN删了,但它也包含Inf,记录一下
files_to_delete_inf.append(filename)
elif has_inf and action_taken and filename not in files_to_delete_inf: # 如果因为NaN删了,但它也包含Inf,记录一下
files_to_delete_inf.append(filename)
except Exception as e:
print(f"错误: 处理文件 '{filename}' 时发生错误: {e}。跳过删除检查。")
files_with_other_issues.append(filename)
is_problematic_current_file = True
if is_problematic_current_file:
problematic_files_count +=1
if is_problematic_current_file:
problematic_files_count += 1
print("\n--- 检查与删除结果 ---")
print(f"总共检查文件数: {all_files_count}")
print(f"总计发现有问题的文件数 (计划删除或有其他读取/格式问题): {problematic_files_count}")
if files_to_delete_nan:
print(f"\n以下 {len(files_to_delete_nan)} 个文件的 'data' 字段包含 NaN 值{' (并已删除,如果非 Dry Run)' if not dry_run else ' (计划删除,如果非 Dry Run)'}:")
for fname in files_to_delete_nan:
@@ -118,17 +116,18 @@ def check_and_delete_invalid_data_files(dataset_path, sample_folder="", dry_run=
if files_to_delete_inf:
print(f"\n以下 {len(files_to_delete_inf)} 个文件的 'data' 字段包含 Inf 值{' (并已删除,如果非 Dry Run)' if not dry_run else ' (计划删除,如果非 Dry Run)'}:")
# 避免重复打印已因NaN删除的文件
unique_inf_files_to_report = [f for f in files_to_delete_inf if f not in files_to_delete_nan or not (f in files_to_delete_nan and not dry_run)]
unique_inf_files_to_report = [f for f in files_to_delete_inf if f not in files_to_delete_nan or not (
f in files_to_delete_nan and not dry_run)]
if unique_inf_files_to_report:
for fname in unique_inf_files_to_report:
for fname in unique_inf_files_to_report:
print(f" - {fname}")
elif not files_to_delete_nan: # 如果没有NaN文件,但有Inf文件
elif not files_to_delete_nan: # 如果没有NaN文件,但有Inf文件
for fname in files_to_delete_inf:
print(f" - {fname}")
else:
print("\n未在 'data' 字段中检测到 Inf 值。")
if files_with_other_issues:
print(f"\n以下 {len(files_with_other_issues)} 个文件存在其他读取/格式问题 (未删除):")
for fname in files_with_other_issues:
@@ -154,15 +153,17 @@ if __name__ == '__main__':
# **备份你的数据!**
perform_actual_deletion = True # <--- 修改这里来启用/禁用实际删除
if dataset_to_check == "YOUR_DATASET_PATH_HERE": # 只是一个占位符检查
if dataset_to_check == "YOUR_DATASET_PATH_HERE": # 只是一个占位符检查
print("请在脚本中设置 'dataset_to_check' 变量为你要检查的数据集路径。")
else:
if perform_actual_deletion:
confirmation = input(f"你确定要删除数据集 '{dataset_to_check}' 中包含无效数据的文件吗?这是一个不可逆操作!(输入 'yes' 以确认): ")
confirmation = input(
f"你确定要删除数据集 '{dataset_to_check}' 中包含无效数据的文件吗?这是一个不可逆操作!(输入 'yes' 以确认): ")
if confirmation.lower() == 'yes':
check_and_delete_invalid_data_files(dataset_to_check, dry_run=False)
check_and_delete_invalid_data_files(
dataset_to_check, dry_run=False)
else:
print("操作已取消。未删除任何文件。")
else:
print("正在以 Dry Run 模式运行,不会删除任何文件。")
check_and_delete_invalid_data_files(dataset_to_check, dry_run=True)
check_and_delete_invalid_data_files(dataset_to_check, dry_run=True)