""" 通用模型训练工具 提供了模型训练、评估、保存等功能,支持: 1. 训练进度可视化 2. 日志记录 3. 模型检查点保存 4. 嵌入向量收集 """ import torch import torch.nn as nn import torch.optim as optim import time import os import json import logging import numpy as np from tqdm import tqdm from datetime import datetime def setup_logger(log_file): """配置日志记录器,如果日志文件存在则覆盖 Args: log_file: 日志文件路径 Returns: logger: 配置好的日志记录器 """ # 创建logger logger = logging.getLogger('train') logger.setLevel(logging.INFO) # 移除现有的处理器 if logger.hasHandlers(): logger.handlers.clear() # 创建文件处理器,使用'w'模式覆盖现有文件 fh = logging.FileHandler(log_file, mode='w') fh.setLevel(logging.INFO) # 创建控制台处理器 ch = logging.StreamHandler() ch.setLevel(logging.INFO) # 创建格式器 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # 添加处理器 logger.addHandler(fh) logger.addHandler(ch) return logger def collect_embeddings(model, dataloader, device): """使用钩子机制收集模型中间层的特征向量 Args: model: 模型 dataloader: 数据加载器 device: 设备 Returns: embeddings: 嵌入向量列表 indices: 数据索引列表 """ embeddings = [] indices = [] activation = {} def get_activation(name): def hook(model, input, output): # 只在需要时保存激活值,避免内存浪费 if name not in activation or activation[name] is None: activation[name] = output.detach() return hook # 注册钩子到所有可能的特征提取层 handles = [] for name, module in model.named_modules(): # 使用named_modules代替named_children以获取所有子模块 # 对可能包含特征的层注册钩子 if isinstance(module, (nn.Conv2d, nn.Linear, nn.Sequential)): handles.append(module.register_forward_hook(get_activation(name))) model.eval() with torch.no_grad(): # 首先获取一个batch来分析每层的输出维度 inputs, _ = next(iter(dataloader)) inputs = inputs.to(device) _ = model(inputs) # 找到维度最大的层 max_dim = 0 max_layer_name = None # 分析所有层的输出维度 for name, feat in activation.items(): if feat is None or len(feat.shape) < 2: continue # 计算展平后的维度 flat_dim = feat.numel() // feat.shape[0] # 每个样本的特征维度 if flat_dim > max_dim: max_dim = flat_dim max_layer_name = name # 清除第一次运行的激活值 activation.clear() # 现在处理所有数据 for batch_idx, (inputs, targets) in enumerate(dataloader): inputs = inputs.to(device) _ = model(inputs) # 获取并处理特征 features = activation[max_layer_name] flat_features = torch.flatten(features, start_dim=1) embeddings.append(flat_features.cpu().numpy()) indices.extend(range(batch_idx * dataloader.batch_size, min((batch_idx + 1) * dataloader.batch_size, len(dataloader.dataset)))) # 清除本次的激活值 activation.clear() # 移除所有钩子 for handle in handles: handle.remove() if len(embeddings) > 0: return np.vstack(embeddings), indices else: return np.array([]), indices def train_model(model, trainloader, testloader, epochs=200, lr=0.1, device='cuda:0', save_dir='./checkpoints', model_name='model'): """通用的模型训练函数 Args: model: 要训练的模型 trainloader: 训练数据加载器 testloader: 测试数据加载器 epochs: 训练轮数 lr: 学习率 device: 训练设备,格式为'cuda:N',其中N为GPU编号(0,1,2,3) save_dir: 模型保存目录 model_name: 模型名称 """ # 检查并设置GPU设备 if not torch.cuda.is_available(): print("CUDA不可用,将使用CPU训练") device = 'cpu' elif not device.startswith('cuda:'): device = f'cuda:0' # 确保device格式正确 if device.startswith('cuda:'): gpu_id = int(device.split(':')[1]) if gpu_id >= torch.cuda.device_count(): print(f"GPU {gpu_id} 不可用,将使用GPU 0") device = 'cuda:0' # 设置保存目录 if not os.path.exists(save_dir): os.makedirs(save_dir) # 设置日志 log_file = os.path.join(os.path.dirname(save_dir), 'code', 'train.log') if not os.path.exists(os.path.dirname(log_file)): os.makedirs(os.path.dirname(log_file)) logger = setup_logger(log_file) # 损失函数和优化器 criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9, weight_decay=5e-4) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200) # 移动模型到指定设备 model = model.to(device) best_acc = 0 start_time = time.time() logger.info(f'开始训练 {model_name}') logger.info(f'总轮数: {epochs}, 学习率: {lr}, 设备: {device}') for epoch in range(epochs): # 训练阶段 model.train() train_loss = 0 correct = 0 total = 0 train_pbar = tqdm(trainloader, desc=f'Epoch {epoch+1}/{epochs} [Train]') for batch_idx, (inputs, targets) in enumerate(train_pbar): inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() # 更新进度条 train_pbar.set_postfix({ 'loss': f'{train_loss/(batch_idx+1):.3f}', 'acc': f'{100.*correct/total:.2f}%' }) # 每100步记录一次 if batch_idx % 100 == 0: logger.info(f'Epoch: {epoch+1} | Batch: {batch_idx} | ' f'Loss: {train_loss/(batch_idx+1):.3f} | ' f'Acc: {100.*correct/total:.2f}%') # 测试阶段 model.eval() test_loss = 0 correct = 0 total = 0 test_pbar = tqdm(testloader, desc=f'Epoch {epoch+1}/{epochs} [Test]') with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(test_pbar): inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) loss = criterion(outputs, targets) test_loss += loss.item() _, predicted = outputs.max(1) total += targets.size(0) correct += predicted.eq(targets).sum().item() # 更新进度条 test_pbar.set_postfix({ 'loss': f'{test_loss/(batch_idx+1):.3f}', 'acc': f'{100.*correct/total:.2f}%' }) # 计算测试精度 acc = 100.*correct/total logger.info(f'Epoch: {epoch+1} | Test Loss: {test_loss/(batch_idx+1):.3f} | ' f'Test Acc: {acc:.2f}%') # 创建epoch保存目录 epoch_dir = os.path.join(save_dir, f'epoch_{epoch+1}') if not os.path.exists(epoch_dir): os.makedirs(epoch_dir) # 保存模型权重 model_path = os.path.join(epoch_dir, 'subject_model.pth') torch.save(model.state_dict(), model_path) # 收集并保存嵌入向量 embeddings, indices = collect_embeddings(model, trainloader, device) # 保存嵌入向量 np.save(os.path.join(epoch_dir, 'train_data.npy'), embeddings) # 保存索引信息 - 仅保存数据点的索引列表 with open(os.path.join(epoch_dir, 'index.json'), 'w') as f: json.dump(indices, f) # 如果是最佳精度,额外保存一份 if acc > best_acc: logger.info(f'Best accuracy: {acc:.2f}%') best_dir = os.path.join(save_dir, 'best') if not os.path.exists(best_dir): os.makedirs(best_dir) # 复制最佳模型文件 best_model_path = os.path.join(best_dir, 'subject_model.pth') torch.save(model.state_dict(), best_model_path) best_acc = acc scheduler.step() # 训练结束 total_time = time.time() - start_time logger.info(f'训练完成! 总用时: {total_time/3600:.2f}小时') logger.info(f'最佳测试精度: {best_acc:.2f}%')