yonghao commited on
Commit
6cf7f4b
·
verified ·
1 Parent(s): c27168a

Add app sequence model template (CoLES+GRU)

Browse files
Files changed (1) hide show
  1. app_sequence_model.py +703 -0
app_sequence_model.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ App 安装序列 风控模型 — 完整代码模板
3
+ ======================================
4
+ 方法: CoLES (Contrastive Learning for Event Sequences) + GRU
5
+ 论文: arxiv:2002.08232 (KDD 2022)
6
+ 依据: EBES 2024 benchmark 验证 GRU+CoLES 在金融序列上排名第一
7
+
8
+ 使用方式:
9
+ 1. 替换 `load_your_data()` 为你自己的数据加载逻辑
10
+ 2. 调整 `CONFIG` 中的超参数
11
+ 3. 先跑 Stage 1 (无监督预训练),再跑 Stage 2 (有监督微调)
12
+
13
+ 依赖: pip install pytorch-lifestream torch scikit-learn lightgbm pandas numpy
14
+ """
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from torch.utils.data import Dataset, DataLoader
20
+ import numpy as np
21
+ import pandas as pd
22
+ from sklearn.model_selection import train_test_split
23
+ from sklearn.metrics import roc_auc_score
24
+ from typing import List, Dict, Tuple, Optional
25
+ import logging
26
+
27
+ logging.basicConfig(level=logging.INFO)
28
+ logger = logging.getLogger(__name__)
29
+
30
+ # ============================================================
31
+ # CONFIG — 所有超参数集中管理
32
+ # ============================================================
33
+ CONFIG = {
34
+ # 数据相关
35
+ "max_seq_len": 200, # 保留最近 200 次安装,过长截断最老的
36
+ "app_vocab_size": 50000, # Top 50K app,长尾合并到 <OTHER>
37
+ "app_category_size": 256, # App 一级类目数量
38
+ "app_source_size": 8, # 安装来源(应用商店/浏览器/预装等)
39
+
40
+ # Embedding 维度
41
+ "app_id_embed_dim": 32, # app_id 嵌入维度
42
+ "app_category_embed_dim": 16, # 类目嵌入维度
43
+ "app_source_embed_dim": 4, # 来源嵌入维度
44
+ "time_feat_dim": 8, # 时间特征维度(正余弦编码)
45
+
46
+ # 序列编码器 (GRU)
47
+ "hidden_size": 256, # GRU 隐藏层大小 (论文推荐 256-512)
48
+ "num_layers": 2, # GRU 层数
49
+ "dropout": 0.1,
50
+ "bidirectional": False, # 单向 GRU (因为时间有方向性)
51
+
52
+ # CoLES 对比学习
53
+ "num_sub_slices": 4, # 每个用户采 K=4 个子序列做对比
54
+ "contrastive_margin": 0.5, # 对比学习 margin
55
+ "temperature": 0.07, # InfoNCE temperature
56
+
57
+ # 训练
58
+ "pretrain_lr": 1e-3, # 预训练学习率
59
+ "finetune_lr": 5e-4, # 微调学习率
60
+ "batch_size": 256,
61
+ "pretrain_epochs": 30,
62
+ "finetune_epochs": 20,
63
+ "weight_decay": 1e-5,
64
+
65
+ # 下游分类器
66
+ "classifier_hidden": 128,
67
+ "num_classes": 1, # 二分类 (违约/正常)
68
+ }
69
+
70
+
71
+ # ============================================================
72
+ # 数据预处理
73
+ # ============================================================
74
+ class AppInstallEvent:
75
+ """单个 App 安装事件"""
76
+ def __init__(self, app_id: int, category_id: int, source_id: int,
77
+ timestamp: float, time_delta: float = 0.0):
78
+ self.app_id = app_id
79
+ self.category_id = category_id
80
+ self.source_id = source_id
81
+ self.timestamp = timestamp
82
+ self.time_delta = time_delta # 距上次安装的天数
83
+
84
+
85
+ def preprocess_app_sequence(raw_df: pd.DataFrame) -> Dict[int, List[AppInstallEvent]]:
86
+ """
87
+ 输入 DataFrame 格式:
88
+ user_id | app_id | app_category | install_source | install_timestamp
89
+
90
+ 输出: {user_id: [AppInstallEvent, ...]} 按时间排序
91
+ """
92
+ user_sequences = {}
93
+
94
+ for user_id, group in raw_df.groupby('user_id'):
95
+ group = group.sort_values('install_timestamp')
96
+ events = []
97
+ prev_time = None
98
+
99
+ for _, row in group.iterrows():
100
+ time_delta = 0.0
101
+ if prev_time is not None:
102
+ time_delta = (row['install_timestamp'] - prev_time) / 86400.0 # 转换为天
103
+
104
+ event = AppInstallEvent(
105
+ app_id=row['app_id'],
106
+ category_id=row['app_category'],
107
+ source_id=row['install_source'],
108
+ timestamp=row['install_timestamp'],
109
+ time_delta=time_delta
110
+ )
111
+ events.append(event)
112
+ prev_time = row['install_timestamp']
113
+
114
+ # 截断: 保留最近 max_seq_len 个事件
115
+ if len(events) > CONFIG['max_seq_len']:
116
+ events = events[-CONFIG['max_seq_len']:]
117
+
118
+ user_sequences[user_id] = events
119
+
120
+ return user_sequences
121
+
122
+
123
+ def sine_cosine_time_encoding(time_delta: float, periods=[1, 7, 30, 365]) -> np.ndarray:
124
+ """
125
+ 正余弦周期时间编码 (来自 LBSF 论文 arxiv:2411.15056)
126
+ 将时间差编码为多个周期的 sin/cos,捕捉日/周/月/年周期性
127
+ """
128
+ embeddings = []
129
+ for T in periods:
130
+ embeddings.append(np.cos(2 * np.pi * time_delta / T))
131
+ embeddings.append(np.sin(2 * np.pi * time_delta / T))
132
+ return np.array(embeddings, dtype=np.float32)
133
+
134
+
135
+ # ============================================================
136
+ # Dataset
137
+ # ============================================================
138
+ class AppSequenceDataset(Dataset):
139
+ """App 安装序列数据集"""
140
+
141
+ def __init__(self, user_sequences: Dict[int, List[AppInstallEvent]],
142
+ labels: Optional[Dict[int, int]] = None):
143
+ self.user_ids = list(user_sequences.keys())
144
+ self.sequences = user_sequences
145
+ self.labels = labels
146
+
147
+ def __len__(self):
148
+ return len(self.user_ids)
149
+
150
+ def __getitem__(self, idx):
151
+ user_id = self.user_ids[idx]
152
+ events = self.sequences[user_id]
153
+
154
+ seq_len = len(events)
155
+ app_ids = torch.zeros(CONFIG['max_seq_len'], dtype=torch.long)
156
+ categories = torch.zeros(CONFIG['max_seq_len'], dtype=torch.long)
157
+ sources = torch.zeros(CONFIG['max_seq_len'], dtype=torch.long)
158
+ time_features = torch.zeros(CONFIG['max_seq_len'], CONFIG['time_feat_dim'])
159
+ mask = torch.zeros(CONFIG['max_seq_len'], dtype=torch.bool)
160
+
161
+ for i, event in enumerate(events):
162
+ app_ids[i] = event.app_id
163
+ categories[i] = event.category_id
164
+ sources[i] = event.source_id
165
+ time_features[i] = torch.from_numpy(
166
+ sine_cosine_time_encoding(event.time_delta)
167
+ )
168
+ mask[i] = True
169
+
170
+ sample = {
171
+ 'app_ids': app_ids,
172
+ 'categories': categories,
173
+ 'sources': sources,
174
+ 'time_features': time_features,
175
+ 'mask': mask,
176
+ 'seq_len': seq_len,
177
+ }
178
+
179
+ if self.labels is not None:
180
+ sample['label'] = torch.tensor(self.labels[user_id], dtype=torch.float32)
181
+
182
+ return sample
183
+
184
+
185
+ # ============================================================
186
+ # 模型: 事件编码器 + GRU 序列编码器
187
+ # ============================================================
188
+ class EventEncoder(nn.Module):
189
+ """将单个 App 安装事件编码为 dense vector"""
190
+
191
+ def __init__(self):
192
+ super().__init__()
193
+ self.app_embed = nn.Embedding(
194
+ CONFIG['app_vocab_size'] + 1, CONFIG['app_id_embed_dim'], padding_idx=0
195
+ )
196
+ self.cat_embed = nn.Embedding(
197
+ CONFIG['app_category_size'] + 1, CONFIG['app_category_embed_dim'], padding_idx=0
198
+ )
199
+ self.source_embed = nn.Embedding(
200
+ CONFIG['app_source_size'] + 1, CONFIG['app_source_embed_dim'], padding_idx=0
201
+ )
202
+
203
+ self.event_dim = (CONFIG['app_id_embed_dim'] +
204
+ CONFIG['app_category_embed_dim'] +
205
+ CONFIG['app_source_embed_dim'] +
206
+ CONFIG['time_feat_dim'])
207
+
208
+ self.proj = nn.Linear(self.event_dim, CONFIG['hidden_size'])
209
+ self.layer_norm = nn.LayerNorm(CONFIG['hidden_size'])
210
+ self.dropout = nn.Dropout(CONFIG['dropout'])
211
+
212
+ def forward(self, app_ids, categories, sources, time_features):
213
+ app_emb = self.app_embed(app_ids)
214
+ cat_emb = self.cat_embed(categories)
215
+ src_emb = self.source_embed(sources)
216
+
217
+ event_repr = torch.cat([app_emb, cat_emb, src_emb, time_features], dim=-1)
218
+ event_repr = self.proj(event_repr)
219
+ event_repr = self.layer_norm(event_repr)
220
+ event_repr = self.dropout(event_repr)
221
+
222
+ return event_repr
223
+
224
+
225
+ class GRUSequenceEncoder(nn.Module):
226
+ """GRU 序列编码器 (CoLES 验证 GRU > LSTM > Transformer 在金融序列上)"""
227
+
228
+ def __init__(self):
229
+ super().__init__()
230
+ self.event_encoder = EventEncoder()
231
+
232
+ self.gru = nn.GRU(
233
+ input_size=CONFIG['hidden_size'],
234
+ hidden_size=CONFIG['hidden_size'],
235
+ num_layers=CONFIG['num_layers'],
236
+ batch_first=True,
237
+ dropout=CONFIG['dropout'] if CONFIG['num_layers'] > 1 else 0,
238
+ bidirectional=CONFIG['bidirectional']
239
+ )
240
+
241
+ gru_output_dim = CONFIG['hidden_size'] * (2 if CONFIG['bidirectional'] else 1)
242
+ self.output_proj = nn.Linear(gru_output_dim, CONFIG['hidden_size'])
243
+
244
+ def forward(self, app_ids, categories, sources, time_features, mask):
245
+ event_repr = self.event_encoder(app_ids, categories, sources, time_features)
246
+
247
+ lengths = mask.sum(dim=1).cpu()
248
+ packed = nn.utils.rnn.pack_padded_sequence(
249
+ event_repr, lengths, batch_first=True, enforce_sorted=False
250
+ )
251
+
252
+ packed_output, hidden = self.gru(packed)
253
+
254
+ if CONFIG['bidirectional']:
255
+ user_embedding = torch.cat([hidden[-2], hidden[-1]], dim=-1)
256
+ else:
257
+ user_embedding = hidden[-1]
258
+
259
+ user_embedding = self.output_proj(user_embedding)
260
+ return user_embedding
261
+
262
+
263
+ # ============================================================
264
+ # Stage 1: CoLES 自监督预训练 (无需标签)
265
+ # ============================================================
266
+ class CoLESModel(nn.Module):
267
+ """CoLES: 同一用户的不同时间切片应该相似,不同用户应该不相似"""
268
+
269
+ def __init__(self):
270
+ super().__init__()
271
+ self.encoder = GRUSequenceEncoder()
272
+
273
+ def forward(self, batch):
274
+ return self.encoder(
275
+ batch['app_ids'], batch['categories'],
276
+ batch['sources'], batch['time_features'], batch['mask']
277
+ )
278
+
279
+
280
+ def sample_sub_sequence(events: List[AppInstallEvent], min_len: int = 5) -> List[AppInstallEvent]:
281
+ """CoLES 核心: 从完整序列中随机切一段子序列"""
282
+ seq_len = len(events)
283
+ if seq_len <= min_len:
284
+ return events
285
+
286
+ start = np.random.randint(0, max(1, seq_len - min_len))
287
+ end = np.random.randint(start + min_len, min(seq_len + 1, start + CONFIG['max_seq_len']))
288
+
289
+ return events[start:end]
290
+
291
+
292
+ def coles_contrastive_loss(embeddings: torch.Tensor, num_sub_slices: int = 4):
293
+ """CoLES Loss: 同一用户的子序列embedding靠近,不同用户的远离"""
294
+ batch_size = embeddings.shape[0] // num_sub_slices
295
+ device = embeddings.device
296
+
297
+ embeddings = F.normalize(embeddings, p=2, dim=1)
298
+ sim_matrix = torch.mm(embeddings, embeddings.t()) / CONFIG['temperature']
299
+
300
+ labels = torch.arange(batch_size).repeat_interleave(num_sub_slices).to(device)
301
+ positive_mask = (labels.unsqueeze(0) == labels.unsqueeze(1)).float()
302
+ positive_mask.fill_diagonal_(0)
303
+
304
+ exp_sim = torch.exp(sim_matrix)
305
+ exp_sim.fill_diagonal_(0)
306
+
307
+ pos_sim = (exp_sim * positive_mask).sum(dim=1)
308
+ all_sim = exp_sim.sum(dim=1)
309
+
310
+ loss = -torch.log(pos_sim / (all_sim + 1e-8) + 1e-8).mean()
311
+ return loss
312
+
313
+
314
+ def pretrain_coles(user_sequences: Dict[int, List[AppInstallEvent]], epochs: int = None):
315
+ """Stage 1: CoLES 无监督预训练,不需要任何标签"""
316
+ if epochs is None:
317
+ epochs = CONFIG['pretrain_epochs']
318
+
319
+ model = CoLESModel()
320
+ optimizer = torch.optim.Adam(model.parameters(), lr=CONFIG['pretrain_lr'], weight_decay=CONFIG['weight_decay'])
321
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
322
+
323
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
324
+ model = model.to(device)
325
+
326
+ user_ids = list(user_sequences.keys())
327
+ batch_size = CONFIG['batch_size']
328
+ K = CONFIG['num_sub_slices']
329
+
330
+ logger.info(f"Starting CoLES pretraining: {len(user_ids)} users, {epochs} epochs")
331
+
332
+ for epoch in range(epochs):
333
+ model.train()
334
+ total_loss = 0
335
+ num_batches = 0
336
+
337
+ np.random.shuffle(user_ids)
338
+
339
+ for batch_start in range(0, len(user_ids), batch_size):
340
+ batch_users = user_ids[batch_start:batch_start + batch_size]
341
+
342
+ all_sub_seqs = []
343
+ for uid in batch_users:
344
+ events = user_sequences[uid]
345
+ for _ in range(K):
346
+ sub_seq = sample_sub_sequence(events)
347
+ all_sub_seqs.append(sub_seq)
348
+
349
+ actual_batch_size = len(all_sub_seqs)
350
+ app_ids = torch.zeros(actual_batch_size, CONFIG['max_seq_len'], dtype=torch.long)
351
+ categories = torch.zeros(actual_batch_size, CONFIG['max_seq_len'], dtype=torch.long)
352
+ sources = torch.zeros(actual_batch_size, CONFIG['max_seq_len'], dtype=torch.long)
353
+ time_features = torch.zeros(actual_batch_size, CONFIG['max_seq_len'], CONFIG['time_feat_dim'])
354
+ mask = torch.zeros(actual_batch_size, CONFIG['max_seq_len'], dtype=torch.bool)
355
+
356
+ for i, events in enumerate(all_sub_seqs):
357
+ for j, event in enumerate(events[:CONFIG['max_seq_len']]):
358
+ app_ids[i, j] = event.app_id
359
+ categories[i, j] = event.category_id
360
+ sources[i, j] = event.source_id
361
+ time_features[i, j] = torch.from_numpy(sine_cosine_time_encoding(event.time_delta))
362
+ mask[i, j] = True
363
+
364
+ batch = {
365
+ 'app_ids': app_ids.to(device), 'categories': categories.to(device),
366
+ 'sources': sources.to(device), 'time_features': time_features.to(device),
367
+ 'mask': mask.to(device),
368
+ }
369
+
370
+ embeddings = model(batch)
371
+ loss = coles_contrastive_loss(embeddings, num_sub_slices=K)
372
+
373
+ optimizer.zero_grad()
374
+ loss.backward()
375
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
376
+ optimizer.step()
377
+
378
+ total_loss += loss.item()
379
+ num_batches += 1
380
+
381
+ scheduler.step()
382
+ avg_loss = total_loss / max(num_batches, 1)
383
+ logger.info(f"Epoch {epoch+1}/{epochs}, Loss: {avg_loss:.4f}, LR: {scheduler.get_last_lr()[0]:.6f}")
384
+
385
+ logger.info("CoLES pretraining complete!")
386
+ return model
387
+
388
+
389
+ # ============================================================
390
+ # Stage 2: 有监督微调 / 下游分类
391
+ # ============================================================
392
+ class RiskClassifier(nn.Module):
393
+ """风险分类头: 冻结/微调 CoLES encoder + MLP head"""
394
+
395
+ def __init__(self, pretrained_encoder: GRUSequenceEncoder, freeze_encoder: bool = False):
396
+ super().__init__()
397
+ self.encoder = pretrained_encoder
398
+ self.freeze_encoder = freeze_encoder
399
+
400
+ if freeze_encoder:
401
+ for param in self.encoder.parameters():
402
+ param.requires_grad = False
403
+
404
+ self.classifier = nn.Sequential(
405
+ nn.Linear(CONFIG['hidden_size'], CONFIG['classifier_hidden']),
406
+ nn.ReLU(),
407
+ nn.Dropout(CONFIG['dropout']),
408
+ nn.Linear(CONFIG['classifier_hidden'], CONFIG['classifier_hidden'] // 2),
409
+ nn.ReLU(),
410
+ nn.Dropout(CONFIG['dropout']),
411
+ nn.Linear(CONFIG['classifier_hidden'] // 2, 1),
412
+ )
413
+
414
+ def forward(self, app_ids, categories, sources, time_features, mask):
415
+ if self.freeze_encoder:
416
+ with torch.no_grad():
417
+ user_emb = self.encoder(app_ids, categories, sources, time_features, mask)
418
+ else:
419
+ user_emb = self.encoder(app_ids, categories, sources, time_features, mask)
420
+
421
+ logits = self.classifier(user_emb).squeeze(-1)
422
+ return logits
423
+
424
+ def get_user_embedding(self, app_ids, categories, sources, time_features, mask):
425
+ """导出用户向量(用于接 LightGBM)"""
426
+ with torch.no_grad():
427
+ return self.encoder(app_ids, categories, sources, time_features, mask)
428
+
429
+
430
+ def finetune_classifier(pretrained_model: CoLESModel,
431
+ user_sequences: Dict[int, List[AppInstallEvent]],
432
+ labels: Dict[int, int],
433
+ freeze_encoder: bool = False):
434
+ """Stage 2: 有监督微调"""
435
+ user_ids = list(labels.keys())
436
+ train_ids, val_ids = train_test_split(user_ids, test_size=0.2,
437
+ stratify=[labels[uid] for uid in user_ids], random_state=42)
438
+
439
+ train_seqs = {uid: user_sequences[uid] for uid in train_ids}
440
+ val_seqs = {uid: user_sequences[uid] for uid in val_ids}
441
+ train_labels = {uid: labels[uid] for uid in train_ids}
442
+ val_labels = {uid: labels[uid] for uid in val_ids}
443
+
444
+ train_dataset = AppSequenceDataset(train_seqs, train_labels)
445
+ val_dataset = AppSequenceDataset(val_seqs, val_labels)
446
+
447
+ train_loader = DataLoader(train_dataset, batch_size=CONFIG['batch_size'], shuffle=True)
448
+ val_loader = DataLoader(val_dataset, batch_size=CONFIG['batch_size'])
449
+
450
+ classifier = RiskClassifier(pretrained_model.encoder, freeze_encoder=freeze_encoder)
451
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
452
+ classifier = classifier.to(device)
453
+
454
+ num_pos = sum(labels.values())
455
+ num_neg = len(labels) - num_pos
456
+ pos_weight = torch.tensor([num_neg / max(num_pos, 1)]).to(device)
457
+ logger.info(f"Class balance: pos={num_pos}, neg={num_neg}, pos_weight={pos_weight.item():.2f}")
458
+
459
+ criterion = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
460
+ optimizer = torch.optim.AdamW(
461
+ filter(lambda p: p.requires_grad, classifier.parameters()),
462
+ lr=CONFIG['finetune_lr'], weight_decay=CONFIG['weight_decay']
463
+ )
464
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.5, patience=3)
465
+
466
+ best_auc = 0
467
+ patience_counter = 0
468
+ max_patience = 7
469
+
470
+ for epoch in range(CONFIG['finetune_epochs']):
471
+ classifier.train()
472
+ train_loss = 0
473
+ for batch in train_loader:
474
+ logits = classifier(
475
+ batch['app_ids'].to(device), batch['categories'].to(device),
476
+ batch['sources'].to(device), batch['time_features'].to(device),
477
+ batch['mask'].to(device)
478
+ )
479
+ loss = criterion(logits, batch['label'].to(device))
480
+ optimizer.zero_grad()
481
+ loss.backward()
482
+ torch.nn.utils.clip_grad_norm_(classifier.parameters(), max_norm=1.0)
483
+ optimizer.step()
484
+ train_loss += loss.item()
485
+
486
+ classifier.eval()
487
+ val_preds = []
488
+ val_labels_list = []
489
+ with torch.no_grad():
490
+ for batch in val_loader:
491
+ logits = classifier(
492
+ batch['app_ids'].to(device), batch['categories'].to(device),
493
+ batch['sources'].to(device), batch['time_features'].to(device),
494
+ batch['mask'].to(device)
495
+ )
496
+ probs = torch.sigmoid(logits).cpu().numpy()
497
+ val_preds.extend(probs)
498
+ val_labels_list.extend(batch['label'].numpy())
499
+
500
+ val_auc = roc_auc_score(val_labels_list, val_preds)
501
+ scheduler.step(val_auc)
502
+
503
+ avg_train_loss = train_loss / len(train_loader)
504
+ logger.info(f"Epoch {epoch+1}/{CONFIG['finetune_epochs']}, Train Loss: {avg_train_loss:.4f}, Val AUC: {val_auc:.4f}")
505
+
506
+ if val_auc > best_auc:
507
+ best_auc = val_auc
508
+ patience_counter = 0
509
+ torch.save(classifier.state_dict(), 'best_app_sequence_model.pt')
510
+ logger.info(f" → New best AUC: {best_auc:.4f}, model saved!")
511
+ else:
512
+ patience_counter += 1
513
+ if patience_counter >= max_patience:
514
+ logger.info(f"Early stopping at epoch {epoch+1}")
515
+ break
516
+
517
+ logger.info(f"Fine-tuning complete. Best Val AUC: {best_auc:.4f}")
518
+ return classifier, best_auc
519
+
520
+
521
+ # ============================================================
522
+ # 方案 B: 导出 CoLES 向量 → LightGBM (论文推荐方案)
523
+ # ============================================================
524
+ def extract_embeddings_for_lgbm(pretrained_model: CoLESModel,
525
+ user_sequences: Dict[int, List[AppInstallEvent]],
526
+ labels: Dict[int, int]):
527
+ """
528
+ 导出用户embedding,接LightGBM
529
+ 这是CoLES论文里效果最好的方案: 预训练256d向量→LightGBM分类
530
+ """
531
+ try:
532
+ import lightgbm as lgb
533
+ except ImportError:
534
+ logger.error("请安装 lightgbm: pip install lightgbm")
535
+ return None
536
+
537
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
538
+ pretrained_model = pretrained_model.to(device)
539
+ pretrained_model.eval()
540
+
541
+ dataset = AppSequenceDataset(user_sequences, labels)
542
+ loader = DataLoader(dataset, batch_size=CONFIG['batch_size'])
543
+
544
+ all_embeddings = []
545
+ all_labels = []
546
+
547
+ with torch.no_grad():
548
+ for batch in loader:
549
+ emb = pretrained_model(batch)
550
+ all_embeddings.append(emb.cpu().numpy())
551
+ all_labels.append(batch['label'].numpy())
552
+
553
+ X = np.concatenate(all_embeddings, axis=0)
554
+ y = np.concatenate(all_labels, axis=0)
555
+
556
+ X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
557
+
558
+ lgb_params = {
559
+ 'objective': 'binary', 'metric': 'auc',
560
+ 'learning_rate': 0.05, 'num_leaves': 63, 'max_depth': 7,
561
+ 'min_child_samples': 20,
562
+ 'scale_pos_weight': sum(y_train == 0) / max(sum(y_train == 1), 1),
563
+ 'subsample': 0.8, 'colsample_bytree': 0.8, 'verbose': -1,
564
+ }
565
+
566
+ train_data = lgb.Dataset(X_train, label=y_train)
567
+ val_data = lgb.Dataset(X_val, label=y_val, reference=train_data)
568
+
569
+ model = lgb.train(
570
+ lgb_params, train_data, num_boost_round=500, valid_sets=[val_data],
571
+ callbacks=[lgb.early_stopping(stopping_rounds=30), lgb.log_evaluation(50)]
572
+ )
573
+
574
+ val_pred = model.predict(X_val)
575
+ val_auc = roc_auc_score(y_val, val_pred)
576
+
577
+ from scipy.stats import ks_2samp
578
+ ks_stat = ks_2samp(val_pred[y_val == 1], val_pred[y_val == 0]).statistic
579
+
580
+ logger.info(f"LightGBM Results: AUC={val_auc:.4f}, KS={ks_stat:.4f}")
581
+ return model, val_auc, ks_stat
582
+
583
+
584
+ # ============================================================
585
+ # Graph-Augmented: App 共现图增强 (arxiv:2604.09085)
586
+ # ============================================================
587
+ class AppCoInstallGraph:
588
+ """
589
+ 构建App共安装图: 如果两个App经常被同一批用户安装,它们之间有边
590
+ 用Node2Vec/GraphSAGE生成App embedding → 替换原始App embedding
591
+ 论文结论: AUC +2.3% over vanilla CoLES
592
+ """
593
+
594
+ def __init__(self, user_sequences: Dict[int, List[AppInstallEvent]]):
595
+ self.user_sequences = user_sequences
596
+
597
+ def build_cooccurrence_matrix(self, min_cooccur: int = 5) -> Dict[Tuple[int, int], float]:
598
+ """构建App共现矩阵"""
599
+ from collections import Counter, defaultdict
600
+
601
+ app_user_count = Counter()
602
+ co_occurrence = defaultdict(int)
603
+
604
+ for user_id, events in self.user_sequences.items():
605
+ user_apps = list(set(e.app_id for e in events))
606
+ for app in user_apps:
607
+ app_user_count[app] += 1
608
+ for i in range(len(user_apps)):
609
+ for j in range(i + 1, min(len(user_apps), 50)):
610
+ pair = tuple(sorted([user_apps[i], user_apps[j]]))
611
+ co_occurrence[pair] += 1
612
+
613
+ edges = {}
614
+ for (app_i, app_j), count in co_occurrence.items():
615
+ if count >= min_cooccur:
616
+ weight = count / np.log(app_user_count[app_i] * app_user_count[app_j] + 1)
617
+ edges[(app_i, app_j)] = weight
618
+
619
+ logger.info(f"Built co-install graph: {len(edges)} edges")
620
+ return edges
621
+
622
+ def train_node2vec_embeddings(self, edges: dict, embed_dim: int = 32):
623
+ """用Node2Vec训练App图嵌入 (pip install node2vec networkx)"""
624
+ try:
625
+ import networkx as nx
626
+ from node2vec import Node2Vec
627
+ except ImportError:
628
+ logger.error("请安装: pip install node2vec networkx")
629
+ return None
630
+
631
+ G = nx.Graph()
632
+ for (app_i, app_j), weight in edges.items():
633
+ G.add_edge(app_i, app_j, weight=weight)
634
+
635
+ node2vec = Node2Vec(G, dimensions=embed_dim, walk_length=30, num_walks=200, p=1, q=0.5, workers=4)
636
+ model = node2vec.fit(window=10, min_count=1)
637
+
638
+ app_embeddings = {}
639
+ for node in G.nodes():
640
+ app_embeddings[node] = model.wv[str(node)]
641
+
642
+ logger.info(f"Node2Vec trained: {len(app_embeddings)} app embeddings")
643
+ return app_embeddings
644
+
645
+
646
+ # ============================================================
647
+ # 主流程示例
648
+ # ============================================================
649
+ def main():
650
+ logger.info("=" * 60)
651
+ logger.info("App 安装序列风控模型 — 完整训练流程")
652
+ logger.info("=" * 60)
653
+
654
+ # ---- 1. 加载数据 (替换为你的数据加载代码) ----
655
+ logger.info("Step 1: Loading data (demo with synthetic data)...")
656
+ np.random.seed(42)
657
+ num_users = 10000
658
+
659
+ records = []
660
+ labels = {}
661
+ for uid in range(num_users):
662
+ num_installs = np.random.randint(10, 200)
663
+ base_time = 1700000000
664
+ for i in range(num_installs):
665
+ records.append({
666
+ 'user_id': uid,
667
+ 'app_id': np.random.randint(1, CONFIG['app_vocab_size']),
668
+ 'app_category': np.random.randint(1, CONFIG['app_category_size']),
669
+ 'install_source': np.random.randint(1, CONFIG['app_source_size']),
670
+ 'install_timestamp': base_time + i * np.random.randint(3600, 86400 * 7),
671
+ })
672
+ labels[uid] = int(np.random.random() < 0.05) # 5% 坏账率
673
+
674
+ raw_df = pd.DataFrame(records)
675
+ logger.info(f" Users: {num_users}, Total installs: {len(records)}, "
676
+ f"Default rate: {sum(labels.values())/len(labels)*100:.1f}%")
677
+
678
+ # ---- 2. 预处理 ----
679
+ logger.info("Step 2: Preprocessing sequences...")
680
+ user_sequences = preprocess_app_sequence(raw_df)
681
+
682
+ # ---- 3. (可选) 构建App共现图 ----
683
+ logger.info("Step 3: Building app co-install graph...")
684
+ graph_builder = AppCoInstallGraph(user_sequences)
685
+ edges = graph_builder.build_cooccurrence_matrix(min_cooccur=3)
686
+
687
+ # ---- 4. CoLES 无监督预训练 ----
688
+ logger.info("Step 4: CoLES unsupervised pretraining...")
689
+ pretrained_model = pretrain_coles(user_sequences, epochs=5)
690
+
691
+ # ---- 5. 有监督微调 ----
692
+ logger.info("Step 5: Supervised fine-tuning...")
693
+ classifier, best_auc = finetune_classifier(
694
+ pretrained_model, user_sequences, labels, freeze_encoder=False
695
+ )
696
+
697
+ logger.info("=" * 60)
698
+ logger.info(f"Training complete! Best AUC: {best_auc:.4f}")
699
+ logger.info("=" * 60)
700
+
701
+
702
+ if __name__ == "__main__":
703
+ main()