""" 金融预测损失函数 包含: - DirectionalMSELoss: MSE + 方向损失 - DirectionalMAELoss: MAE + 方向损失 - MultiTaskLoss: 价格预测 + 涨跌分类 多任务损失 """ import torch import torch.nn as nn import torch.nn.functional as F class DirectionalMSELoss(nn.Module): """ 带方向损失的MSE Loss = MSE(pred, true) + direction_weight * DirectionLoss 方向损失鼓励模型正确预测涨跌方向 """ def __init__(self, direction_weight=0.3): super().__init__() self.mse = nn.MSELoss() self.direction_weight = direction_weight def forward(self, pred, target): """ pred: [B, pred_len] 预测序列 target: [B, pred_len] 真实序列 """ # 1. MSE损失(价格预测) mse_loss = self.mse(pred, target) # 2. 方向损失(涨跌预测) # 计算预测和真实的变化 pred_change = pred[:, -1] - pred[:, 0] # 预测的总变化 true_change = target[:, -1] - target[:, 0] # 真实的总变化 # 二元交叉熵:预测变化 vs 真实是否上涨 true_direction = (true_change > 0).float() direction_loss = F.binary_cross_entropy_with_logits( pred_change, true_direction ) # 3. 总损失 total_loss = mse_loss + self.direction_weight * direction_loss return total_loss class DirectionalMAELoss(nn.Module): """ 带方向损失的MAE Loss = MAE(pred, true) + direction_weight * DirectionLoss """ def __init__(self, direction_weight=0.3): super().__init__() self.direction_weight = direction_weight def forward(self, pred, target): # MAE损失 mae_loss = F.l1_loss(pred, target) # 方向损失 pred_change = pred[:, -1] - pred[:, 0] true_change = target[:, -1] - target[:, 0] true_direction = (true_change > 0).float() direction_loss = F.binary_cross_entropy_with_logits( pred_change, true_direction ) return mae_loss + self.direction_weight * direction_loss class MultiStepDirectionalLoss(nn.Module): """ 多步方向损失 不仅考虑首尾方向,还考虑每一步的方向 """ def __init__(self, mse_weight=1.0, direction_weight=0.3, step_weight=0.1): super().__init__() self.mse_weight = mse_weight self.direction_weight = direction_weight self.step_weight = step_weight self.mse = nn.MSELoss() def forward(self, pred, target): # MSE损失 mse_loss = self.mse(pred, target) # 首尾方向损失 pred_change = pred[:, -1] - pred[:, 0] true_change = target[:, -1] - target[:, 0] true_direction = (true_change > 0).float() main_direction_loss = F.binary_cross_entropy_with_logits( pred_change, true_direction ) # 每一步方向损失 pred_steps = pred[:, 1:] - pred[:, :-1] # [B, T-1] true_steps = target[:, 1:] - target[:, :-1] # [B, T-1] true_step_dirs = (true_steps > 0).float() step_direction_loss = F.binary_cross_entropy_with_logits( pred_steps, true_step_dirs ) total_loss = (self.mse_weight * mse_loss + self.direction_weight * main_direction_loss + self.step_weight * step_direction_loss) return total_loss class MultiTaskLoss(nn.Module): """ 多任务损失 任务1: 价格预测 (MSE) 任务2: 涨跌分类 (BCE) 需要模型同时输出预测序列和涨跌概率 """ def __init__(self, price_weight=1.0, direction_weight=0.5): super().__init__() self.price_weight = price_weight self.direction_weight = direction_weight self.mse = nn.MSELoss() self.bce = nn.BCEWithLogitsLoss() def forward(self, pred_price, pred_direction, target_price): """ pred_price: [B, pred_len] 价格预测 pred_direction: [B, 1] 涨跌预测logit target_price: [B, pred_len] 真实价格 """ # 价格预测损失 price_loss = self.mse(pred_price, target_price) # 涨跌分类损失 true_direction = (target_price[:, -1] - target_price[:, 0] > 0).float().unsqueeze(1) direction_loss = self.bce(pred_direction, true_direction) return self.price_weight * price_loss + self.direction_weight * direction_loss class TrendAwareLoss(nn.Module): """ 趋势感知损失 对趋势方向错误的样本给予更高的惩罚 """ def __init__(self, base_weight=1.0, penalty_weight=2.0): super().__init__() self.base_weight = base_weight self.penalty_weight = penalty_weight def forward(self, pred, target): # 基础MSE mse = (pred - target) ** 2 # 计算方向 pred_direction = torch.sign(pred[:, -1] - pred[:, 0]) # [B] true_direction = torch.sign(target[:, -1] - target[:, 0]) # [B] # 方向错误的样本权重更高 direction_wrong = (pred_direction != true_direction).float() # [B] # 加权 weights = self.base_weight + self.penalty_weight * direction_wrong.unsqueeze(1) # [B, 1] weighted_mse = (mse * weights).mean() return weighted_mse class HuberDirectionalLoss(nn.Module): """ Huber + 方向损失 Huber损失对异常值更鲁棒 """ def __init__(self, delta=1.0, direction_weight=0.3): super().__init__() self.huber = nn.HuberLoss(delta=delta) self.direction_weight = direction_weight def forward(self, pred, target): huber_loss = self.huber(pred, target) pred_change = pred[:, -1] - pred[:, 0] true_change = target[:, -1] - target[:, 0] true_direction = (true_change > 0).float() direction_loss = F.binary_cross_entropy_with_logits( pred_change, true_direction ) return huber_loss + self.direction_weight * direction_loss def get_loss_function(loss_name, **kwargs): """ 获取损失函数 Args: loss_name: 损失函数名称 **kwargs: 参数 Returns: 损失函数实例 """ losses = { 'mse': nn.MSELoss, 'mae': nn.L1Loss, 'huber': nn.HuberLoss, 'directional_mse': DirectionalMSELoss, 'directional_mae': DirectionalMAELoss, 'multistep_directional': MultiStepDirectionalLoss, 'trend_aware': TrendAwareLoss, 'huber_directional': HuberDirectionalLoss, } if loss_name.lower() not in losses: raise ValueError(f"Unknown loss: {loss_name}. Available: {list(losses.keys())}") return losses[loss_name.lower()](**kwargs) # 测试 if __name__ == '__main__': print("损失函数测试") print("=" * 60) B, T = 8, 20 pred = torch.randn(B, T) target = torch.randn(B, T) losses_to_test = [ ('mse', {}), ('directional_mse', {'direction_weight': 0.3}), ('directional_mae', {'direction_weight': 0.3}), ('multistep_directional', {}), ('trend_aware', {}), ('huber_directional', {}), ] for name, kwargs in losses_to_test: loss_fn = get_loss_function(name, **kwargs) loss = loss_fn(pred, target) print(f"{name:25s}: {loss.item():.4f}") print("\n✅ 所有损失函数测试通过")