File size: 7,722 Bytes
3621f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""
金融预测损失函数

包含:
- 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✅ 所有损失函数测试通过")