ins-pricing 0.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. ins_pricing/README.md +60 -0
  2. ins_pricing/__init__.py +102 -0
  3. ins_pricing/governance/README.md +18 -0
  4. ins_pricing/governance/__init__.py +20 -0
  5. ins_pricing/governance/approval.py +93 -0
  6. ins_pricing/governance/audit.py +37 -0
  7. ins_pricing/governance/registry.py +99 -0
  8. ins_pricing/governance/release.py +159 -0
  9. ins_pricing/modelling/BayesOpt.py +146 -0
  10. ins_pricing/modelling/BayesOpt_USAGE.md +925 -0
  11. ins_pricing/modelling/BayesOpt_entry.py +575 -0
  12. ins_pricing/modelling/BayesOpt_incremental.py +731 -0
  13. ins_pricing/modelling/Explain_Run.py +36 -0
  14. ins_pricing/modelling/Explain_entry.py +539 -0
  15. ins_pricing/modelling/Pricing_Run.py +36 -0
  16. ins_pricing/modelling/README.md +33 -0
  17. ins_pricing/modelling/__init__.py +44 -0
  18. ins_pricing/modelling/bayesopt/__init__.py +98 -0
  19. ins_pricing/modelling/bayesopt/config_preprocess.py +303 -0
  20. ins_pricing/modelling/bayesopt/core.py +1476 -0
  21. ins_pricing/modelling/bayesopt/models.py +2196 -0
  22. ins_pricing/modelling/bayesopt/trainers.py +2446 -0
  23. ins_pricing/modelling/bayesopt/utils.py +1021 -0
  24. ins_pricing/modelling/cli_common.py +136 -0
  25. ins_pricing/modelling/explain/__init__.py +55 -0
  26. ins_pricing/modelling/explain/gradients.py +334 -0
  27. ins_pricing/modelling/explain/metrics.py +176 -0
  28. ins_pricing/modelling/explain/permutation.py +155 -0
  29. ins_pricing/modelling/explain/shap_utils.py +146 -0
  30. ins_pricing/modelling/notebook_utils.py +284 -0
  31. ins_pricing/modelling/plotting/__init__.py +45 -0
  32. ins_pricing/modelling/plotting/common.py +63 -0
  33. ins_pricing/modelling/plotting/curves.py +572 -0
  34. ins_pricing/modelling/plotting/diagnostics.py +139 -0
  35. ins_pricing/modelling/plotting/geo.py +362 -0
  36. ins_pricing/modelling/plotting/importance.py +121 -0
  37. ins_pricing/modelling/run_logging.py +133 -0
  38. ins_pricing/modelling/tests/conftest.py +8 -0
  39. ins_pricing/modelling/tests/test_cross_val_generic.py +66 -0
  40. ins_pricing/modelling/tests/test_distributed_utils.py +18 -0
  41. ins_pricing/modelling/tests/test_explain.py +56 -0
  42. ins_pricing/modelling/tests/test_geo_tokens_split.py +49 -0
  43. ins_pricing/modelling/tests/test_graph_cache.py +33 -0
  44. ins_pricing/modelling/tests/test_plotting.py +63 -0
  45. ins_pricing/modelling/tests/test_plotting_library.py +150 -0
  46. ins_pricing/modelling/tests/test_preprocessor.py +48 -0
  47. ins_pricing/modelling/watchdog_run.py +211 -0
  48. ins_pricing/pricing/README.md +44 -0
  49. ins_pricing/pricing/__init__.py +27 -0
  50. ins_pricing/pricing/calibration.py +39 -0
  51. ins_pricing/pricing/data_quality.py +117 -0
  52. ins_pricing/pricing/exposure.py +85 -0
  53. ins_pricing/pricing/factors.py +91 -0
  54. ins_pricing/pricing/monitoring.py +99 -0
  55. ins_pricing/pricing/rate_table.py +78 -0
  56. ins_pricing/production/__init__.py +21 -0
  57. ins_pricing/production/drift.py +30 -0
  58. ins_pricing/production/monitoring.py +143 -0
  59. ins_pricing/production/scoring.py +40 -0
  60. ins_pricing/reporting/README.md +20 -0
  61. ins_pricing/reporting/__init__.py +11 -0
  62. ins_pricing/reporting/report_builder.py +72 -0
  63. ins_pricing/reporting/scheduler.py +45 -0
  64. ins_pricing/setup.py +41 -0
  65. ins_pricing v2/__init__.py +23 -0
  66. ins_pricing v2/governance/__init__.py +20 -0
  67. ins_pricing v2/governance/approval.py +93 -0
  68. ins_pricing v2/governance/audit.py +37 -0
  69. ins_pricing v2/governance/registry.py +99 -0
  70. ins_pricing v2/governance/release.py +159 -0
  71. ins_pricing v2/modelling/Explain_Run.py +36 -0
  72. ins_pricing v2/modelling/Pricing_Run.py +36 -0
  73. ins_pricing v2/modelling/__init__.py +151 -0
  74. ins_pricing v2/modelling/cli_common.py +141 -0
  75. ins_pricing v2/modelling/config.py +249 -0
  76. ins_pricing v2/modelling/config_preprocess.py +254 -0
  77. ins_pricing v2/modelling/core.py +741 -0
  78. ins_pricing v2/modelling/data_container.py +42 -0
  79. ins_pricing v2/modelling/explain/__init__.py +55 -0
  80. ins_pricing v2/modelling/explain/gradients.py +334 -0
  81. ins_pricing v2/modelling/explain/metrics.py +176 -0
  82. ins_pricing v2/modelling/explain/permutation.py +155 -0
  83. ins_pricing v2/modelling/explain/shap_utils.py +146 -0
  84. ins_pricing v2/modelling/features.py +215 -0
  85. ins_pricing v2/modelling/model_manager.py +148 -0
  86. ins_pricing v2/modelling/model_plotting.py +463 -0
  87. ins_pricing v2/modelling/models.py +2203 -0
  88. ins_pricing v2/modelling/notebook_utils.py +294 -0
  89. ins_pricing v2/modelling/plotting/__init__.py +45 -0
  90. ins_pricing v2/modelling/plotting/common.py +63 -0
  91. ins_pricing v2/modelling/plotting/curves.py +572 -0
  92. ins_pricing v2/modelling/plotting/diagnostics.py +139 -0
  93. ins_pricing v2/modelling/plotting/geo.py +362 -0
  94. ins_pricing v2/modelling/plotting/importance.py +121 -0
  95. ins_pricing v2/modelling/run_logging.py +133 -0
  96. ins_pricing v2/modelling/tests/conftest.py +8 -0
  97. ins_pricing v2/modelling/tests/test_cross_val_generic.py +66 -0
  98. ins_pricing v2/modelling/tests/test_distributed_utils.py +18 -0
  99. ins_pricing v2/modelling/tests/test_explain.py +56 -0
  100. ins_pricing v2/modelling/tests/test_geo_tokens_split.py +49 -0
  101. ins_pricing v2/modelling/tests/test_graph_cache.py +33 -0
  102. ins_pricing v2/modelling/tests/test_plotting.py +63 -0
  103. ins_pricing v2/modelling/tests/test_plotting_library.py +150 -0
  104. ins_pricing v2/modelling/tests/test_preprocessor.py +48 -0
  105. ins_pricing v2/modelling/trainers.py +2447 -0
  106. ins_pricing v2/modelling/utils.py +1020 -0
  107. ins_pricing v2/modelling/watchdog_run.py +211 -0
  108. ins_pricing v2/pricing/__init__.py +27 -0
  109. ins_pricing v2/pricing/calibration.py +39 -0
  110. ins_pricing v2/pricing/data_quality.py +117 -0
  111. ins_pricing v2/pricing/exposure.py +85 -0
  112. ins_pricing v2/pricing/factors.py +91 -0
  113. ins_pricing v2/pricing/monitoring.py +99 -0
  114. ins_pricing v2/pricing/rate_table.py +78 -0
  115. ins_pricing v2/production/__init__.py +21 -0
  116. ins_pricing v2/production/drift.py +30 -0
  117. ins_pricing v2/production/monitoring.py +143 -0
  118. ins_pricing v2/production/scoring.py +40 -0
  119. ins_pricing v2/reporting/__init__.py +11 -0
  120. ins_pricing v2/reporting/report_builder.py +72 -0
  121. ins_pricing v2/reporting/scheduler.py +45 -0
  122. ins_pricing v2/scripts/BayesOpt_incremental.py +722 -0
  123. ins_pricing v2/scripts/Explain_entry.py +545 -0
  124. ins_pricing v2/scripts/__init__.py +1 -0
  125. ins_pricing v2/scripts/train.py +568 -0
  126. ins_pricing v2/setup.py +55 -0
  127. ins_pricing v2/smoke_test.py +28 -0
  128. ins_pricing-0.1.6.dist-info/METADATA +78 -0
  129. ins_pricing-0.1.6.dist-info/RECORD +169 -0
  130. ins_pricing-0.1.6.dist-info/WHEEL +5 -0
  131. ins_pricing-0.1.6.dist-info/top_level.txt +4 -0
  132. user_packages/__init__.py +105 -0
  133. user_packages legacy/BayesOpt.py +5659 -0
  134. user_packages legacy/BayesOpt_entry.py +513 -0
  135. user_packages legacy/BayesOpt_incremental.py +685 -0
  136. user_packages legacy/Pricing_Run.py +36 -0
  137. user_packages legacy/Try/BayesOpt Legacy251213.py +3719 -0
  138. user_packages legacy/Try/BayesOpt Legacy251215.py +3758 -0
  139. user_packages legacy/Try/BayesOpt lagecy251201.py +3506 -0
  140. user_packages legacy/Try/BayesOpt lagecy251218.py +3992 -0
  141. user_packages legacy/Try/BayesOpt legacy.py +3280 -0
  142. user_packages legacy/Try/BayesOpt.py +838 -0
  143. user_packages legacy/Try/BayesOptAll.py +1569 -0
  144. user_packages legacy/Try/BayesOptAllPlatform.py +909 -0
  145. user_packages legacy/Try/BayesOptCPUGPU.py +1877 -0
  146. user_packages legacy/Try/BayesOptSearch.py +830 -0
  147. user_packages legacy/Try/BayesOptSearchOrigin.py +829 -0
  148. user_packages legacy/Try/BayesOptV1.py +1911 -0
  149. user_packages legacy/Try/BayesOptV10.py +2973 -0
  150. user_packages legacy/Try/BayesOptV11.py +3001 -0
  151. user_packages legacy/Try/BayesOptV12.py +3001 -0
  152. user_packages legacy/Try/BayesOptV2.py +2065 -0
  153. user_packages legacy/Try/BayesOptV3.py +2209 -0
  154. user_packages legacy/Try/BayesOptV4.py +2342 -0
  155. user_packages legacy/Try/BayesOptV5.py +2372 -0
  156. user_packages legacy/Try/BayesOptV6.py +2759 -0
  157. user_packages legacy/Try/BayesOptV7.py +2832 -0
  158. user_packages legacy/Try/BayesOptV8Codex.py +2731 -0
  159. user_packages legacy/Try/BayesOptV8Gemini.py +2614 -0
  160. user_packages legacy/Try/BayesOptV9.py +2927 -0
  161. user_packages legacy/Try/BayesOpt_entry legacy.py +313 -0
  162. user_packages legacy/Try/ModelBayesOptSearch.py +359 -0
  163. user_packages legacy/Try/ResNetBayesOptSearch.py +249 -0
  164. user_packages legacy/Try/XgbBayesOptSearch.py +121 -0
  165. user_packages legacy/Try/xgbbayesopt.py +523 -0
  166. user_packages legacy/__init__.py +19 -0
  167. user_packages legacy/cli_common.py +124 -0
  168. user_packages legacy/notebook_utils.py +228 -0
  169. user_packages legacy/watchdog_run.py +202 -0
@@ -0,0 +1,3758 @@
1
+ from sklearn.metrics import log_loss, make_scorer, mean_tweedie_deviance
2
+ from sklearn.preprocessing import StandardScaler
3
+ from sklearn.neighbors import NearestNeighbors
4
+ from sklearn.model_selection import ShuffleSplit, cross_val_score # 1.2.2
5
+ import torch.distributed as dist
6
+ from torch.nn.parallel import DistributedDataParallel as DDP
7
+ from torch.nn.utils import clip_grad_norm_
8
+ from torch.cuda.amp import autocast, GradScaler
9
+ from torch.utils.data import Dataset, DataLoader, TensorDataset, DistributedSampler
10
+ import xgboost as xgb # 1.7.0
11
+ import torch.nn.functional as F
12
+ import torch.nn as nn
13
+ import torch # 版本: 1.10.1+cu111
14
+ import statsmodels.api as sm
15
+ import shap
16
+ import pandas as pd # 2.2.3
17
+ import optuna # 4.3.0
18
+ import numpy as np # 1.26.2
19
+ try:
20
+ from torch_geometric.nn import knn_graph
21
+ from torch_geometric.utils import add_self_loops, to_undirected
22
+ _PYG_AVAILABLE = True
23
+ except Exception:
24
+ knn_graph = None # type: ignore
25
+ add_self_loops = None # type: ignore
26
+ to_undirected = None # type: ignore
27
+ _PYG_AVAILABLE = False
28
+ try:
29
+ import pynndescent
30
+ _PYNN_AVAILABLE = True
31
+ except Exception:
32
+ pynndescent = None # type: ignore
33
+ _PYNN_AVAILABLE = False
34
+ import matplotlib.pyplot as plt
35
+ import joblib
36
+ import csv
37
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
38
+ from pathlib import Path
39
+ from dataclasses import dataclass
40
+ from contextlib import nullcontext
41
+ import os
42
+ import math
43
+ import gc
44
+ import copy
45
+ # 通过限制内存块拆分让 PyTorch 分配器减少碎片化,缓解显存 OOM
46
+ # 如需自定义,可通过环境变量 PYTORCH_CUDA_ALLOC_CONF 覆盖默认设置
47
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:256")
48
+
49
+
50
+ # 常量与工具模块
51
+ # =============================================================================
52
+ torch.backends.cudnn.benchmark = True
53
+ EPS = 1e-8
54
+
55
+
56
+ class IOUtils:
57
+ # 文件与路径处理的小工具集合。
58
+
59
+ @staticmethod
60
+ def csv_to_dict(file_path: str) -> List[Dict[str, Any]]:
61
+ with open(file_path, mode='r', encoding='utf-8') as file:
62
+ reader = csv.DictReader(file)
63
+ return [
64
+ dict(filter(lambda item: item[0] != '', row.items()))
65
+ for row in reader
66
+ ]
67
+
68
+ @staticmethod
69
+ def ensure_parent_dir(file_path: str) -> None:
70
+ # 若目标文件所在目录不存在则自动创建
71
+ directory = os.path.dirname(file_path)
72
+ if directory:
73
+ os.makedirs(directory, exist_ok=True)
74
+
75
+
76
+ class TrainingUtils:
77
+ # 训练阶段常用的小型辅助函数集合。
78
+
79
+ @staticmethod
80
+ def compute_batch_size(data_size: int, learning_rate: float, batch_num: int, minimum: int) -> int:
81
+ estimated = int((learning_rate / 1e-4) ** 0.5 *
82
+ (data_size / max(batch_num, 1)))
83
+ return max(1, min(data_size, max(minimum, estimated)))
84
+
85
+ @staticmethod
86
+ def tweedie_loss(pred, target, p=1.5, eps=1e-6, max_clip=1e6):
87
+ # 为确保稳定性先将预测值裁剪为正数
88
+ pred_clamped = torch.clamp(pred, min=eps)
89
+ if p == 1:
90
+ term1 = target * torch.log(target / pred_clamped + eps) # 泊松
91
+ term2 = -target + pred_clamped
92
+ term3 = 0
93
+ elif p == 0:
94
+ term1 = 0.5 * torch.pow(target - pred_clamped, 2) # 高斯
95
+ term2 = 0
96
+ term3 = 0
97
+ elif p == 2:
98
+ term1 = torch.log(pred_clamped / target + eps) # 伽马
99
+ term2 = -target / pred_clamped + 1
100
+ term3 = 0
101
+ else:
102
+ term1 = torch.pow(target, 2 - p) / ((1 - p) * (2 - p))
103
+ term2 = target * torch.pow(pred_clamped, 1 - p) / (1 - p)
104
+ term3 = torch.pow(pred_clamped, 2 - p) / (2 - p)
105
+ return torch.nan_to_num( # Tweedie 负对数似然(忽略常数项)
106
+ 2 * (term1 - term2 + term3),
107
+ nan=eps,
108
+ posinf=max_clip,
109
+ neginf=-max_clip
110
+ )
111
+
112
+ @staticmethod
113
+ def free_cuda() -> None:
114
+ print(">>> Moving all models to CPU...")
115
+ for obj in gc.get_objects():
116
+ try:
117
+ if hasattr(obj, "to") and callable(obj.to):
118
+ obj.to("cpu")
119
+ except Exception:
120
+ pass
121
+
122
+ print(">>> Deleting tensors, optimizers, dataloaders...")
123
+ gc.collect()
124
+
125
+ print(">>> Emptying CUDA cache...")
126
+ torch.cuda.empty_cache()
127
+ torch.cuda.synchronize()
128
+
129
+ print(">>> CUDA memory freed.")
130
+
131
+
132
+ class DistributedUtils:
133
+ _cached_state: Optional[tuple] = None
134
+
135
+ @staticmethod
136
+ def setup_ddp():
137
+ """初始化用于分布式训练的 DDP 进程组。"""
138
+ if dist.is_initialized():
139
+ if DistributedUtils._cached_state is None:
140
+ rank = dist.get_rank()
141
+ world_size = dist.get_world_size()
142
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
143
+ DistributedUtils._cached_state = (
144
+ True,
145
+ local_rank,
146
+ rank,
147
+ world_size,
148
+ )
149
+ return DistributedUtils._cached_state
150
+
151
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
152
+ rank = int(os.environ["RANK"])
153
+ world_size = int(os.environ["WORLD_SIZE"])
154
+ local_rank = int(os.environ["LOCAL_RANK"])
155
+
156
+ if torch.cuda.is_available():
157
+ torch.cuda.set_device(local_rank)
158
+
159
+ dist.init_process_group(backend="nccl", init_method="env://")
160
+ print(
161
+ f">>> DDP Initialized: Rank {rank}/{world_size}, Local Rank {local_rank}")
162
+ DistributedUtils._cached_state = (
163
+ True,
164
+ local_rank,
165
+ rank,
166
+ world_size,
167
+ )
168
+ return DistributedUtils._cached_state
169
+ else:
170
+ print(
171
+ f">>> DDP Setup Failed: RANK or WORLD_SIZE not found in env. Keys found: {list(os.environ.keys())}")
172
+ return False, 0, 0, 1
173
+
174
+ @staticmethod
175
+ def cleanup_ddp():
176
+ """销毁已创建的 DDP 进程组并清理本地缓存状态。"""
177
+ if dist.is_initialized():
178
+ dist.destroy_process_group()
179
+ DistributedUtils._cached_state = None
180
+
181
+ @staticmethod
182
+ def is_main_process():
183
+ return not dist.is_initialized() or dist.get_rank() == 0
184
+
185
+ @staticmethod
186
+ def world_size() -> int:
187
+ return dist.get_world_size() if dist.is_initialized() else 1
188
+
189
+
190
+ class PlotUtils:
191
+ # 多种模型共享的绘图辅助工具。
192
+
193
+ @staticmethod
194
+ def split_data(data: pd.DataFrame, col_nme: str, wgt_nme: str, n_bins: int = 10) -> pd.DataFrame:
195
+ data_sorted = data.sort_values(by=col_nme, ascending=True).copy()
196
+ data_sorted['cum_weight'] = data_sorted[wgt_nme].cumsum()
197
+ w_sum = data_sorted[wgt_nme].sum()
198
+ if w_sum <= EPS:
199
+ data_sorted.loc[:, 'bins'] = 0
200
+ else:
201
+ data_sorted.loc[:, 'bins'] = np.floor(
202
+ data_sorted['cum_weight'] * float(n_bins) / w_sum
203
+ )
204
+ data_sorted.loc[(data_sorted['bins'] == n_bins),
205
+ 'bins'] = n_bins - 1
206
+ return data_sorted.groupby(['bins'], observed=True).sum(numeric_only=True)
207
+
208
+ @staticmethod
209
+ def plot_lift_ax(ax, plot_data, title, pred_label='Predicted', act_label='Actual', weight_label='Earned Exposure'):
210
+ ax.plot(plot_data.index, plot_data['act_v'],
211
+ label=act_label, color='red')
212
+ ax.plot(plot_data.index, plot_data['exp_v'],
213
+ label=pred_label, color='blue')
214
+ ax.set_title(title, fontsize=8)
215
+ ax.set_xticks(plot_data.index)
216
+ ax.set_xticklabels(plot_data.index, rotation=90, fontsize=6)
217
+ ax.tick_params(axis='y', labelsize=6)
218
+ ax.legend(loc='upper left', fontsize=5, frameon=False)
219
+ ax.margins(0.05)
220
+ ax2 = ax.twinx()
221
+ ax2.bar(plot_data.index, plot_data['weight'],
222
+ alpha=0.5, color='seagreen',
223
+ label=weight_label)
224
+ ax2.tick_params(axis='y', labelsize=6)
225
+ ax2.legend(loc='upper right', fontsize=5, frameon=False)
226
+
227
+ @staticmethod
228
+ def plot_dlift_ax(ax, plot_data, title, label1, label2, act_label='Actual', weight_label='Earned Exposure'):
229
+ ax.plot(plot_data.index, plot_data['act_v'],
230
+ label=act_label, color='red')
231
+ ax.plot(plot_data.index, plot_data['exp_v1'],
232
+ label=label1, color='blue')
233
+ ax.plot(plot_data.index, plot_data['exp_v2'],
234
+ label=label2, color='black')
235
+ ax.set_title(title, fontsize=8)
236
+ ax.set_xticks(plot_data.index)
237
+ ax.set_xticklabels(plot_data.index, rotation=90, fontsize=6)
238
+ ax.set_xlabel(f'{label1} / {label2}', fontsize=6)
239
+ ax.tick_params(axis='y', labelsize=6)
240
+ ax.legend(loc='upper left', fontsize=5, frameon=False)
241
+ ax.margins(0.1)
242
+ ax2 = ax.twinx()
243
+ ax2.bar(plot_data.index, plot_data['weight'],
244
+ alpha=0.5, color='seagreen',
245
+ label=weight_label)
246
+ ax2.tick_params(axis='y', labelsize=6)
247
+ ax2.legend(loc='upper right', fontsize=5, frameon=False)
248
+
249
+ @staticmethod
250
+ def plot_lift_list(pred_model, w_pred_list, w_act_list,
251
+ weight_list, tgt_nme, n_bins: int = 10,
252
+ fig_nme: str = 'Lift Chart'):
253
+ lift_data = pd.DataFrame()
254
+ lift_data.loc[:, 'pred'] = pred_model
255
+ lift_data.loc[:, 'w_pred'] = w_pred_list
256
+ lift_data.loc[:, 'act'] = w_act_list
257
+ lift_data.loc[:, 'weight'] = weight_list
258
+ plot_data = PlotUtils.split_data(lift_data, 'pred', 'weight', n_bins)
259
+ plot_data['exp_v'] = plot_data['w_pred'] / plot_data['weight']
260
+ plot_data['act_v'] = plot_data['act'] / plot_data['weight']
261
+ plot_data.reset_index(inplace=True)
262
+
263
+ fig = plt.figure(figsize=(7, 5))
264
+ ax = fig.add_subplot(111)
265
+ PlotUtils.plot_lift_ax(ax, plot_data, f'Lift Chart of {tgt_nme}')
266
+ plt.subplots_adjust(wspace=0.3)
267
+
268
+ save_path = os.path.join(
269
+ os.getcwd(), 'plot', f'05_{tgt_nme}_{fig_nme}.png')
270
+ IOUtils.ensure_parent_dir(save_path)
271
+ plt.savefig(save_path, dpi=300)
272
+ plt.close(fig)
273
+
274
+ @staticmethod
275
+ def plot_dlift_list(pred_model_1, pred_model_2,
276
+ model_nme_1, model_nme_2,
277
+ tgt_nme,
278
+ w_list, w_act_list, n_bins: int = 10,
279
+ fig_nme: str = 'Double Lift Chart'):
280
+ lift_data = pd.DataFrame()
281
+ lift_data.loc[:, 'pred1'] = pred_model_1
282
+ lift_data.loc[:, 'pred2'] = pred_model_2
283
+ lift_data.loc[:, 'diff_ly'] = lift_data['pred1'] / lift_data['pred2']
284
+ lift_data.loc[:, 'act'] = w_act_list
285
+ lift_data.loc[:, 'weight'] = w_list
286
+ lift_data.loc[:, 'w_pred1'] = lift_data['pred1'] * lift_data['weight']
287
+ lift_data.loc[:, 'w_pred2'] = lift_data['pred2'] * lift_data['weight']
288
+ plot_data = PlotUtils.split_data(
289
+ lift_data, 'diff_ly', 'weight', n_bins)
290
+ plot_data['exp_v1'] = plot_data['w_pred1'] / plot_data['act']
291
+ plot_data['exp_v2'] = plot_data['w_pred2'] / plot_data['act']
292
+ plot_data['act_v'] = plot_data['act']/plot_data['act']
293
+ plot_data.reset_index(inplace=True)
294
+
295
+ fig = plt.figure(figsize=(7, 5))
296
+ ax = fig.add_subplot(111)
297
+ PlotUtils.plot_dlift_ax(
298
+ ax, plot_data, f'Double Lift Chart of {tgt_nme}', model_nme_1, model_nme_2)
299
+ plt.subplots_adjust(bottom=0.25, top=0.95, right=0.8)
300
+
301
+ save_path = os.path.join(
302
+ os.getcwd(), 'plot', f'06_{tgt_nme}_{fig_nme}.png')
303
+ IOUtils.ensure_parent_dir(save_path)
304
+ plt.savefig(save_path, dpi=300)
305
+ plt.close(fig)
306
+
307
+
308
+ # 向后兼容的函数式封装
309
+ def csv_to_dict(file_path: str) -> List[Dict[str, Any]]:
310
+ return IOUtils.csv_to_dict(file_path)
311
+
312
+
313
+ def ensure_parent_dir(file_path: str) -> None:
314
+ IOUtils.ensure_parent_dir(file_path)
315
+
316
+
317
+ def compute_batch_size(data_size: int, learning_rate: float, batch_num: int, minimum: int) -> int:
318
+ return TrainingUtils.compute_batch_size(data_size, learning_rate, batch_num, minimum)
319
+
320
+
321
+ # 定义在 PyTorch 环境下的 Tweedie 偏差损失函数
322
+ # 参考文档:https://scikit-learn.org/stable/modules/model_evaluation.html#mean-poisson-gamma-and-tweedie-deviances
323
+ def tweedie_loss(pred, target, p=1.5, eps=1e-6, max_clip=1e6):
324
+ return TrainingUtils.tweedie_loss(pred, target, p=p, eps=eps, max_clip=max_clip)
325
+
326
+
327
+ # 定义释放CUDA内存函数
328
+ def free_cuda():
329
+ TrainingUtils.free_cuda()
330
+
331
+
332
+ class TorchTrainerMixin:
333
+ # 面向 Torch 表格训练器的共享工具方法。
334
+
335
+ def _device_type(self) -> str:
336
+ return getattr(self, "device", torch.device("cpu")).type
337
+
338
+ def _build_dataloader(self,
339
+ dataset,
340
+ N: int,
341
+ base_bs_gpu: tuple,
342
+ base_bs_cpu: tuple,
343
+ min_bs: int = 64,
344
+ target_effective_cuda: int = 1024,
345
+ target_effective_cpu: int = 512,
346
+ large_threshold: int = 200_000,
347
+ mid_threshold: int = 50_000):
348
+ batch_size = TrainingUtils.compute_batch_size(
349
+ data_size=len(dataset),
350
+ learning_rate=self.learning_rate,
351
+ batch_num=self.batch_num,
352
+ minimum=min_bs
353
+ )
354
+ gpu_large, gpu_mid, gpu_small = base_bs_gpu
355
+ cpu_mid, cpu_small = base_bs_cpu
356
+
357
+ if self._device_type() == 'cuda':
358
+ device_count = torch.cuda.device_count()
359
+ if getattr(self, "is_ddp_enabled", False):
360
+ device_count = 1
361
+ # 多卡环境下,适当增大最小批量,确保每张卡都能分到足够数据
362
+ if device_count > 1:
363
+ min_bs = min_bs * device_count
364
+ print(
365
+ f">>> Multi-GPU detected: {device_count} devices. Adjusted min_bs to {min_bs}.")
366
+
367
+ if N > large_threshold:
368
+ base_bs = gpu_large * device_count
369
+ elif N > mid_threshold:
370
+ base_bs = gpu_mid * device_count
371
+ else:
372
+ base_bs = gpu_small * device_count
373
+ else:
374
+ base_bs = cpu_mid if N > mid_threshold else cpu_small
375
+
376
+ # 重新计算 batch_size,确保不小于调整后的 min_bs
377
+ batch_size = TrainingUtils.compute_batch_size(
378
+ data_size=len(dataset),
379
+ learning_rate=self.learning_rate,
380
+ batch_num=self.batch_num,
381
+ minimum=min_bs
382
+ )
383
+ batch_size = min(batch_size, base_bs, N)
384
+
385
+ target_effective_bs = target_effective_cuda if self._device_type(
386
+ ) == 'cuda' else target_effective_cpu
387
+ if getattr(self, "is_ddp_enabled", False):
388
+ world_size = max(1, DistributedUtils.world_size())
389
+ target_effective_bs = max(1, target_effective_bs // world_size)
390
+ accum_steps = max(1, target_effective_bs // batch_size)
391
+
392
+ # Linux (posix) 采用 fork 更高效;Windows (nt) 使用 spawn,开销更大。
393
+ if os.name == 'nt':
394
+ workers = 0
395
+ else:
396
+ workers = min(8, os.cpu_count() or 1)
397
+ if getattr(self, "is_ddp_enabled", False):
398
+ workers = 0 # DDP 下禁用多 worker,防止子进程冲突
399
+ print(
400
+ f">>> DataLoader config: Batch Size={batch_size}, Accum Steps={accum_steps}, Workers={workers}")
401
+ sampler = None
402
+ if dist.is_initialized():
403
+ sampler = DistributedSampler(dataset, shuffle=True)
404
+ shuffle = False # 交由 DistributedSampler 完成随机打乱
405
+ else:
406
+ shuffle = True
407
+
408
+ persistent = workers > 0
409
+ if getattr(self, "is_ddp_enabled", False):
410
+ persistent = False # 防止 DDP/pruning 提前退出导致 worker 状态异常
411
+ dataloader = DataLoader(
412
+ dataset,
413
+ batch_size=batch_size,
414
+ shuffle=shuffle,
415
+ sampler=sampler,
416
+ num_workers=workers,
417
+ pin_memory=(self._device_type() == 'cuda'),
418
+ persistent_workers=persistent,
419
+ )
420
+ return dataloader, accum_steps
421
+
422
+ def _compute_weighted_loss(self, y_pred, y_true, weights, apply_softplus: bool = False):
423
+ task = getattr(self, "task_type", "regression")
424
+ if task == 'classification':
425
+ loss_fn = nn.BCEWithLogitsLoss(reduction='none')
426
+ losses = loss_fn(y_pred, y_true).view(-1)
427
+ else:
428
+ if apply_softplus:
429
+ y_pred = F.softplus(y_pred)
430
+ y_pred = torch.clamp(y_pred, min=1e-6)
431
+ power = getattr(self, "tw_power", 1.5)
432
+ losses = tweedie_loss(y_pred, y_true, p=power).view(-1)
433
+ weighted_loss = (losses * weights.view(-1)).sum() / \
434
+ torch.clamp(weights.sum(), min=EPS)
435
+ return weighted_loss
436
+
437
+ def _early_stop_update(self, val_loss, best_loss, best_state, patience_counter, model,
438
+ ignore_keys: Optional[List[str]] = None):
439
+ if val_loss < best_loss:
440
+ ignore_keys = ignore_keys or []
441
+ state_dict = {
442
+ k: (v.clone() if isinstance(v, torch.Tensor) else copy.deepcopy(v))
443
+ for k, v in model.state_dict().items()
444
+ if not any(k.startswith(ignore_key) for ignore_key in ignore_keys)
445
+ }
446
+ return val_loss, state_dict, 0, False
447
+ patience_counter += 1
448
+ should_stop = best_state is not None and patience_counter >= getattr(
449
+ self, "patience", 0)
450
+ return best_loss, best_state, patience_counter, should_stop
451
+
452
+ def _train_model(self,
453
+ model,
454
+ dataloader,
455
+ accum_steps,
456
+ optimizer,
457
+ scaler,
458
+ forward_fn,
459
+ val_forward_fn=None,
460
+ apply_softplus: bool = False,
461
+ clip_fn=None,
462
+ trial: Optional[optuna.trial.Trial] = None):
463
+ device_type = self._device_type()
464
+ best_loss = float('inf')
465
+ best_state = None
466
+ patience_counter = 0
467
+ stop_training = False
468
+
469
+ is_ddp_model = isinstance(model, DDP)
470
+
471
+ for epoch in range(1, getattr(self, "epochs", 1) + 1):
472
+ if hasattr(self, 'dataloader_sampler') and self.dataloader_sampler is not None:
473
+ self.dataloader_sampler.set_epoch(epoch)
474
+
475
+ model.train()
476
+ optimizer.zero_grad()
477
+
478
+ for step, batch in enumerate(dataloader):
479
+ is_update_step = ((step + 1) % accum_steps == 0) or \
480
+ ((step + 1) == len(dataloader))
481
+ sync_cm = model.no_sync if (
482
+ is_ddp_model and not is_update_step) else nullcontext
483
+
484
+ with sync_cm():
485
+ with autocast(enabled=(device_type == 'cuda')):
486
+ y_pred, y_true, w = forward_fn(batch)
487
+ weighted_loss = self._compute_weighted_loss(
488
+ y_pred, y_true, w, apply_softplus=apply_softplus)
489
+ loss_for_backward = weighted_loss / accum_steps
490
+
491
+ scaler.scale(loss_for_backward).backward()
492
+
493
+ if is_update_step:
494
+ if clip_fn is not None:
495
+ clip_fn()
496
+ scaler.step(optimizer)
497
+ scaler.update()
498
+ optimizer.zero_grad()
499
+
500
+ if val_forward_fn is not None:
501
+ should_compute_val = (not dist.is_initialized()
502
+ or DistributedUtils.is_main_process())
503
+ val_device = getattr(self, "device", torch.device("cpu"))
504
+ if not isinstance(val_device, torch.device):
505
+ val_device = torch.device(val_device)
506
+ loss_tensor_device = val_device if device_type == 'cuda' else torch.device(
507
+ "cpu")
508
+ val_loss_tensor = torch.zeros(1, device=loss_tensor_device)
509
+
510
+ if should_compute_val:
511
+ model.eval()
512
+ with torch.no_grad(), autocast(enabled=(device_type == 'cuda')):
513
+ val_result = val_forward_fn()
514
+ if isinstance(val_result, tuple) and len(val_result) == 3:
515
+ y_val_pred, y_val_true, w_val = val_result
516
+ val_weighted_loss = self._compute_weighted_loss(
517
+ y_val_pred, y_val_true, w_val, apply_softplus=apply_softplus)
518
+ else:
519
+ val_weighted_loss = val_result
520
+ val_loss_tensor[0] = float(val_weighted_loss)
521
+
522
+ if dist.is_initialized():
523
+ dist.broadcast(val_loss_tensor, src=0)
524
+ val_weighted_loss = float(val_loss_tensor.item())
525
+
526
+ best_loss, best_state, patience_counter, stop_training = self._early_stop_update(
527
+ val_weighted_loss, best_loss, best_state, patience_counter, model)
528
+
529
+ prune_flag = False
530
+ is_main_rank = DistributedUtils.is_main_process()
531
+ if trial is not None and (not dist.is_initialized() or is_main_rank):
532
+ trial.report(val_weighted_loss, epoch)
533
+ prune_flag = trial.should_prune()
534
+
535
+ if dist.is_initialized():
536
+ prune_device = getattr(self, "device", torch.device("cpu"))
537
+ if not isinstance(prune_device, torch.device):
538
+ prune_device = torch.device(prune_device)
539
+ prune_tensor = torch.zeros(1, device=prune_device)
540
+ if is_main_rank:
541
+ prune_tensor.fill_(1 if prune_flag else 0)
542
+ dist.broadcast(prune_tensor, src=0)
543
+ prune_flag = bool(prune_tensor.item())
544
+
545
+ if prune_flag:
546
+ raise optuna.TrialPruned()
547
+
548
+ if stop_training:
549
+ break
550
+
551
+ return best_state
552
+
553
+
554
+ # =============================================================================
555
+ # 绘图辅助模块
556
+ # =============================================================================
557
+
558
+ def split_data(data, col_nme, wgt_nme, n_bins=10):
559
+ return PlotUtils.split_data(data, col_nme, wgt_nme, n_bins)
560
+
561
+ # 定义提纯曲线(Lift)绘制函数
562
+
563
+
564
+ def plot_lift_list(pred_model, w_pred_list, w_act_list,
565
+ weight_list, tgt_nme, n_bins=10,
566
+ fig_nme='Lift Chart'):
567
+ return PlotUtils.plot_lift_list(pred_model, w_pred_list, w_act_list,
568
+ weight_list, tgt_nme, n_bins, fig_nme)
569
+
570
+ # 定义双提纯曲线绘制函数
571
+
572
+
573
+ def plot_dlift_list(pred_model_1, pred_model_2,
574
+ model_nme_1, model_nme_2,
575
+ tgt_nme,
576
+ w_list, w_act_list, n_bins=10,
577
+ fig_nme='Double Lift Chart'):
578
+ return PlotUtils.plot_dlift_list(pred_model_1, pred_model_2,
579
+ model_nme_1, model_nme_2,
580
+ tgt_nme, w_list, w_act_list,
581
+ n_bins, fig_nme)
582
+
583
+
584
+ # =============================================================================
585
+ # ResNet 模型与 sklearn 风格封装
586
+ # =============================================================================
587
+
588
+ # 开始定义ResNet模型结构
589
+ # 残差块:两层线性 + ReLU + 残差连接
590
+ # ResBlock 继承 nn.Module
591
+ class ResBlock(nn.Module):
592
+ def __init__(self, dim: int, dropout: float = 0.1,
593
+ use_layernorm: bool = False, residual_scale: float = 0.1
594
+ ):
595
+ super().__init__()
596
+ self.use_layernorm = use_layernorm
597
+
598
+ if use_layernorm:
599
+ Norm = nn.LayerNorm # 对最后一维做归一化
600
+ else:
601
+ def Norm(d): return nn.BatchNorm1d(d) # 保留一个开关,想试 BN 时也能用
602
+
603
+ self.norm1 = Norm(dim)
604
+ self.fc1 = nn.Linear(dim, dim, bias=True)
605
+ self.act = nn.ReLU(inplace=True)
606
+ self.dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
607
+ # 如需在第二层后追加归一化,可启用下行:self.norm2 = Norm(dim)
608
+ self.fc2 = nn.Linear(dim, dim, bias=True)
609
+
610
+ # 残差缩放,防止一开始就把主干搞炸
611
+ self.res_scale = nn.Parameter(
612
+ torch.tensor(residual_scale, dtype=torch.float32)
613
+ )
614
+
615
+ def forward(self, x):
616
+ # 前置激活结构
617
+ out = self.norm1(x)
618
+ out = self.fc1(out)
619
+ out = self.act(out)
620
+ out = self.dropout(out)
621
+ # 若启用了第二次归一化,在此处调用:out = self.norm2(out)
622
+ out = self.fc2(out)
623
+ # 残差缩放再相加
624
+ return x + self.res_scale * out
625
+
626
+ # ResNetSequential 继承 nn.Module,定义整个网络结构
627
+
628
+
629
+ class ResNetSequential(nn.Module):
630
+ # 输入张量形状:(batch, input_dim)
631
+ # 网络结构:全连接 + 归一化 + ReLU,再堆叠若干残差块,最后输出 Softplus
632
+
633
+ def __init__(self, input_dim: int, hidden_dim: int = 64, block_num: int = 2,
634
+ use_layernorm: bool = True, dropout: float = 0.1,
635
+ residual_scale: float = 0.1, task_type: str = 'regression'):
636
+ super(ResNetSequential, self).__init__()
637
+
638
+ self.net = nn.Sequential()
639
+ self.net.add_module('fc1', nn.Linear(input_dim, hidden_dim))
640
+
641
+ # 如需在首层后增加显式归一化,可按需启用下方示例代码:
642
+ # 如果使用 LayerNorm:
643
+ # self.net.add_module('norm1', nn.LayerNorm(hidden_dim))
644
+ # 否则可改用 BatchNorm:
645
+ # self.net.add_module('norm1', nn.BatchNorm1d(hidden_dim))
646
+
647
+ # 如果希望在残差块前加入 ReLU,可启用:self.net.add_module('relu1', nn.ReLU(inplace=True))
648
+
649
+ # 多个残差块
650
+ for i in range(block_num):
651
+ self.net.add_module(
652
+ f'ResBlk_{i+1}',
653
+ ResBlock(
654
+ hidden_dim,
655
+ dropout=dropout,
656
+ use_layernorm=use_layernorm,
657
+ residual_scale=residual_scale)
658
+ )
659
+
660
+ self.net.add_module('fc_out', nn.Linear(hidden_dim, 1))
661
+
662
+ if task_type == 'classification':
663
+ self.net.add_module('softplus', nn.Identity())
664
+ else:
665
+ self.net.add_module('softplus', nn.Softplus())
666
+
667
+ def forward(self, x):
668
+ if self.training and not hasattr(self, '_printed_device'):
669
+ print(f">>> ResNetSequential executing on device: {x.device}")
670
+ self._printed_device = True
671
+ return self.net(x)
672
+
673
+ # 定义ResNet模型的Scikit-Learn接口类
674
+
675
+
676
+ class ResNetSklearn(TorchTrainerMixin, nn.Module):
677
+ def __init__(self, model_nme: str, input_dim: int, hidden_dim: int = 64,
678
+ block_num: int = 2, batch_num: int = 100, epochs: int = 100,
679
+ task_type: str = 'regression',
680
+ tweedie_power: float = 1.5, learning_rate: float = 0.01, patience: int = 10,
681
+ use_layernorm: bool = True, dropout: float = 0.1,
682
+ residual_scale: float = 0.1,
683
+ use_data_parallel: bool = True,
684
+ use_ddp: bool = False):
685
+ super(ResNetSklearn, self).__init__()
686
+
687
+ self.use_ddp = use_ddp
688
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = (
689
+ False, 0, 0, 1)
690
+
691
+ if self.use_ddp:
692
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = DistributedUtils.setup_ddp()
693
+
694
+ self.input_dim = input_dim
695
+ self.hidden_dim = hidden_dim
696
+ self.block_num = block_num
697
+ self.batch_num = batch_num
698
+ self.epochs = epochs
699
+ self.task_type = task_type
700
+ self.model_nme = model_nme
701
+ self.learning_rate = learning_rate
702
+ self.patience = patience
703
+ self.use_layernorm = use_layernorm
704
+ self.dropout = dropout
705
+ self.residual_scale = residual_scale
706
+
707
+ # 设备选择:cuda > mps > cpu
708
+ if self.is_ddp_enabled:
709
+ self.device = torch.device(f'cuda:{self.local_rank}')
710
+ elif torch.cuda.is_available():
711
+ self.device = torch.device('cuda')
712
+ elif torch.backends.mps.is_available():
713
+ self.device = torch.device('mps')
714
+ else:
715
+ self.device = torch.device('cpu')
716
+
717
+ # Tweedie 幂指数设定(分类时不使用)
718
+ if self.task_type == 'classification':
719
+ self.tw_power = None
720
+ elif 'f' in self.model_nme:
721
+ self.tw_power = 1
722
+ elif 's' in self.model_nme:
723
+ self.tw_power = 2
724
+ else:
725
+ self.tw_power = tweedie_power
726
+
727
+ # 搭建网络(先在 CPU 上建好)
728
+ core = ResNetSequential(
729
+ self.input_dim,
730
+ self.hidden_dim,
731
+ self.block_num,
732
+ use_layernorm=self.use_layernorm,
733
+ dropout=self.dropout,
734
+ residual_scale=self.residual_scale,
735
+ task_type=self.task_type
736
+ )
737
+
738
+ # ===== 多卡支持:DataParallel vs DistributedDataParallel =====
739
+ if self.is_ddp_enabled:
740
+ core = core.to(self.device)
741
+ core = DDP(core, device_ids=[
742
+ self.local_rank], output_device=self.local_rank)
743
+ elif use_data_parallel and (self.device.type == 'cuda') and (torch.cuda.device_count() > 1):
744
+ core = nn.DataParallel(core, device_ids=list(
745
+ range(torch.cuda.device_count())))
746
+ # DataParallel 会把输入 scatter 到多卡上,但“主设备”仍然是 cuda:0
747
+ self.device = torch.device('cuda')
748
+
749
+ self.resnet = core.to(self.device)
750
+
751
+ # ================ 内部工具 ================
752
+ def _build_train_val_tensors(self, X_train, y_train, w_train, X_val, y_val, w_val):
753
+ X_tensor = torch.tensor(X_train.values, dtype=torch.float32)
754
+ y_tensor = torch.tensor(
755
+ y_train.values, dtype=torch.float32).view(-1, 1)
756
+ w_tensor = torch.tensor(w_train.values, dtype=torch.float32).view(
757
+ -1, 1) if w_train is not None else torch.ones_like(y_tensor)
758
+
759
+ has_val = X_val is not None and y_val is not None
760
+ if has_val:
761
+ X_val_tensor = torch.tensor(X_val.values, dtype=torch.float32)
762
+ y_val_tensor = torch.tensor(
763
+ y_val.values, dtype=torch.float32).view(-1, 1)
764
+ w_val_tensor = torch.tensor(w_val.values, dtype=torch.float32).view(
765
+ -1, 1) if w_val is not None else torch.ones_like(y_val_tensor)
766
+ else:
767
+ X_val_tensor = y_val_tensor = w_val_tensor = None
768
+ return X_tensor, y_tensor, w_tensor, X_val_tensor, y_val_tensor, w_val_tensor, has_val
769
+
770
+ def forward(self, x):
771
+ # 处理 SHAP 的 NumPy 输入
772
+ if isinstance(x, np.ndarray):
773
+ x_tensor = torch.tensor(x, dtype=torch.float32)
774
+ else:
775
+ x_tensor = x
776
+
777
+ x_tensor = x_tensor.to(self.device)
778
+ y_pred = self.resnet(x_tensor)
779
+ return y_pred
780
+
781
+ # ---------------- 训练 ----------------
782
+
783
+ def fit(self, X_train, y_train, w_train=None,
784
+ X_val=None, y_val=None, w_val=None, trial=None):
785
+
786
+ X_tensor, y_tensor, w_tensor, X_val_tensor, y_val_tensor, w_val_tensor, has_val = \
787
+ self._build_train_val_tensors(
788
+ X_train, y_train, w_train, X_val, y_val, w_val)
789
+
790
+ dataset = TensorDataset(X_tensor, y_tensor, w_tensor)
791
+ dataloader, accum_steps = self._build_dataloader(
792
+ dataset,
793
+ N=X_tensor.shape[0],
794
+ base_bs_gpu=(2048, 1024, 512),
795
+ base_bs_cpu=(256, 128),
796
+ min_bs=64,
797
+ target_effective_cuda=2048,
798
+ target_effective_cpu=1024
799
+ )
800
+
801
+ # 在每个 epoch 开始前设置 sampler 的 epoch,以保证 shuffle 的随机性
802
+ if self.is_ddp_enabled and hasattr(dataloader.sampler, 'set_epoch'):
803
+ self.dataloader_sampler = dataloader.sampler
804
+ else:
805
+ self.dataloader_sampler = None
806
+
807
+ # === 4. 优化器与 AMP ===
808
+ self.optimizer = torch.optim.Adam(
809
+ self.resnet.parameters(), lr=self.learning_rate)
810
+ self.scaler = GradScaler(enabled=(self.device.type == 'cuda'))
811
+
812
+ X_val_dev = y_val_dev = w_val_dev = None
813
+ val_dataloader = None
814
+ if has_val:
815
+ # 构建验证集 DataLoader
816
+ val_dataset = TensorDataset(
817
+ X_val_tensor, y_val_tensor, w_val_tensor)
818
+ # 验证阶段无需反向传播,可适当放大批量以提高吞吐
819
+ val_bs = accum_steps * dataloader.batch_size
820
+
821
+ # 验证集的 worker 数沿用相同的分配逻辑
822
+ if os.name == 'nt':
823
+ val_workers = 0
824
+ else:
825
+ val_workers = min(4, os.cpu_count() or 1)
826
+ if getattr(self, "is_ddp_enabled", False):
827
+ val_workers = 0 # DDP 下禁用多 worker,防止子进程冲突
828
+
829
+ val_dataloader = DataLoader(
830
+ val_dataset,
831
+ batch_size=val_bs,
832
+ shuffle=False,
833
+ num_workers=val_workers,
834
+ pin_memory=(self.device.type == 'cuda'),
835
+ persistent_workers=val_workers > 0,
836
+ )
837
+ # 验证集通常不需要 DDP Sampler,因为我们只在主进程验证或汇总验证结果
838
+ # 但为了简单起见,这里保持单卡验证或主进程验证
839
+
840
+ is_data_parallel = isinstance(self.resnet, nn.DataParallel)
841
+
842
+ def forward_fn(batch):
843
+ X_batch, y_batch, w_batch = batch
844
+
845
+ if not is_data_parallel:
846
+ X_batch = X_batch.to(self.device, non_blocking=True)
847
+ # 目标值与权重始终与主设备保持一致,便于后续损失计算
848
+ y_batch = y_batch.to(self.device, non_blocking=True)
849
+ w_batch = w_batch.to(self.device, non_blocking=True)
850
+
851
+ y_pred = self.resnet(X_batch)
852
+ return y_pred, y_batch, w_batch
853
+
854
+ def val_forward_fn():
855
+ total_loss = 0.0
856
+ total_weight = 0.0
857
+ for batch in val_dataloader:
858
+ X_b, y_b, w_b = batch
859
+ if not is_data_parallel:
860
+ X_b = X_b.to(self.device, non_blocking=True)
861
+ y_b = y_b.to(self.device, non_blocking=True)
862
+ w_b = w_b.to(self.device, non_blocking=True)
863
+
864
+ y_pred = self.resnet(X_b)
865
+
866
+ # 手动计算当前批次的加权损失,以便后续精确加总
867
+ task = getattr(self, "task_type", "regression")
868
+ if task == 'classification':
869
+ loss_fn = nn.BCEWithLogitsLoss(reduction='none')
870
+ losses = loss_fn(y_pred, y_b).view(-1)
871
+ else:
872
+ # 此处无需再做 softplus:训练时 apply_softplus=False,模型前向结果本身已为正
873
+ y_pred_clamped = torch.clamp(y_pred, min=1e-6)
874
+ power = getattr(self, "tw_power", 1.5)
875
+ losses = tweedie_loss(
876
+ y_pred_clamped, y_b, p=power).view(-1)
877
+
878
+ batch_weight_sum = torch.clamp(w_b.sum(), min=EPS)
879
+ batch_weighted_loss_sum = (losses * w_b.view(-1)).sum()
880
+
881
+ total_loss += batch_weighted_loss_sum.item()
882
+ total_weight += batch_weight_sum.item()
883
+
884
+ return total_loss / max(total_weight, EPS)
885
+
886
+ clip_fn = None
887
+ if self.device.type == 'cuda':
888
+ def clip_fn(): return (self.scaler.unscale_(self.optimizer),
889
+ clip_grad_norm_(self.resnet.parameters(), max_norm=1.0))
890
+
891
+ # DDP 模式下,只在主进程打印日志和保存模型
892
+ if self.is_ddp_enabled and not DistributedUtils.is_main_process():
893
+ # 非主进程不进行验证回调中的打印操作(需在 _train_model 内部控制,这里暂略)
894
+ pass
895
+
896
+ best_state = self._train_model(
897
+ self.resnet,
898
+ dataloader,
899
+ accum_steps,
900
+ self.optimizer,
901
+ self.scaler,
902
+ forward_fn,
903
+ val_forward_fn if has_val else None,
904
+ apply_softplus=False,
905
+ clip_fn=clip_fn,
906
+ trial=trial
907
+ )
908
+
909
+ if has_val and best_state is not None:
910
+ self.resnet.load_state_dict(best_state)
911
+
912
+ # ---------------- 预测 ----------------
913
+
914
+ def predict(self, X_test):
915
+ self.resnet.eval()
916
+ if isinstance(X_test, pd.DataFrame):
917
+ X_np = X_test.values.astype(np.float32)
918
+ else:
919
+ X_np = X_test
920
+
921
+ with torch.no_grad():
922
+ y_pred = self(X_np).cpu().numpy()
923
+
924
+ if self.task_type == 'classification':
925
+ y_pred = 1 / (1 + np.exp(-y_pred)) # Sigmoid 函数将 logit 转换为概率
926
+ else:
927
+ y_pred = np.clip(y_pred, 1e-6, None)
928
+ return y_pred.flatten()
929
+
930
+ # ---------------- 设置参数 ----------------
931
+
932
+ def set_params(self, params):
933
+ for key, value in params.items():
934
+ if hasattr(self, key):
935
+ setattr(self, key, value)
936
+ else:
937
+ raise ValueError(f"Parameter {key} not found in model.")
938
+ return self
939
+
940
+
941
+ # =============================================================================
942
+ # FT-Transformer 模型与 sklearn 风格封装
943
+ # =============================================================================
944
+ # 开始定义FT Transformer模型结构
945
+
946
+
947
+ class FeatureTokenizer(nn.Module):
948
+ """将数值/类别/地理 token 统一映射为 Transformer 输入 tokens。"""
949
+
950
+ def __init__(self, num_numeric: int, cat_cardinalities, d_model: int, num_geo: int = 0):
951
+ super().__init__()
952
+
953
+ self.num_numeric = num_numeric
954
+ self.has_numeric = num_numeric > 0
955
+ self.num_geo = num_geo
956
+ self.has_geo = num_geo > 0
957
+
958
+ if self.has_numeric:
959
+ self.num_linear = nn.Linear(num_numeric, d_model)
960
+
961
+ self.embeddings = nn.ModuleList([
962
+ nn.Embedding(card, d_model) for card in cat_cardinalities
963
+ ])
964
+
965
+ if self.has_geo:
966
+ # 地理 token 直接线性映射,避免对原始字符串做 one-hot;上游已编码/标准化
967
+ self.geo_linear = nn.Linear(num_geo, d_model)
968
+
969
+ def forward(self, X_num, X_cat, X_geo=None):
970
+ tokens = []
971
+
972
+ if self.has_numeric:
973
+ num_token = self.num_linear(X_num)
974
+ tokens.append(num_token)
975
+
976
+ for i, emb in enumerate(self.embeddings):
977
+ tok = emb(X_cat[:, i])
978
+ tokens.append(tok)
979
+
980
+ if self.has_geo:
981
+ if X_geo is None:
982
+ raise RuntimeError("启用了地理 token,但未提供 X_geo。")
983
+ geo_token = self.geo_linear(X_geo)
984
+ tokens.append(geo_token)
985
+
986
+ x = torch.stack(tokens, dim=1)
987
+ return x
988
+
989
+ # 定义具有残差缩放的Encoder层
990
+
991
+
992
+ class ScaledTransformerEncoderLayer(nn.Module):
993
+ def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048,
994
+ dropout: float = 0.1, residual_scale_attn: float = 1.0,
995
+ residual_scale_ffn: float = 1.0, norm_first: bool = True,
996
+ ):
997
+ super().__init__()
998
+ self.self_attn = nn.MultiheadAttention(
999
+ embed_dim=d_model,
1000
+ num_heads=nhead,
1001
+ dropout=dropout,
1002
+ batch_first=True
1003
+ )
1004
+
1005
+ # 前馈网络部分
1006
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
1007
+ self.dropout = nn.Dropout(dropout)
1008
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
1009
+
1010
+ # 归一化与 Dropout
1011
+ self.norm1 = nn.LayerNorm(d_model)
1012
+ self.norm2 = nn.LayerNorm(d_model)
1013
+ self.dropout1 = nn.Dropout(dropout)
1014
+ self.dropout2 = nn.Dropout(dropout)
1015
+
1016
+ self.activation = nn.GELU()
1017
+ # 如果偏好 ReLU,可将激活函数改为:self.activation = nn.ReLU()
1018
+ self.norm_first = norm_first
1019
+
1020
+ # 残差缩放系数
1021
+ self.res_scale_attn = residual_scale_attn
1022
+ self.res_scale_ffn = residual_scale_ffn
1023
+
1024
+ def forward(self, src, src_mask=None, src_key_padding_mask=None):
1025
+ # 输入张量形状:(batch, 序列长度, d_model)
1026
+ x = src
1027
+
1028
+ if self.norm_first:
1029
+ # 先归一化再做注意力
1030
+ x = x + self._sa_block(self.norm1(x), src_mask,
1031
+ src_key_padding_mask)
1032
+ x = x + self._ff_block(self.norm2(x))
1033
+ else:
1034
+ # 后归一化(一般不启用)
1035
+ x = self.norm1(
1036
+ x + self._sa_block(x, src_mask, src_key_padding_mask))
1037
+ x = self.norm2(x + self._ff_block(x))
1038
+
1039
+ return x
1040
+
1041
+ def _sa_block(self, x, attn_mask, key_padding_mask):
1042
+ # 自注意力并附带残差缩放
1043
+ attn_out, _ = self.self_attn(
1044
+ x, x, x,
1045
+ attn_mask=attn_mask,
1046
+ key_padding_mask=key_padding_mask,
1047
+ need_weights=False
1048
+ )
1049
+ return self.res_scale_attn * self.dropout1(attn_out)
1050
+
1051
+ def _ff_block(self, x):
1052
+ # 前馈网络并附带残差缩放
1053
+ x2 = self.linear2(self.dropout(self.activation(self.linear1(x))))
1054
+ return self.res_scale_ffn * self.dropout2(x2)
1055
+
1056
+ # 定义FT-Transformer核心模型
1057
+
1058
+
1059
+ class FTTransformerCore(nn.Module):
1060
+ # 最小可用版本的 FT-Transformer,由三部分组成:
1061
+ # 1) FeatureTokenizer:将数值/类别特征转换成 token;
1062
+ # 2) TransformerEncoder:建模特征之间的交互;
1063
+ # 3) 池化 + MLP + Softplus:输出正值,方便 Tweedie/Gamma 等任务。
1064
+
1065
+ def __init__(self, num_numeric: int, cat_cardinalities, d_model: int = 64,
1066
+ n_heads: int = 8, n_layers: int = 4, dropout: float = 0.1,
1067
+ task_type: str = 'regression', num_geo: int = 0
1068
+ ):
1069
+ super().__init__()
1070
+
1071
+ self.tokenizer = FeatureTokenizer(
1072
+ num_numeric=num_numeric,
1073
+ cat_cardinalities=cat_cardinalities,
1074
+ d_model=d_model,
1075
+ num_geo=num_geo
1076
+ )
1077
+ scale = 1.0 / math.sqrt(n_layers) # 推荐一个默认值
1078
+ encoder_layer = ScaledTransformerEncoderLayer(
1079
+ d_model=d_model,
1080
+ nhead=n_heads,
1081
+ dim_feedforward=d_model * 4,
1082
+ dropout=dropout,
1083
+ residual_scale_attn=scale,
1084
+ residual_scale_ffn=scale,
1085
+ norm_first=True,
1086
+ )
1087
+ self.encoder = nn.TransformerEncoder(
1088
+ encoder_layer,
1089
+ num_layers=n_layers
1090
+ )
1091
+ self.n_layers = n_layers
1092
+
1093
+ layers = [
1094
+ # 如需更深的输出头,可按需启用下方示例层:
1095
+ # nn.LayerNorm(d_model), # 额外的归一化层
1096
+ # nn.Linear(d_model, d_model), # 额外的全连接层
1097
+ # nn.GELU(), # 对应的激活层
1098
+ nn.Linear(d_model, 1),
1099
+ ]
1100
+
1101
+ if task_type == 'classification':
1102
+ # 分类任务输出 logits,与 BCEWithLogitsLoss 更匹配
1103
+ layers.append(nn.Identity())
1104
+ else:
1105
+ # 回归任务需保持正值,适配 Tweedie/Gamma
1106
+ layers.append(nn.Softplus())
1107
+
1108
+ self.head = nn.Sequential(*layers)
1109
+
1110
+ def forward(self, X_num, X_cat, X_geo=None):
1111
+
1112
+ # 输入:
1113
+ # X_num -> (batch, 数值特征数) 的 float32 张量
1114
+ # X_cat -> (batch, 类别特征数) 的 long 张量
1115
+ # X_geo -> (batch, 地理 token 维度) 的 float32 张量
1116
+
1117
+ if self.training and not hasattr(self, '_printed_device'):
1118
+ print(f">>> FTTransformerCore executing on device: {X_num.device}")
1119
+ self._printed_device = True
1120
+
1121
+ # => 张量形状 (batch, token_num, d_model)
1122
+ tokens = self.tokenizer(X_num, X_cat, X_geo)
1123
+ # => 张量形状 (batch, token_num, d_model)
1124
+ x = self.encoder(tokens)
1125
+
1126
+ # 对 token 做平均池化,再送入回归头
1127
+ x = x.mean(dim=1) # => 张量形状 (batch, d_model)
1128
+
1129
+ # => 张量形状 (batch, 1),Softplus 约束为正
1130
+ out = self.head(x)
1131
+ return out
1132
+
1133
+ # 定义TabularDataset类
1134
+
1135
+
1136
+ class TabularDataset(Dataset):
1137
+ def __init__(self, X_num, X_cat, X_geo, y, w):
1138
+
1139
+ # 输入张量说明:
1140
+ # X_num: torch.float32,shape=(N, 数值特征数)
1141
+ # X_cat: torch.long, shape=(N, 类别特征数)
1142
+ # X_geo: torch.float32,shape=(N, 地理 token 维度),可为空张量
1143
+ # y: torch.float32,shape=(N, 1)
1144
+ # w: torch.float32,shape=(N, 1)
1145
+
1146
+ self.X_num = X_num
1147
+ self.X_cat = X_cat
1148
+ self.X_geo = X_geo
1149
+ self.y = y
1150
+ self.w = w
1151
+
1152
+ def __len__(self):
1153
+ return self.y.shape[0]
1154
+
1155
+ def __getitem__(self, idx):
1156
+ return (
1157
+ self.X_num[idx],
1158
+ self.X_cat[idx],
1159
+ self.X_geo[idx],
1160
+ self.y[idx],
1161
+ self.w[idx],
1162
+ )
1163
+
1164
+ # 定义FTTransformer的Scikit-Learn接口类
1165
+
1166
+
1167
+ class FTTransformerSklearn(TorchTrainerMixin, nn.Module):
1168
+
1169
+ # sklearn 风格包装:
1170
+ # - num_cols:数值特征列名列表
1171
+ # - cat_cols:类别特征列名列表(需事先做标签编码,取值 ∈ [0, n_classes-1])
1172
+
1173
+ def __init__(self, model_nme: str, num_cols, cat_cols, d_model: int = 64, n_heads: int = 8,
1174
+ n_layers: int = 4, dropout: float = 0.1, batch_num: int = 100, epochs: int = 100,
1175
+ task_type: str = 'regression',
1176
+ tweedie_power: float = 1.5, learning_rate: float = 1e-3, patience: int = 10,
1177
+ use_data_parallel: bool = True,
1178
+ use_ddp: bool = False
1179
+ ):
1180
+ super().__init__()
1181
+
1182
+ self.use_ddp = use_ddp
1183
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = (
1184
+ False, 0, 0, 1)
1185
+ if self.use_ddp:
1186
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = DistributedUtils.setup_ddp()
1187
+
1188
+ self.model_nme = model_nme
1189
+ self.num_cols = list(num_cols)
1190
+ self.cat_cols = list(cat_cols)
1191
+ self.d_model = d_model
1192
+ self.n_heads = n_heads
1193
+ self.n_layers = n_layers
1194
+ self.dropout = dropout
1195
+ self.batch_num = batch_num
1196
+ self.epochs = epochs
1197
+ self.learning_rate = learning_rate
1198
+ self.task_type = task_type
1199
+ self.patience = patience
1200
+ if self.task_type == 'classification':
1201
+ self.tw_power = None # 分类时不使用 Tweedie 幂
1202
+ elif 'f' in self.model_nme:
1203
+ self.tw_power = 1.0
1204
+ elif 's' in self.model_nme:
1205
+ self.tw_power = 2.0
1206
+ else:
1207
+ self.tw_power = tweedie_power
1208
+
1209
+ if self.is_ddp_enabled:
1210
+ self.device = torch.device(f"cuda:{self.local_rank}")
1211
+ elif torch.cuda.is_available():
1212
+ self.device = torch.device("cuda")
1213
+ elif torch.backends.mps.is_available():
1214
+ self.device = torch.device("mps")
1215
+ else:
1216
+ self.device = torch.device("cpu")
1217
+ self.cat_cardinalities = None
1218
+ self.cat_categories = {}
1219
+ self.ft = None
1220
+ self.use_data_parallel = torch.cuda.device_count() > 1 and use_data_parallel
1221
+ self.num_geo = 0
1222
+ self._geo_params: Dict[str, Any] = {}
1223
+
1224
+ def _build_model(self, X_train):
1225
+ num_numeric = len(self.num_cols)
1226
+ cat_cardinalities = []
1227
+
1228
+ for col in self.cat_cols:
1229
+ cats = X_train[col].astype('category')
1230
+ categories = cats.cat.categories
1231
+ self.cat_categories[col] = categories # 保存训练集类别全集
1232
+
1233
+ card = len(categories) + 1 # 多预留 1 类给“未知/缺失”
1234
+ cat_cardinalities.append(card)
1235
+
1236
+ self.cat_cardinalities = cat_cardinalities
1237
+
1238
+ core = FTTransformerCore(
1239
+ num_numeric=num_numeric,
1240
+ cat_cardinalities=cat_cardinalities,
1241
+ d_model=self.d_model,
1242
+ n_heads=self.n_heads,
1243
+ n_layers=self.n_layers,
1244
+ dropout=self.dropout,
1245
+ task_type=self.task_type,
1246
+ num_geo=self.num_geo
1247
+ )
1248
+ if self.is_ddp_enabled:
1249
+ core = core.to(self.device)
1250
+ core = DDP(core, device_ids=[
1251
+ self.local_rank], output_device=self.local_rank)
1252
+ elif self.use_data_parallel:
1253
+ core = nn.DataParallel(core, device_ids=list(
1254
+ range(torch.cuda.device_count())))
1255
+ self.device = torch.device("cuda")
1256
+ self.ft = core.to(self.device)
1257
+
1258
+ def _encode_cats(self, X):
1259
+ # 输入 DataFrame 至少需要包含所有类别特征列
1260
+ # 返回形状 (N, 类别特征数) 的 int64 数组
1261
+
1262
+ if not self.cat_cols:
1263
+ return np.zeros((len(X), 0), dtype='int64')
1264
+
1265
+ X_cat_list = []
1266
+ for col in self.cat_cols:
1267
+ # 使用训练阶段记录的类别全集
1268
+ categories = self.cat_categories[col]
1269
+ # 按固定类别构造 Categorical
1270
+ cats = pd.Categorical(X[col], categories=categories)
1271
+ codes = cats.codes.astype('int64', copy=True) # -1 表示未知或缺失
1272
+ # 未知或缺失映射到额外的“未知”索引 len(categories)
1273
+ codes[codes < 0] = len(categories)
1274
+ X_cat_list.append(codes)
1275
+
1276
+ X_cat_np = np.stack(X_cat_list, axis=1) # 形状 (N, 类别特征数)
1277
+ return X_cat_np
1278
+
1279
+ def _build_train_tensors(self, X_train, y_train, w_train, geo_train=None):
1280
+ return self._tensorize_split(X_train, y_train, w_train, geo_tokens=geo_train)
1281
+
1282
+ def _build_val_tensors(self, X_val, y_val, w_val, geo_val=None):
1283
+ return self._tensorize_split(X_val, y_val, w_val, geo_tokens=geo_val, allow_none=True)
1284
+
1285
+ def _tensorize_split(self, X, y, w, geo_tokens=None, allow_none: bool = False):
1286
+ if X is None:
1287
+ if allow_none:
1288
+ return None, None, None, None, None, False
1289
+ raise ValueError("输入特征 X 不能为空。")
1290
+
1291
+ X_num = torch.tensor(
1292
+ X[self.num_cols].to_numpy(dtype=np.float32, copy=True),
1293
+ dtype=torch.float32
1294
+ )
1295
+ if self.cat_cols:
1296
+ X_cat = torch.tensor(self._encode_cats(X), dtype=torch.long)
1297
+ else:
1298
+ X_cat = torch.zeros((X_num.shape[0], 0), dtype=torch.long)
1299
+
1300
+ if geo_tokens is not None:
1301
+ geo_np = np.asarray(geo_tokens, dtype=np.float32)
1302
+ if geo_np.ndim == 1:
1303
+ geo_np = geo_np.reshape(-1, 1)
1304
+ elif self.num_geo > 0:
1305
+ raise RuntimeError("geo_tokens 不能为空,请先准备好地理 token。")
1306
+ else:
1307
+ geo_np = np.zeros((X_num.shape[0], 0), dtype=np.float32)
1308
+ X_geo = torch.tensor(geo_np, dtype=torch.float32)
1309
+
1310
+ y_tensor = torch.tensor(
1311
+ y.values, dtype=torch.float32).view(-1, 1) if y is not None else None
1312
+ if y_tensor is None:
1313
+ w_tensor = None
1314
+ elif w is not None:
1315
+ w_tensor = torch.tensor(
1316
+ w.values, dtype=torch.float32).view(-1, 1)
1317
+ else:
1318
+ w_tensor = torch.ones_like(y_tensor)
1319
+ return X_num, X_cat, X_geo, y_tensor, w_tensor, y is not None
1320
+
1321
+ def fit(self, X_train, y_train, w_train=None,
1322
+ X_val=None, y_val=None, w_val=None, trial=None,
1323
+ geo_train=None, geo_val=None):
1324
+
1325
+ # 首次拟合时需要构建底层模型结构
1326
+ self.num_geo = geo_train.shape[1] if geo_train is not None else 0
1327
+ if self.ft is None:
1328
+ self._build_model(X_train)
1329
+
1330
+ X_num_train, X_cat_train, X_geo_train, y_tensor, w_tensor, _ = self._build_train_tensors(
1331
+ X_train, y_train, w_train, geo_train=geo_train)
1332
+ X_num_val, X_cat_val, X_geo_val, y_val_tensor, w_val_tensor, has_val = self._build_val_tensors(
1333
+ X_val, y_val, w_val, geo_val=geo_val)
1334
+
1335
+ # --- 构建 DataLoader ---
1336
+ dataset = TabularDataset(
1337
+ X_num_train, X_cat_train, X_geo_train, y_tensor, w_tensor
1338
+ )
1339
+
1340
+ dataloader, accum_steps = self._build_dataloader(
1341
+ dataset,
1342
+ N=X_num_train.shape[0],
1343
+ base_bs_gpu=(2048, 1024, 512),
1344
+ base_bs_cpu=(256, 128),
1345
+ min_bs=64,
1346
+ target_effective_cuda=2048,
1347
+ target_effective_cpu=1024
1348
+ )
1349
+
1350
+ if self.is_ddp_enabled and hasattr(dataloader.sampler, 'set_epoch'):
1351
+ self.dataloader_sampler = dataloader.sampler
1352
+ else:
1353
+ self.dataloader_sampler = None
1354
+
1355
+ optimizer = torch.optim.Adam(
1356
+ self.ft.parameters(), lr=self.learning_rate)
1357
+ scaler = GradScaler(enabled=(self.device.type == 'cuda'))
1358
+
1359
+ X_num_val_dev = X_cat_val_dev = y_val_dev = w_val_dev = None
1360
+ val_dataloader = None
1361
+ if has_val:
1362
+ val_dataset = TabularDataset(
1363
+ X_num_val, X_cat_val, X_geo_val, y_val_tensor, w_val_tensor
1364
+ )
1365
+ val_bs = accum_steps * dataloader.batch_size
1366
+
1367
+ if os.name == 'nt':
1368
+ val_workers = 0
1369
+ else:
1370
+ val_workers = min(4, os.cpu_count() or 1)
1371
+ if getattr(self, "is_ddp_enabled", False):
1372
+ val_workers = 0 # DDP 下禁用多 worker,防止子进程冲突
1373
+
1374
+ val_dataloader = DataLoader(
1375
+ val_dataset,
1376
+ batch_size=val_bs,
1377
+ shuffle=False,
1378
+ num_workers=val_workers,
1379
+ pin_memory=(self.device.type == 'cuda'),
1380
+ persistent_workers=val_workers > 0,
1381
+ )
1382
+
1383
+ is_data_parallel = isinstance(self.ft, nn.DataParallel)
1384
+
1385
+ def forward_fn(batch):
1386
+ X_num_b, X_cat_b, X_geo_b, y_b, w_b = batch
1387
+
1388
+ if not is_data_parallel:
1389
+ X_num_b = X_num_b.to(self.device, non_blocking=True)
1390
+ X_cat_b = X_cat_b.to(self.device, non_blocking=True)
1391
+ X_geo_b = X_geo_b.to(self.device, non_blocking=True)
1392
+ y_b = y_b.to(self.device, non_blocking=True)
1393
+ w_b = w_b.to(self.device, non_blocking=True)
1394
+
1395
+ y_pred = self.ft(X_num_b, X_cat_b, X_geo_b)
1396
+ return y_pred, y_b, w_b
1397
+
1398
+ def val_forward_fn():
1399
+ total_loss = 0.0
1400
+ total_weight = 0.0
1401
+ for batch in val_dataloader:
1402
+ X_num_b, X_cat_b, X_geo_b, y_b, w_b = batch
1403
+ if not is_data_parallel:
1404
+ X_num_b = X_num_b.to(self.device, non_blocking=True)
1405
+ X_cat_b = X_cat_b.to(self.device, non_blocking=True)
1406
+ X_geo_b = X_geo_b.to(self.device, non_blocking=True)
1407
+ y_b = y_b.to(self.device, non_blocking=True)
1408
+ w_b = w_b.to(self.device, non_blocking=True)
1409
+
1410
+ y_pred = self.ft(X_num_b, X_cat_b, X_geo_b)
1411
+
1412
+ # 手动计算验证损失
1413
+ task = getattr(self, "task_type", "regression")
1414
+ if task == 'classification':
1415
+ loss_fn = nn.BCEWithLogitsLoss(reduction='none')
1416
+ losses = loss_fn(y_pred, y_b).view(-1)
1417
+ else:
1418
+ # 模型输出已通过 Softplus,无需再次应用
1419
+ y_pred_clamped = torch.clamp(y_pred, min=1e-6)
1420
+ power = getattr(self, "tw_power", 1.5)
1421
+ losses = tweedie_loss(
1422
+ y_pred_clamped, y_b, p=power).view(-1)
1423
+
1424
+ batch_weight_sum = torch.clamp(w_b.sum(), min=EPS)
1425
+ batch_weighted_loss_sum = (losses * w_b.view(-1)).sum()
1426
+
1427
+ total_loss += batch_weighted_loss_sum.item()
1428
+ total_weight += batch_weight_sum.item()
1429
+
1430
+ return total_loss / max(total_weight, EPS)
1431
+
1432
+ clip_fn = None
1433
+ if self.device.type == 'cuda':
1434
+ def clip_fn(): return (scaler.unscale_(optimizer),
1435
+ clip_grad_norm_(self.ft.parameters(), max_norm=1.0))
1436
+
1437
+ best_state = self._train_model(
1438
+ self.ft,
1439
+ dataloader,
1440
+ accum_steps,
1441
+ optimizer,
1442
+ scaler,
1443
+ forward_fn,
1444
+ val_forward_fn if has_val else None,
1445
+ apply_softplus=False,
1446
+ clip_fn=clip_fn,
1447
+ trial=trial
1448
+ )
1449
+
1450
+ if has_val and best_state is not None:
1451
+ self.ft.load_state_dict(best_state)
1452
+
1453
+ def predict(self, X_test, geo_tokens=None):
1454
+ # X_test 需要包含所有数值列与类别列;geo_tokens 为可选的地理 token
1455
+
1456
+ self.ft.eval()
1457
+ X_num, X_cat, X_geo, _, _, _ = self._tensorize_split(
1458
+ X_test, None, None, geo_tokens=geo_tokens, allow_none=True)
1459
+
1460
+ with torch.no_grad():
1461
+ X_num = X_num.to(self.device, non_blocking=True)
1462
+ X_cat = X_cat.to(self.device, non_blocking=True)
1463
+ X_geo = X_geo.to(self.device, non_blocking=True)
1464
+ y_pred = self.ft(X_num, X_cat, X_geo).cpu().numpy()
1465
+
1466
+ if self.task_type == 'classification':
1467
+ # 从 logits 转换为概率
1468
+ y_pred = 1 / (1 + np.exp(-y_pred))
1469
+ else:
1470
+ # 模型已含 softplus,若需要可按需做 log-exp 平滑:y_pred = log(1 + exp(y_pred))
1471
+ y_pred = np.clip(y_pred, 1e-6, None)
1472
+ return y_pred.ravel()
1473
+
1474
+ def set_params(self, params: dict):
1475
+
1476
+ # 和 sklearn 风格保持一致。
1477
+ # 注意:对结构性参数(如 d_model/n_heads)修改后,需要重新 fit 才会生效。
1478
+
1479
+ for key, value in params.items():
1480
+ if hasattr(self, key):
1481
+ setattr(self, key, value)
1482
+ else:
1483
+ raise ValueError(f"Parameter {key} not found in model.")
1484
+ return self
1485
+
1486
+
1487
+ # =============================================================================
1488
+ # 图神经网络 (GNN) 简化实现
1489
+ # =============================================================================
1490
+
1491
+
1492
+ class SimpleGraphLayer(nn.Module):
1493
+ def __init__(self, in_dim: int, out_dim: int, dropout: float = 0.1):
1494
+ super().__init__()
1495
+ self.linear = nn.Linear(in_dim, out_dim)
1496
+ self.activation = nn.ReLU(inplace=True)
1497
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
1498
+
1499
+ def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
1500
+ # 基于归一化稀疏邻接矩阵的消息传递:A_hat * X * W
1501
+ h = torch.sparse.mm(adj, x)
1502
+ h = self.linear(h)
1503
+ h = self.activation(h)
1504
+ return self.dropout(h)
1505
+
1506
+
1507
+ class SimpleGNN(nn.Module):
1508
+ def __init__(self, input_dim: int, hidden_dim: int = 64, num_layers: int = 2,
1509
+ dropout: float = 0.1, task_type: str = 'regression'):
1510
+ super().__init__()
1511
+ layers = []
1512
+ dim_in = input_dim
1513
+ for _ in range(max(1, num_layers)):
1514
+ layers.append(SimpleGraphLayer(
1515
+ dim_in, hidden_dim, dropout=dropout))
1516
+ dim_in = hidden_dim
1517
+ self.layers = nn.ModuleList(layers)
1518
+ self.output = nn.Linear(hidden_dim, 1)
1519
+ if task_type == 'classification':
1520
+ self.output_act = nn.Identity()
1521
+ else:
1522
+ self.output_act = nn.Softplus()
1523
+ self.task_type = task_type
1524
+ # 用 buffer 保持邻接矩阵,便于 DataParallel 复制
1525
+ self.register_buffer("adj_buffer", torch.empty(0))
1526
+
1527
+ def forward(self, x: torch.Tensor, adj: Optional[torch.Tensor] = None) -> torch.Tensor:
1528
+ adj_used = adj if adj is not None else getattr(
1529
+ self, "adj_buffer", None)
1530
+ if adj_used is None or adj_used.numel() == 0:
1531
+ raise RuntimeError("Adjacency is not set for GNN forward.")
1532
+ h = x
1533
+ for layer in self.layers:
1534
+ h = layer(h, adj_used)
1535
+ h = torch.sparse.mm(adj_used, h)
1536
+ out = self.output(h)
1537
+ return self.output_act(out)
1538
+
1539
+
1540
+ class GraphNeuralNetSklearn(TorchTrainerMixin, nn.Module):
1541
+ def __init__(self, model_nme: str, input_dim: int, hidden_dim: int = 64,
1542
+ num_layers: int = 2, k_neighbors: int = 10, dropout: float = 0.1,
1543
+ learning_rate: float = 1e-3, epochs: int = 100, patience: int = 10,
1544
+ task_type: str = 'regression', tweedie_power: float = 1.5,
1545
+ use_data_parallel: bool = False, use_ddp: bool = False,
1546
+ use_approx_knn: bool = True, approx_knn_threshold: int = 50000,
1547
+ graph_cache_path: Optional[str] = None,
1548
+ max_gpu_knn_nodes: Optional[int] = None,
1549
+ knn_gpu_mem_ratio: float = 0.9,
1550
+ knn_gpu_mem_overhead: float = 2.0) -> None:
1551
+ super().__init__()
1552
+ self.model_nme = model_nme
1553
+ self.input_dim = input_dim
1554
+ self.hidden_dim = hidden_dim
1555
+ self.num_layers = num_layers
1556
+ self.k_neighbors = max(1, k_neighbors)
1557
+ self.dropout = dropout
1558
+ self.learning_rate = learning_rate
1559
+ self.epochs = epochs
1560
+ self.patience = patience
1561
+ self.task_type = task_type
1562
+ self.use_approx_knn = use_approx_knn
1563
+ self.approx_knn_threshold = approx_knn_threshold
1564
+ self.graph_cache_path = Path(
1565
+ graph_cache_path) if graph_cache_path else None
1566
+ self.max_gpu_knn_nodes = max_gpu_knn_nodes
1567
+ self.knn_gpu_mem_ratio = max(0.0, min(1.0, knn_gpu_mem_ratio))
1568
+ self.knn_gpu_mem_overhead = max(1.0, knn_gpu_mem_overhead)
1569
+ self._knn_warning_emitted = False
1570
+
1571
+ if self.task_type == 'classification':
1572
+ self.tw_power = None
1573
+ elif 'f' in self.model_nme:
1574
+ self.tw_power = 1.0
1575
+ elif 's' in self.model_nme:
1576
+ self.tw_power = 2.0
1577
+ else:
1578
+ self.tw_power = tweedie_power
1579
+
1580
+ self.ddp_enabled = False
1581
+ self.local_rank = 0
1582
+ self.data_parallel_enabled = False
1583
+
1584
+ # DDP 仅在 CUDA 下有效;若未初始化成功则自动回退单卡
1585
+ if use_ddp and torch.cuda.is_available():
1586
+ ddp_ok, local_rank, _, _ = DistributedUtils.setup_ddp()
1587
+ if ddp_ok:
1588
+ self.ddp_enabled = True
1589
+ self.local_rank = local_rank
1590
+ self.device = torch.device(f'cuda:{local_rank}')
1591
+ else:
1592
+ self.device = torch.device('cuda')
1593
+ elif torch.cuda.is_available():
1594
+ self.device = torch.device('cuda')
1595
+ elif torch.backends.mps.is_available():
1596
+ self.device = torch.device('mps')
1597
+ else:
1598
+ self.device = torch.device('cpu')
1599
+ self.use_pyg_knn = self.device.type == 'cuda' and _PYG_AVAILABLE
1600
+
1601
+ self.gnn = SimpleGNN(
1602
+ input_dim=self.input_dim,
1603
+ hidden_dim=self.hidden_dim,
1604
+ num_layers=self.num_layers,
1605
+ dropout=self.dropout,
1606
+ task_type=self.task_type
1607
+ ).to(self.device)
1608
+
1609
+ # DataParallel 会将完整图复制到每张卡并按特征拆分,适合中等规模图
1610
+ if (not self.ddp_enabled) and use_data_parallel and (self.device.type == 'cuda') and (torch.cuda.device_count() > 1):
1611
+ self.data_parallel_enabled = True
1612
+ self.gnn = nn.DataParallel(
1613
+ self.gnn, device_ids=list(range(torch.cuda.device_count())))
1614
+ self.device = torch.device('cuda')
1615
+
1616
+ if self.ddp_enabled:
1617
+ self.gnn = DDP(
1618
+ self.gnn,
1619
+ device_ids=[self.local_rank],
1620
+ output_device=self.local_rank,
1621
+ find_unused_parameters=False
1622
+ )
1623
+
1624
+ def _unwrap_gnn(self) -> nn.Module:
1625
+ return self.gnn.module if isinstance(self.gnn, DDP) else self.gnn
1626
+
1627
+ def _set_adj_buffer(self, adj: torch.Tensor) -> None:
1628
+ base = self._unwrap_gnn()
1629
+ if hasattr(base, "adj_buffer"):
1630
+ base.adj_buffer = adj
1631
+ else:
1632
+ base.register_buffer("adj_buffer", adj)
1633
+
1634
+ def _load_cached_adj(self) -> Optional[torch.Tensor]:
1635
+ if self.graph_cache_path and self.graph_cache_path.exists():
1636
+ try:
1637
+ adj = torch.load(self.graph_cache_path,
1638
+ map_location=self.device)
1639
+ return adj.to(self.device)
1640
+ except Exception as exc:
1641
+ print(
1642
+ f"[GNN] Failed to load cached graph from {self.graph_cache_path}: {exc}")
1643
+ return None
1644
+
1645
+ def _build_edge_index_cpu(self, X_np: np.ndarray) -> torch.Tensor:
1646
+ n_samples = X_np.shape[0]
1647
+ k = min(self.k_neighbors, max(1, n_samples - 1))
1648
+ n_neighbors = min(k + 1, n_samples)
1649
+ use_approx = (self.use_approx_knn or n_samples >=
1650
+ self.approx_knn_threshold) and _PYNN_AVAILABLE
1651
+ indices = None
1652
+ if use_approx:
1653
+ try:
1654
+ nn_index = pynndescent.NNDescent(
1655
+ X_np,
1656
+ n_neighbors=n_neighbors,
1657
+ random_state=0
1658
+ )
1659
+ indices, _ = nn_index.neighbor_graph
1660
+ except Exception as exc:
1661
+ print(
1662
+ f"[GNN] Approximate kNN failed ({exc}); falling back to exact search.")
1663
+ use_approx = False
1664
+
1665
+ if indices is None:
1666
+ nbrs = NearestNeighbors(n_neighbors=n_neighbors, algorithm="auto")
1667
+ nbrs.fit(X_np)
1668
+ _, indices = nbrs.kneighbors(X_np)
1669
+
1670
+ indices = np.asarray(indices)
1671
+
1672
+ rows = []
1673
+ cols = []
1674
+ for i in range(n_samples):
1675
+ for j in indices[i]:
1676
+ if i == j:
1677
+ continue
1678
+ rows.append(i)
1679
+ cols.append(j)
1680
+ rows.append(j)
1681
+ cols.append(i)
1682
+
1683
+ # 添加自环,避免度为 0 的节点
1684
+ rows.extend(range(n_samples))
1685
+ cols.extend(range(n_samples))
1686
+
1687
+ edge_index = torch.tensor(
1688
+ [rows, cols], dtype=torch.long, device=self.device)
1689
+ return edge_index
1690
+
1691
+ def _build_edge_index_gpu(self, X_tensor: torch.Tensor) -> torch.Tensor:
1692
+ if not self.use_pyg_knn or knn_graph is None or add_self_loops is None or to_undirected is None:
1693
+ # 防御式编程:调用前应检查 use_pyg_knn
1694
+ raise RuntimeError(
1695
+ "GPU graph builder requested but PyG is unavailable.")
1696
+
1697
+ n_samples = X_tensor.size(0)
1698
+ k = min(self.k_neighbors, max(1, n_samples - 1))
1699
+
1700
+ # knn_graph 运行在 GPU 上,避免 CPU 构图成为瓶颈
1701
+ edge_index = knn_graph(
1702
+ X_tensor,
1703
+ k=k,
1704
+ loop=False
1705
+ )
1706
+ edge_index = to_undirected(edge_index, num_nodes=n_samples)
1707
+ edge_index, _ = add_self_loops(edge_index, num_nodes=n_samples)
1708
+ return edge_index
1709
+
1710
+ def _log_knn_fallback(self, reason: str) -> None:
1711
+ if self._knn_warning_emitted:
1712
+ return
1713
+ if (not self.ddp_enabled) or self.local_rank == 0:
1714
+ print(f"[GNN] Falling back to CPU kNN builder: {reason}")
1715
+ self._knn_warning_emitted = True
1716
+
1717
+ def _should_use_gpu_knn(self, n_samples: int, X_tensor: torch.Tensor) -> bool:
1718
+ if not self.use_pyg_knn:
1719
+ return False
1720
+
1721
+ reason = None
1722
+ if self.max_gpu_knn_nodes is not None and n_samples > self.max_gpu_knn_nodes:
1723
+ reason = f"node count {n_samples} exceeds max_gpu_knn_nodes={self.max_gpu_knn_nodes}"
1724
+ elif self.device.type == 'cuda' and torch.cuda.is_available():
1725
+ try:
1726
+ device_index = self.device.index
1727
+ if device_index is None:
1728
+ device_index = torch.cuda.current_device()
1729
+ free_mem, total_mem = torch.cuda.mem_get_info(device_index)
1730
+ feature_bytes = X_tensor.element_size() * X_tensor.nelement()
1731
+ required = int(feature_bytes * self.knn_gpu_mem_overhead)
1732
+ budget = int(free_mem * self.knn_gpu_mem_ratio)
1733
+ if required > budget:
1734
+ required_gb = required / (1024 ** 3)
1735
+ budget_gb = budget / (1024 ** 3)
1736
+ reason = (f"requires ~{required_gb:.2f} GiB temporary GPU memory "
1737
+ f"but only {budget_gb:.2f} GiB free on cuda:{device_index}")
1738
+ except Exception:
1739
+ # 在较老版本或某些环境下 mem_get_info 可能不可用,默认继续尝试 GPU
1740
+ reason = None
1741
+
1742
+ if reason:
1743
+ self._log_knn_fallback(reason)
1744
+ return False
1745
+ return True
1746
+
1747
+ def _normalized_adj(self, edge_index: torch.Tensor, num_nodes: int) -> torch.Tensor:
1748
+ values = torch.ones(edge_index.shape[1], device=self.device)
1749
+ adj = torch.sparse_coo_tensor(
1750
+ edge_index.to(self.device), values, (num_nodes, num_nodes))
1751
+ adj = adj.coalesce()
1752
+
1753
+ deg = torch.sparse.sum(adj, dim=1).to_dense()
1754
+ deg_inv_sqrt = torch.pow(deg + 1e-8, -0.5)
1755
+ row, col = adj.indices()
1756
+ norm_values = deg_inv_sqrt[row] * adj.values() * deg_inv_sqrt[col]
1757
+ adj_norm = torch.sparse_coo_tensor(
1758
+ adj.indices(), norm_values, size=adj.shape)
1759
+ return adj_norm
1760
+
1761
+ def _tensorize_split(self, X, y, w, allow_none: bool = False):
1762
+ if X is None and allow_none:
1763
+ return None, None, None
1764
+ X_np = X.values.astype(np.float32)
1765
+ X_tensor = torch.tensor(X_np, dtype=torch.float32, device=self.device)
1766
+ if y is None:
1767
+ y_tensor = None
1768
+ else:
1769
+ y_tensor = torch.tensor(
1770
+ y.values, dtype=torch.float32, device=self.device).view(-1, 1)
1771
+ if w is None:
1772
+ w_tensor = torch.ones(
1773
+ (len(X), 1), dtype=torch.float32, device=self.device)
1774
+ else:
1775
+ w_tensor = torch.tensor(
1776
+ w.values, dtype=torch.float32, device=self.device).view(-1, 1)
1777
+ return X_tensor, y_tensor, w_tensor
1778
+
1779
+ def _build_graph_from_df(self, X_df: pd.DataFrame, X_tensor: Optional[torch.Tensor] = None) -> torch.Tensor:
1780
+ if X_tensor is None:
1781
+ X_tensor = torch.tensor(
1782
+ X_df.values.astype(np.float32),
1783
+ dtype=torch.float32,
1784
+ device=self.device
1785
+ )
1786
+ if self.graph_cache_path:
1787
+ cached = self._load_cached_adj()
1788
+ if cached is not None:
1789
+ return cached
1790
+ use_gpu_knn = self._should_use_gpu_knn(X_df.shape[0], X_tensor)
1791
+ if use_gpu_knn:
1792
+ edge_index = self._build_edge_index_gpu(X_tensor)
1793
+ else:
1794
+ edge_index = self._build_edge_index_cpu(
1795
+ X_df.values.astype(np.float32))
1796
+ adj_norm = self._normalized_adj(edge_index, X_df.shape[0])
1797
+ if self.graph_cache_path:
1798
+ try:
1799
+ IOUtils.ensure_parent_dir(str(self.graph_cache_path))
1800
+ torch.save(adj_norm.cpu(), self.graph_cache_path)
1801
+ except Exception as exc:
1802
+ print(
1803
+ f"[GNN] Failed to cache graph to {self.graph_cache_path}: {exc}")
1804
+ return adj_norm
1805
+
1806
+ def fit(self, X_train, y_train, w_train=None,
1807
+ X_val=None, y_val=None, w_val=None,
1808
+ trial: Optional[optuna.trial.Trial] = None):
1809
+
1810
+ X_train_tensor, y_train_tensor, w_train_tensor = self._tensorize_split(
1811
+ X_train, y_train, w_train, allow_none=False)
1812
+ has_val = X_val is not None and y_val is not None
1813
+ if has_val:
1814
+ X_val_tensor, y_val_tensor, w_val_tensor = self._tensorize_split(
1815
+ X_val, y_val, w_val, allow_none=False)
1816
+ else:
1817
+ X_val_tensor = y_val_tensor = w_val_tensor = None
1818
+
1819
+ adj_train = self._build_graph_from_df(X_train, X_train_tensor)
1820
+ adj_val = self._build_graph_from_df(
1821
+ X_val, X_val_tensor) if has_val else None
1822
+ # DataParallel 需要将邻接矩阵缓存在模型上,避免被 scatter
1823
+ self._set_adj_buffer(adj_train)
1824
+
1825
+ base_gnn = self._unwrap_gnn()
1826
+ optimizer = torch.optim.Adam(
1827
+ base_gnn.parameters(), lr=self.learning_rate)
1828
+ scaler = GradScaler(enabled=(self.device.type == 'cuda'))
1829
+
1830
+ best_loss = float('inf')
1831
+ best_state = None
1832
+ patience_counter = 0
1833
+
1834
+ for epoch in range(1, self.epochs + 1):
1835
+ self.gnn.train()
1836
+ optimizer.zero_grad()
1837
+ with autocast(enabled=(self.device.type == 'cuda')):
1838
+ if self.data_parallel_enabled:
1839
+ y_pred = self.gnn(X_train_tensor)
1840
+ else:
1841
+ y_pred = self.gnn(X_train_tensor, adj_train)
1842
+ loss = self._compute_weighted_loss(
1843
+ y_pred, y_train_tensor, w_train_tensor, apply_softplus=False)
1844
+ scaler.scale(loss).backward()
1845
+ scaler.unscale_(optimizer)
1846
+ clip_grad_norm_(self.gnn.parameters(), max_norm=1.0)
1847
+ scaler.step(optimizer)
1848
+ scaler.update()
1849
+
1850
+ if has_val:
1851
+ self.gnn.eval()
1852
+ if self.data_parallel_enabled and adj_val is not None:
1853
+ self._set_adj_buffer(adj_val)
1854
+ with torch.no_grad(), autocast(enabled=(self.device.type == 'cuda')):
1855
+ if self.data_parallel_enabled:
1856
+ y_val_pred = self.gnn(X_val_tensor)
1857
+ else:
1858
+ y_val_pred = self.gnn(X_val_tensor, adj_val)
1859
+ val_loss = self._compute_weighted_loss(
1860
+ y_val_pred, y_val_tensor, w_val_tensor, apply_softplus=False)
1861
+ if self.data_parallel_enabled:
1862
+ # 恢复训练邻接矩阵
1863
+ self._set_adj_buffer(adj_train)
1864
+
1865
+ best_loss, best_state, patience_counter, stop_training = self._early_stop_update(
1866
+ val_loss, best_loss, best_state, patience_counter, base_gnn,
1867
+ ignore_keys=["adj_buffer"])
1868
+
1869
+ if trial is not None:
1870
+ trial.report(val_loss, epoch)
1871
+ if trial.should_prune():
1872
+ raise optuna.TrialPruned()
1873
+ if stop_training:
1874
+ break
1875
+
1876
+ if best_state is not None:
1877
+ base_gnn.load_state_dict(best_state, strict=False)
1878
+
1879
+ def predict(self, X: pd.DataFrame) -> np.ndarray:
1880
+ self.gnn.eval()
1881
+ X_tensor, _, _ = self._tensorize_split(
1882
+ X, None, None, allow_none=False)
1883
+ adj = self._build_graph_from_df(X, X_tensor)
1884
+ if self.data_parallel_enabled:
1885
+ self._set_adj_buffer(adj)
1886
+ with torch.no_grad():
1887
+ if self.data_parallel_enabled:
1888
+ y_pred = self.gnn(X_tensor).cpu().numpy()
1889
+ else:
1890
+ y_pred = self.gnn(X_tensor, adj).cpu().numpy()
1891
+ if self.task_type == 'classification':
1892
+ y_pred = 1 / (1 + np.exp(-y_pred))
1893
+ else:
1894
+ y_pred = np.clip(y_pred, 1e-6, None)
1895
+ return y_pred.ravel()
1896
+
1897
+ def set_params(self, params: Dict[str, Any]):
1898
+ for key, value in params.items():
1899
+ if hasattr(self, key):
1900
+ setattr(self, key, value)
1901
+ else:
1902
+ raise ValueError(f"Parameter {key} not found in GNN model.")
1903
+ # 结构参数变化后需要重建骨架
1904
+ self.gnn = SimpleGNN(
1905
+ input_dim=self.input_dim,
1906
+ hidden_dim=self.hidden_dim,
1907
+ num_layers=self.num_layers,
1908
+ dropout=self.dropout,
1909
+ task_type=self.task_type
1910
+ ).to(self.device)
1911
+ return self
1912
+
1913
+
1914
+ # ===== 基础组件与训练封装 =====================================================
1915
+
1916
+ # =============================================================================
1917
+ # 配置、预处理与训练器基类
1918
+ # =============================================================================
1919
+ @dataclass
1920
+ class BayesOptConfig:
1921
+ model_nme: str
1922
+ resp_nme: str
1923
+ weight_nme: str
1924
+ factor_nmes: List[str]
1925
+ task_type: str = 'regression'
1926
+ binary_resp_nme: Optional[str] = None
1927
+ cate_list: Optional[List[str]] = None
1928
+ prop_test: float = 0.25
1929
+ rand_seed: Optional[int] = None
1930
+ epochs: int = 100
1931
+ use_gpu: bool = True
1932
+ use_resn_data_parallel: bool = False
1933
+ use_ft_data_parallel: bool = False
1934
+ use_resn_ddp: bool = False
1935
+ use_ft_ddp: bool = False
1936
+ use_gnn_data_parallel: bool = False
1937
+ use_gnn_ddp: bool = False
1938
+ gnn_use_approx_knn: bool = True
1939
+ gnn_approx_knn_threshold: int = 50000
1940
+ gnn_graph_cache: Optional[str] = None
1941
+ gnn_max_gpu_knn_nodes: Optional[int] = 200000
1942
+ gnn_knn_gpu_mem_ratio: float = 0.9
1943
+ gnn_knn_gpu_mem_overhead: float = 2.0
1944
+ geo_feature_nmes: Optional[List[str]] = None # 用于构造地理 token 的列,空则不启用 GNN
1945
+ geo_token_hidden_dim: int = 32
1946
+ geo_token_layers: int = 2
1947
+ geo_token_dropout: float = 0.1
1948
+ geo_token_k_neighbors: int = 10
1949
+ geo_token_learning_rate: float = 1e-3
1950
+ geo_token_epochs: int = 50
1951
+ output_dir: Optional[str] = None
1952
+ optuna_storage: Optional[str] = None
1953
+ optuna_study_prefix: Optional[str] = None
1954
+
1955
+
1956
+ class OutputManager:
1957
+ # 统一管理结果、图表与模型的输出路径
1958
+
1959
+ def __init__(self, root: Optional[str] = None, model_name: str = "model") -> None:
1960
+ self.root = Path(root or os.getcwd())
1961
+ self.model_name = model_name
1962
+ self.plot_dir = self.root / 'plot'
1963
+ self.result_dir = self.root / 'Results'
1964
+ self.model_dir = self.root / 'model'
1965
+
1966
+ def _prepare(self, path: Path) -> str:
1967
+ ensure_parent_dir(str(path))
1968
+ return str(path)
1969
+
1970
+ def plot_path(self, filename: str) -> str:
1971
+ return self._prepare(self.plot_dir / filename)
1972
+
1973
+ def result_path(self, filename: str) -> str:
1974
+ return self._prepare(self.result_dir / filename)
1975
+
1976
+ def model_path(self, filename: str) -> str:
1977
+ return self._prepare(self.model_dir / filename)
1978
+
1979
+
1980
+ class DatasetPreprocessor:
1981
+ # 为各训练器准备通用的训练/测试数据视图
1982
+
1983
+ def __init__(self, train_df: pd.DataFrame, test_df: pd.DataFrame,
1984
+ config: BayesOptConfig) -> None:
1985
+ self.config = config
1986
+ self.train_data = train_df.copy(deep=True)
1987
+ self.test_data = test_df.copy(deep=True)
1988
+ self.num_features: List[str] = []
1989
+ self.train_oht_data: Optional[pd.DataFrame] = None
1990
+ self.test_oht_data: Optional[pd.DataFrame] = None
1991
+ self.train_oht_scl_data: Optional[pd.DataFrame] = None
1992
+ self.test_oht_scl_data: Optional[pd.DataFrame] = None
1993
+ self.var_nmes: List[str] = []
1994
+ self.cat_categories_for_shap: Dict[str, List[Any]] = {}
1995
+
1996
+ def run(self) -> "DatasetPreprocessor":
1997
+ """执行预处理:类别编码、目标值裁剪以及数值特征标准化。"""
1998
+ cfg = self.config
1999
+ # 预先计算加权实际值,后续画图、校验都依赖该字段
2000
+ self.train_data.loc[:, 'w_act'] = self.train_data[cfg.resp_nme] * \
2001
+ self.train_data[cfg.weight_nme]
2002
+ self.test_data.loc[:, 'w_act'] = self.test_data[cfg.resp_nme] * \
2003
+ self.test_data[cfg.weight_nme]
2004
+ if cfg.binary_resp_nme:
2005
+ self.train_data.loc[:, 'w_binary_act'] = self.train_data[cfg.binary_resp_nme] * \
2006
+ self.train_data[cfg.weight_nme]
2007
+ self.test_data.loc[:, 'w_binary_act'] = self.test_data[cfg.binary_resp_nme] * \
2008
+ self.test_data[cfg.weight_nme]
2009
+ # 高分位裁剪用来吸收离群值;若删除会导致极端点主导损失
2010
+ q99 = self.train_data[cfg.resp_nme].quantile(0.999)
2011
+ self.train_data[cfg.resp_nme] = self.train_data[cfg.resp_nme].clip(
2012
+ upper=q99)
2013
+ cate_list = list(cfg.cate_list or [])
2014
+ if cate_list:
2015
+ for cate in cate_list:
2016
+ self.train_data[cate] = self.train_data[cate].astype(
2017
+ 'category')
2018
+ self.test_data[cate] = self.test_data[cate].astype('category')
2019
+ cats = self.train_data[cate].cat.categories
2020
+ self.cat_categories_for_shap[cate] = list(cats)
2021
+ self.num_features = [
2022
+ nme for nme in cfg.factor_nmes if nme not in cate_list]
2023
+ train_oht = self.train_data[cfg.factor_nmes +
2024
+ [cfg.weight_nme] + [cfg.resp_nme]].copy()
2025
+ test_oht = self.test_data[cfg.factor_nmes +
2026
+ [cfg.weight_nme] + [cfg.resp_nme]].copy()
2027
+ train_oht = pd.get_dummies(
2028
+ train_oht,
2029
+ columns=cate_list,
2030
+ drop_first=True,
2031
+ dtype=np.int8
2032
+ )
2033
+ test_oht = pd.get_dummies(
2034
+ test_oht,
2035
+ columns=cate_list,
2036
+ drop_first=True,
2037
+ dtype=np.int8
2038
+ )
2039
+
2040
+ # 重新索引时将缺失的哑变量列补零,避免测试集列数与训练集不一致
2041
+ test_oht = test_oht.reindex(columns=train_oht.columns, fill_value=0)
2042
+
2043
+ # 保留未缩放的 one-hot 数据,供交叉验证时按折内标准化避免泄露
2044
+ self.train_oht_data = train_oht.copy(deep=True)
2045
+ self.test_oht_data = test_oht.copy(deep=True)
2046
+
2047
+ train_oht_scaled = train_oht.copy(deep=True)
2048
+ test_oht_scaled = test_oht.copy(deep=True)
2049
+ for num_chr in self.num_features:
2050
+ # 逐列标准化保障每个特征在同一量级,否则神经网络会难以收敛
2051
+ scaler = StandardScaler()
2052
+ train_oht_scaled[num_chr] = scaler.fit_transform(
2053
+ train_oht_scaled[num_chr].values.reshape(-1, 1))
2054
+ test_oht_scaled[num_chr] = scaler.transform(
2055
+ test_oht_scaled[num_chr].values.reshape(-1, 1))
2056
+ # 重新索引时将缺失的哑变量列补零,避免测试集列数与训练集不一致
2057
+ test_oht_scaled = test_oht_scaled.reindex(
2058
+ columns=train_oht_scaled.columns, fill_value=0)
2059
+ self.train_oht_scl_data = train_oht_scaled
2060
+ self.test_oht_scl_data = test_oht_scaled
2061
+ self.var_nmes = list(
2062
+ set(list(train_oht_scaled.columns)) -
2063
+ set([cfg.weight_nme, cfg.resp_nme])
2064
+ )
2065
+ return self
2066
+
2067
+ # =============================================================================
2068
+ # 训练器体系
2069
+ # =============================================================================
2070
+
2071
+
2072
+ class TrainerBase:
2073
+ def __init__(self, context: "BayesOptModel", label: str, model_name_prefix: str) -> None:
2074
+ self.ctx = context
2075
+ self.label = label
2076
+ self.model_name_prefix = model_name_prefix
2077
+ self.model = None
2078
+ self.best_params: Optional[Dict[str, Any]] = None
2079
+ self.best_trial = None
2080
+ self.enable_distributed_optuna: bool = False
2081
+ self._distributed_forced_params: Optional[Dict[str, Any]] = None
2082
+
2083
+ @property
2084
+ def config(self) -> BayesOptConfig:
2085
+ return self.ctx.config
2086
+
2087
+ @property
2088
+ def output(self) -> OutputManager:
2089
+ return self.ctx.output_manager
2090
+
2091
+ def _get_model_filename(self) -> str:
2092
+ ext = 'pkl' if self.label in ['Xgboost', 'GLM'] else 'pth'
2093
+ return f'01_{self.ctx.model_nme}_{self.model_name_prefix}.{ext}'
2094
+
2095
+ def tune(self, max_evals: int, objective_fn=None) -> None:
2096
+ # 通用的 Optuna 调参循环流程。
2097
+ if objective_fn is None:
2098
+ # 若子类未显式提供 objective_fn,则默认使用 cross_val 作为优化目标
2099
+ objective_fn = self.cross_val
2100
+
2101
+ if self._should_use_distributed_optuna():
2102
+ self._distributed_tune(max_evals, objective_fn)
2103
+ return
2104
+
2105
+ total_trials = max(1, int(max_evals))
2106
+ progress_counter = {"count": 0}
2107
+
2108
+ def objective_wrapper(trial: optuna.trial.Trial) -> float:
2109
+ should_log = DistributedUtils.is_main_process()
2110
+ if should_log:
2111
+ current_idx = progress_counter["count"] + 1
2112
+ print(
2113
+ f"[Optuna][{self.label}] Trial {current_idx}/{total_trials} started "
2114
+ f"(trial_id={trial.number})."
2115
+ )
2116
+ try:
2117
+ result = objective_fn(trial)
2118
+ except RuntimeError as exc:
2119
+ if "out of memory" in str(exc).lower():
2120
+ print(
2121
+ f"[Optuna][{self.label}] OOM detected. Pruning trial and clearing CUDA cache."
2122
+ )
2123
+ self._clean_gpu()
2124
+ raise optuna.TrialPruned() from exc
2125
+ raise
2126
+ finally:
2127
+ self._clean_gpu()
2128
+ if should_log:
2129
+ progress_counter["count"] = progress_counter["count"] + 1
2130
+ trial_state = getattr(trial, "state", None)
2131
+ state_repr = getattr(trial_state, "name", "OK")
2132
+ print(
2133
+ f"[Optuna][{self.label}] Trial {progress_counter['count']}/{total_trials} finished "
2134
+ f"(status={state_repr})."
2135
+ )
2136
+ return result
2137
+
2138
+ study = optuna.create_study(
2139
+ direction='minimize',
2140
+ sampler=optuna.samplers.TPESampler(seed=self.ctx.rand_seed)
2141
+ )
2142
+ study.optimize(objective_wrapper, n_trials=max_evals)
2143
+ self.best_params = study.best_params
2144
+ self.best_trial = study.best_trial
2145
+
2146
+ # 将最优参数保存为 CSV,方便复现
2147
+ params_path = self.output.result_path(
2148
+ f'{self.ctx.model_nme}_bestparams_{self.label.lower()}.csv'
2149
+ )
2150
+ pd.DataFrame(self.best_params, index=[0]).to_csv(params_path)
2151
+
2152
+ def train(self) -> None:
2153
+ raise NotImplementedError
2154
+
2155
+ def save(self) -> None:
2156
+ if self.model is None:
2157
+ print(f"[save] Warning: No model to save for {self.label}")
2158
+ return
2159
+
2160
+ path = self.output.model_path(self._get_model_filename())
2161
+ if self.label in ['Xgboost', 'GLM']:
2162
+ joblib.dump(self.model, path)
2163
+ else:
2164
+ # PyTorch 模型既可以只存 state_dict,也可以整个对象一起序列化
2165
+ # 兼容历史行为:ResNetTrainer 保存 state_dict,FTTrainer 保存完整对象
2166
+ if hasattr(self.model, 'resnet'): # ResNetSklearn 模型
2167
+ torch.save(self.model.resnet.state_dict(), path)
2168
+ else: # FTTransformerSklearn 或其他 PyTorch 模型
2169
+ torch.save(self.model, path)
2170
+
2171
+ def load(self) -> None:
2172
+ path = self.output.model_path(self._get_model_filename())
2173
+ if not os.path.exists(path):
2174
+ print(f"[load] Warning: Model file not found: {path}")
2175
+ return
2176
+
2177
+ if self.label in ['Xgboost', 'GLM']:
2178
+ self.model = joblib.load(path)
2179
+ else:
2180
+ # PyTorch 模型的加载需要根据结构区别处理
2181
+ if self.label == 'ResNet' or self.label == 'ResNetClassifier':
2182
+ # ResNet 需要重新构建骨架,结构参数依赖 ctx,因此交由子类处理
2183
+ pass
2184
+ else:
2185
+ # FT-Transformer 序列化了整个对象,可直接加载后迁移到目标设备
2186
+ loaded = torch.load(path, map_location='cpu')
2187
+ self._move_to_device(loaded)
2188
+ self.model = loaded
2189
+
2190
+ def _move_to_device(self, model_obj):
2191
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
2192
+ if hasattr(model_obj, 'device'):
2193
+ model_obj.device = device
2194
+ if hasattr(model_obj, 'to'):
2195
+ model_obj.to(device)
2196
+ # 若对象内部还包含 ft/resnet 子模块,也要同时迁移设备
2197
+ if hasattr(model_obj, 'ft'):
2198
+ model_obj.ft.to(device)
2199
+ if hasattr(model_obj, 'resnet'):
2200
+ model_obj.resnet.to(device)
2201
+ if hasattr(model_obj, 'gnn'):
2202
+ model_obj.gnn.to(device)
2203
+
2204
+ def _should_use_distributed_optuna(self) -> bool:
2205
+ if not self.enable_distributed_optuna:
2206
+ return False
2207
+ try:
2208
+ world_env = int(os.environ.get("WORLD_SIZE", "1"))
2209
+ except Exception:
2210
+ world_env = 1
2211
+ return world_env > 1
2212
+
2213
+ def _distributed_is_main(self) -> bool:
2214
+ return DistributedUtils.is_main_process()
2215
+
2216
+ def _distributed_send_command(self, payload: Dict[str, Any]) -> None:
2217
+ if not self._should_use_distributed_optuna() or not self._distributed_is_main():
2218
+ return
2219
+ DistributedUtils.setup_ddp()
2220
+ message = [payload]
2221
+ dist.broadcast_object_list(message, src=0)
2222
+
2223
+ def _distributed_prepare_trial(self, params: Dict[str, Any]) -> None:
2224
+ if not self._should_use_distributed_optuna():
2225
+ return
2226
+ if not self._distributed_is_main():
2227
+ return
2228
+ self._distributed_send_command({"type": "RUN", "params": params})
2229
+ dist.barrier()
2230
+
2231
+ def _distributed_worker_loop(self, objective_fn: Callable[[Optional[optuna.trial.Trial]], float]) -> None:
2232
+ DistributedUtils.setup_ddp()
2233
+ while True:
2234
+ message = [None]
2235
+ dist.broadcast_object_list(message, src=0)
2236
+ payload = message[0]
2237
+ if not isinstance(payload, dict):
2238
+ continue
2239
+ cmd = payload.get("type")
2240
+ if cmd == "STOP":
2241
+ best_params = payload.get("best_params")
2242
+ if best_params is not None:
2243
+ self.best_params = best_params
2244
+ break
2245
+ if cmd == "RUN":
2246
+ params = payload.get("params") or {}
2247
+ self._distributed_forced_params = params
2248
+ dist.barrier()
2249
+ try:
2250
+ objective_fn(None)
2251
+ except optuna.TrialPruned:
2252
+ pass
2253
+ except Exception as exc:
2254
+ print(
2255
+ f"[Optuna][Worker][{self.label}] Exception: {exc}", flush=True)
2256
+ finally:
2257
+ self._clean_gpu()
2258
+ dist.barrier()
2259
+
2260
+ def _distributed_tune(self, max_evals: int, objective_fn: Callable[[optuna.trial.Trial], float]) -> None:
2261
+ DistributedUtils.setup_ddp()
2262
+ if not self._distributed_is_main():
2263
+ self._distributed_worker_loop(objective_fn)
2264
+ return
2265
+
2266
+ total_trials = max(1, int(max_evals))
2267
+ progress_counter = {"count": 0}
2268
+
2269
+ def objective_wrapper(trial: optuna.trial.Trial) -> float:
2270
+ should_log = True
2271
+ if should_log:
2272
+ current_idx = progress_counter["count"] + 1
2273
+ print(
2274
+ f"[Optuna][{self.label}] Trial {current_idx}/{total_trials} started "
2275
+ f"(trial_id={trial.number})."
2276
+ )
2277
+ try:
2278
+ result = objective_fn(trial)
2279
+ except RuntimeError as exc:
2280
+ if "out of memory" in str(exc).lower():
2281
+ print(
2282
+ f"[Optuna][{self.label}] OOM detected. Pruning trial and clearing CUDA cache."
2283
+ )
2284
+ self._clean_gpu()
2285
+ raise optuna.TrialPruned() from exc
2286
+ raise
2287
+ finally:
2288
+ self._clean_gpu()
2289
+ if should_log:
2290
+ progress_counter["count"] = progress_counter["count"] + 1
2291
+ trial_state = getattr(trial, "state", None)
2292
+ state_repr = getattr(trial_state, "name", "OK")
2293
+ print(
2294
+ f"[Optuna][{self.label}] Trial {progress_counter['count']}/{total_trials} finished "
2295
+ f"(status={state_repr})."
2296
+ )
2297
+ dist.barrier()
2298
+ return result
2299
+
2300
+ study = optuna.create_study(
2301
+ direction='minimize',
2302
+ sampler=optuna.samplers.TPESampler(seed=self.ctx.rand_seed)
2303
+ )
2304
+ try:
2305
+ study.optimize(objective_wrapper, n_trials=max_evals)
2306
+ self.best_params = study.best_params
2307
+ self.best_trial = study.best_trial
2308
+ params_path = self.output.result_path(
2309
+ f'{self.ctx.model_nme}_bestparams_{self.label.lower()}.csv'
2310
+ )
2311
+ pd.DataFrame(self.best_params, index=[0]).to_csv(params_path)
2312
+ finally:
2313
+ self._distributed_send_command(
2314
+ {"type": "STOP", "best_params": self.best_params})
2315
+
2316
+ def _clean_gpu(self):
2317
+ gc.collect()
2318
+ if torch.cuda.is_available():
2319
+ device = None
2320
+ try:
2321
+ device = getattr(self, "device", None)
2322
+ except Exception:
2323
+ device = None
2324
+ if isinstance(device, torch.device):
2325
+ try:
2326
+ torch.cuda.set_device(device)
2327
+ except Exception:
2328
+ pass
2329
+ torch.cuda.empty_cache()
2330
+ torch.cuda.ipc_collect()
2331
+ torch.cuda.synchronize()
2332
+
2333
+ def _standardize_fold(self,
2334
+ X_train: pd.DataFrame,
2335
+ X_val: pd.DataFrame,
2336
+ columns: Optional[List[str]] = None
2337
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, StandardScaler]:
2338
+ """在训练折上拟合 StandardScaler,并同步变换训练/验证特征。
2339
+
2340
+ 参数:
2341
+ X_train: 训练集特征。
2342
+ X_val: 验证集特征。
2343
+ columns: 需要缩放的列名;默认对全部列进行缩放。
2344
+
2345
+ 返回:
2346
+ 缩放后的训练/验证特征,以及已拟合好的 scaler 对象。
2347
+ """
2348
+ scaler = StandardScaler()
2349
+ cols = list(columns) if columns else list(X_train.columns)
2350
+ X_train_scaled = X_train.copy(deep=True)
2351
+ X_val_scaled = X_val.copy(deep=True)
2352
+ if cols:
2353
+ scaler.fit(X_train_scaled[cols])
2354
+ X_train_scaled[cols] = scaler.transform(X_train_scaled[cols])
2355
+ X_val_scaled[cols] = scaler.transform(X_val_scaled[cols])
2356
+ return X_train_scaled, X_val_scaled, scaler
2357
+
2358
+ def cross_val_generic(
2359
+ self,
2360
+ trial: optuna.trial.Trial,
2361
+ hyperparameter_space: Dict[str, Callable[[optuna.trial.Trial], Any]],
2362
+ data_provider: Callable[[], Tuple[pd.DataFrame, pd.Series, Optional[pd.Series]]],
2363
+ model_builder: Callable[[Dict[str, Any]], Any],
2364
+ metric_fn: Callable[[pd.Series, np.ndarray, Optional[pd.Series]], float],
2365
+ sample_limit: Optional[int] = None,
2366
+ preprocess_fn: Optional[Callable[[
2367
+ pd.DataFrame, pd.DataFrame], Tuple[pd.DataFrame, pd.DataFrame]]] = None,
2368
+ fit_predict_fn: Optional[
2369
+ Callable[[Any, pd.DataFrame, pd.Series, Optional[pd.Series],
2370
+ pd.DataFrame, pd.Series, Optional[pd.Series],
2371
+ optuna.trial.Trial], np.ndarray]
2372
+ ] = None,
2373
+ cleanup_fn: Optional[Callable[[Any], None]] = None,
2374
+ splitter: Optional[Iterable[Tuple[np.ndarray, np.ndarray]]] = None) -> float:
2375
+ """通用的留出/交叉验证辅助函数,用于复用调参流程。
2376
+
2377
+ 参数:
2378
+ trial: 当前 Optuna trial。
2379
+ hyperparameter_space: 参数采样器字典,键为参数名。
2380
+ data_provider: 返回 (X, y, sample_weight) 的回调。
2381
+ model_builder: 每个折构造新模型的回调。
2382
+ metric_fn: 计算损失或得分的函数,入参为 y_true、y_pred、weight。
2383
+ sample_limit: 可选样本上限,超出时随机抽样。
2384
+ preprocess_fn: 可选的折内预处理函数,输入 (X_train, X_val)。
2385
+ fit_predict_fn: 可选自定义训练与预测逻辑,返回验证集预测。
2386
+ cleanup_fn: 可选清理函数,每个折结束后调用。
2387
+ splitter: 可选的 (train_idx, val_idx) 迭代器;默认使用单个 ShuffleSplit。
2388
+
2389
+ 返回:
2390
+ 各折验证指标的平均值。
2391
+ """
2392
+ params: Optional[Dict[str, Any]] = None
2393
+ if self._distributed_forced_params is not None:
2394
+ params = self._distributed_forced_params
2395
+ self._distributed_forced_params = None
2396
+ else:
2397
+ if trial is None:
2398
+ raise RuntimeError(
2399
+ "Missing Optuna trial for parameter sampling.")
2400
+ params = {name: sampler(trial)
2401
+ for name, sampler in hyperparameter_space.items()}
2402
+ if self._should_use_distributed_optuna():
2403
+ self._distributed_prepare_trial(params)
2404
+ X_all, y_all, w_all = data_provider()
2405
+ if sample_limit is not None and len(X_all) > sample_limit:
2406
+ sampled_idx = X_all.sample(
2407
+ n=sample_limit,
2408
+ random_state=self.ctx.rand_seed
2409
+ ).index
2410
+ X_all = X_all.loc[sampled_idx]
2411
+ y_all = y_all.loc[sampled_idx]
2412
+ w_all = w_all.loc[sampled_idx] if w_all is not None else None
2413
+
2414
+ splits = splitter or [next(ShuffleSplit(
2415
+ n_splits=int(1 / self.ctx.prop_test),
2416
+ test_size=self.ctx.prop_test,
2417
+ random_state=self.ctx.rand_seed
2418
+ ).split(X_all))]
2419
+
2420
+ losses: List[float] = []
2421
+ for train_idx, val_idx in splits:
2422
+ X_train = X_all.iloc[train_idx]
2423
+ y_train = y_all.iloc[train_idx]
2424
+ X_val = X_all.iloc[val_idx]
2425
+ y_val = y_all.iloc[val_idx]
2426
+ w_train = w_all.iloc[train_idx] if w_all is not None else None
2427
+ w_val = w_all.iloc[val_idx] if w_all is not None else None
2428
+
2429
+ if preprocess_fn:
2430
+ X_train, X_val = preprocess_fn(X_train, X_val)
2431
+
2432
+ model = model_builder(params)
2433
+ try:
2434
+ if fit_predict_fn:
2435
+ y_pred = fit_predict_fn(
2436
+ model, X_train, y_train, w_train,
2437
+ X_val, y_val, w_val, trial
2438
+ )
2439
+ else:
2440
+ fit_kwargs = {}
2441
+ if w_train is not None:
2442
+ fit_kwargs["sample_weight"] = w_train
2443
+ model.fit(X_train, y_train, **fit_kwargs)
2444
+ y_pred = model.predict(X_val)
2445
+ losses.append(metric_fn(y_val, y_pred, w_val))
2446
+ finally:
2447
+ if cleanup_fn:
2448
+ cleanup_fn(model)
2449
+ self._clean_gpu()
2450
+
2451
+ return float(np.mean(losses))
2452
+
2453
+ # 预测 + 缓存逻辑
2454
+ def _predict_and_cache(self,
2455
+ model,
2456
+ pred_prefix: str,
2457
+ use_oht: bool = False,
2458
+ design_fn=None,
2459
+ predict_kwargs_train: Optional[Dict[str, Any]] = None,
2460
+ predict_kwargs_test: Optional[Dict[str, Any]] = None) -> None:
2461
+ if design_fn:
2462
+ X_train = design_fn(train=True)
2463
+ X_test = design_fn(train=False)
2464
+ elif use_oht:
2465
+ X_train = self.ctx.train_oht_scl_data[self.ctx.var_nmes]
2466
+ X_test = self.ctx.test_oht_scl_data[self.ctx.var_nmes]
2467
+ else:
2468
+ X_train = self.ctx.train_data[self.ctx.factor_nmes]
2469
+ X_test = self.ctx.test_data[self.ctx.factor_nmes]
2470
+
2471
+ preds_train = model.predict(X_train, **(predict_kwargs_train or {}))
2472
+ preds_test = model.predict(X_test, **(predict_kwargs_test or {}))
2473
+
2474
+ self.ctx.train_data[f'pred_{pred_prefix}'] = preds_train
2475
+ self.ctx.test_data[f'pred_{pred_prefix}'] = preds_test
2476
+ self.ctx.train_data[f'w_pred_{pred_prefix}'] = (
2477
+ self.ctx.train_data[f'pred_{pred_prefix}'] *
2478
+ self.ctx.train_data[self.ctx.weight_nme]
2479
+ )
2480
+ self.ctx.test_data[f'w_pred_{pred_prefix}'] = (
2481
+ self.ctx.test_data[f'pred_{pred_prefix}'] *
2482
+ self.ctx.test_data[self.ctx.weight_nme]
2483
+ )
2484
+
2485
+ def _fit_predict_cache(self,
2486
+ model,
2487
+ X_train,
2488
+ y_train,
2489
+ sample_weight,
2490
+ pred_prefix: str,
2491
+ use_oht: bool = False,
2492
+ design_fn=None,
2493
+ fit_kwargs: Optional[Dict[str, Any]] = None,
2494
+ sample_weight_arg: Optional[str] = 'sample_weight',
2495
+ predict_kwargs_train: Optional[Dict[str, Any]] = None,
2496
+ predict_kwargs_test: Optional[Dict[str, Any]] = None) -> None:
2497
+ fit_kwargs = fit_kwargs.copy() if fit_kwargs else {}
2498
+ if sample_weight is not None and sample_weight_arg:
2499
+ fit_kwargs.setdefault(sample_weight_arg, sample_weight)
2500
+ model.fit(X_train, y_train, **fit_kwargs)
2501
+ self.ctx.model_label.append(self.label)
2502
+ self._predict_and_cache(
2503
+ model,
2504
+ pred_prefix,
2505
+ use_oht=use_oht,
2506
+ design_fn=design_fn,
2507
+ predict_kwargs_train=predict_kwargs_train,
2508
+ predict_kwargs_test=predict_kwargs_test)
2509
+
2510
+
2511
+ class XGBTrainer(TrainerBase):
2512
+ def __init__(self, context: "BayesOptModel") -> None:
2513
+ super().__init__(context, 'Xgboost', 'Xgboost')
2514
+ self.model: Optional[xgb.XGBRegressor] = None
2515
+
2516
+ def _build_estimator(self) -> xgb.XGBRegressor:
2517
+ params = dict(
2518
+ objective=self.ctx.obj,
2519
+ random_state=self.ctx.rand_seed,
2520
+ subsample=0.9,
2521
+ tree_method='gpu_hist' if self.ctx.use_gpu else 'hist',
2522
+ enable_categorical=True,
2523
+ predictor='gpu_predictor' if self.ctx.use_gpu else 'cpu_predictor'
2524
+ )
2525
+ if self.ctx.use_gpu:
2526
+ params['gpu_id'] = 0
2527
+ print(f">>> XGBoost using GPU ID: 0 (Single GPU Mode)")
2528
+ return xgb.XGBRegressor(**params)
2529
+
2530
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2531
+ learning_rate = trial.suggest_float(
2532
+ 'learning_rate', 1e-5, 1e-1, log=True)
2533
+ gamma = trial.suggest_float('gamma', 0, 10000)
2534
+ max_depth = trial.suggest_int('max_depth', 3, 25)
2535
+ n_estimators = trial.suggest_int('n_estimators', 10, 500, step=10)
2536
+ min_child_weight = trial.suggest_int(
2537
+ 'min_child_weight', 100, 10000, step=100)
2538
+ reg_alpha = trial.suggest_float('reg_alpha', 1e-10, 1, log=True)
2539
+ reg_lambda = trial.suggest_float('reg_lambda', 1e-10, 1, log=True)
2540
+ if self.ctx.obj == 'reg:tweedie':
2541
+ tweedie_variance_power = trial.suggest_float(
2542
+ 'tweedie_variance_power', 1, 2)
2543
+ elif self.ctx.obj == 'count:poisson':
2544
+ tweedie_variance_power = 1
2545
+ elif self.ctx.obj == 'reg:gamma':
2546
+ tweedie_variance_power = 2
2547
+ else:
2548
+ tweedie_variance_power = 1.5
2549
+ clf = self._build_estimator()
2550
+ params = {
2551
+ 'learning_rate': learning_rate,
2552
+ 'gamma': gamma,
2553
+ 'max_depth': max_depth,
2554
+ 'n_estimators': n_estimators,
2555
+ 'min_child_weight': min_child_weight,
2556
+ 'reg_alpha': reg_alpha,
2557
+ 'reg_lambda': reg_lambda
2558
+ }
2559
+ if self.ctx.obj == 'reg:tweedie':
2560
+ params['tweedie_variance_power'] = tweedie_variance_power
2561
+ clf.set_params(**params)
2562
+ n_jobs = 1 if self.ctx.use_gpu else int(1 / self.ctx.prop_test)
2563
+ acc = cross_val_score(
2564
+ clf,
2565
+ self.ctx.train_data[self.ctx.factor_nmes],
2566
+ self.ctx.train_data[self.ctx.resp_nme].values,
2567
+ fit_params=self.ctx.fit_params,
2568
+ cv=self.ctx.cv,
2569
+ scoring=make_scorer(
2570
+ mean_tweedie_deviance,
2571
+ power=tweedie_variance_power,
2572
+ greater_is_better=False),
2573
+ error_score='raise',
2574
+ n_jobs=n_jobs
2575
+ ).mean()
2576
+ return -acc
2577
+
2578
+ def train(self) -> None:
2579
+ if not self.best_params:
2580
+ raise RuntimeError('请先运行 tune() 以获得 XGB 最优参数。')
2581
+ self.model = self._build_estimator()
2582
+ self.model.set_params(**self.best_params)
2583
+ self._fit_predict_cache(
2584
+ self.model,
2585
+ self.ctx.train_data[self.ctx.factor_nmes],
2586
+ self.ctx.train_data[self.ctx.resp_nme].values,
2587
+ sample_weight=None,
2588
+ pred_prefix='xgb',
2589
+ fit_kwargs=self.ctx.fit_params,
2590
+ sample_weight_arg=None # 样本权重已通过 fit_kwargs 传入
2591
+ )
2592
+ self.ctx.xgb_best = self.model
2593
+
2594
+
2595
+ class GLMTrainer(TrainerBase):
2596
+ def __init__(self, context: "BayesOptModel") -> None:
2597
+ super().__init__(context, 'GLM', 'GLM')
2598
+ self.model = None
2599
+
2600
+ def _select_family(self, tweedie_power: Optional[float] = None):
2601
+ if self.ctx.task_type == 'classification':
2602
+ return sm.families.Binomial()
2603
+ if self.ctx.obj == 'count:poisson':
2604
+ return sm.families.Poisson()
2605
+ if self.ctx.obj == 'reg:gamma':
2606
+ return sm.families.Gamma()
2607
+ power = tweedie_power if tweedie_power is not None else 1.5
2608
+ return sm.families.Tweedie(var_power=power, link=sm.families.links.log())
2609
+
2610
+ def _prepare_design(self, data: pd.DataFrame) -> pd.DataFrame:
2611
+ # 为 statsmodels 设计矩阵添加截距项
2612
+ X = data[self.ctx.var_nmes]
2613
+ return sm.add_constant(X, has_constant='add')
2614
+
2615
+ def _metric_power(self, family, tweedie_power: Optional[float]) -> float:
2616
+ if isinstance(family, sm.families.Poisson):
2617
+ return 1.0
2618
+ if isinstance(family, sm.families.Gamma):
2619
+ return 2.0
2620
+ if isinstance(family, sm.families.Tweedie):
2621
+ return tweedie_power if tweedie_power is not None else getattr(family, 'var_power', 1.5)
2622
+ return 1.5
2623
+
2624
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2625
+ param_space = {
2626
+ "alpha": lambda t: t.suggest_float('alpha', 1e-6, 1e2, log=True),
2627
+ "l1_ratio": lambda t: t.suggest_float('l1_ratio', 0.0, 1.0)
2628
+ }
2629
+ if self.ctx.task_type == 'regression' and self.ctx.obj == 'reg:tweedie':
2630
+ param_space["tweedie_power"] = lambda t: t.suggest_float(
2631
+ 'tweedie_power', 1.0, 2.0)
2632
+
2633
+ def data_provider():
2634
+ data = self.ctx.train_oht_data if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data
2635
+ assert data is not None, "Preprocessed training data is missing."
2636
+ return data[self.ctx.var_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2637
+
2638
+ def preprocess_fn(X_train, X_val):
2639
+ X_train_s, X_val_s, _ = self._standardize_fold(
2640
+ X_train, X_val, self.ctx.num_features)
2641
+ return self._prepare_design(X_train_s), self._prepare_design(X_val_s)
2642
+
2643
+ metric_ctx: Dict[str, Any] = {}
2644
+
2645
+ def model_builder(params):
2646
+ family = self._select_family(params.get("tweedie_power"))
2647
+ metric_ctx["family"] = family
2648
+ metric_ctx["tweedie_power"] = params.get("tweedie_power")
2649
+ return {
2650
+ "family": family,
2651
+ "alpha": params["alpha"],
2652
+ "l1_ratio": params["l1_ratio"],
2653
+ "tweedie_power": params.get("tweedie_power")
2654
+ }
2655
+
2656
+ def fit_predict(model_cfg, X_train, y_train, w_train, X_val, y_val, w_val, _trial):
2657
+ glm = sm.GLM(y_train, X_train,
2658
+ family=model_cfg["family"],
2659
+ freq_weights=w_train)
2660
+ result = glm.fit_regularized(
2661
+ alpha=model_cfg["alpha"],
2662
+ L1_wt=model_cfg["l1_ratio"],
2663
+ maxiter=200
2664
+ )
2665
+ return result.predict(X_val)
2666
+
2667
+ def metric_fn(y_true, y_pred, weight):
2668
+ if self.ctx.task_type == 'classification':
2669
+ y_pred_clipped = np.clip(y_pred, EPS, 1 - EPS)
2670
+ return log_loss(y_true, y_pred_clipped, sample_weight=weight)
2671
+ y_pred_safe = np.maximum(y_pred, EPS)
2672
+ return mean_tweedie_deviance(
2673
+ y_true,
2674
+ y_pred_safe,
2675
+ sample_weight=weight,
2676
+ power=self._metric_power(
2677
+ metric_ctx.get("family"), metric_ctx.get("tweedie_power"))
2678
+ )
2679
+
2680
+ return self.cross_val_generic(
2681
+ trial=trial,
2682
+ hyperparameter_space=param_space,
2683
+ data_provider=data_provider,
2684
+ model_builder=model_builder,
2685
+ metric_fn=metric_fn,
2686
+ preprocess_fn=preprocess_fn,
2687
+ fit_predict_fn=fit_predict,
2688
+ splitter=self.ctx.cv.split(self.ctx.train_oht_data[self.ctx.var_nmes]
2689
+ if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data[self.ctx.var_nmes])
2690
+ )
2691
+
2692
+ def train(self) -> None:
2693
+ if not self.best_params:
2694
+ raise RuntimeError('请先运行 tune() 以获得 GLM 最优参数。')
2695
+ tweedie_power = self.best_params.get('tweedie_power')
2696
+ family = self._select_family(tweedie_power)
2697
+
2698
+ X_train = self._prepare_design(self.ctx.train_oht_scl_data)
2699
+ y_train = self.ctx.train_oht_scl_data[self.ctx.resp_nme]
2700
+ w_train = self.ctx.train_oht_scl_data[self.ctx.weight_nme]
2701
+
2702
+ glm = sm.GLM(y_train, X_train, family=family,
2703
+ freq_weights=w_train)
2704
+ self.model = glm.fit_regularized(
2705
+ alpha=self.best_params['alpha'],
2706
+ L1_wt=self.best_params['l1_ratio'],
2707
+ maxiter=300
2708
+ )
2709
+
2710
+ self.ctx.glm_best = self.model
2711
+ self.ctx.model_label += [self.label]
2712
+ self._predict_and_cache(
2713
+ self.model,
2714
+ 'glm',
2715
+ design_fn=lambda train: self._prepare_design(
2716
+ self.ctx.train_oht_scl_data if train else self.ctx.test_oht_scl_data
2717
+ )
2718
+ )
2719
+
2720
+
2721
+ class ResNetTrainer(TrainerBase):
2722
+ def __init__(self, context: "BayesOptModel") -> None:
2723
+ if context.task_type == 'classification':
2724
+ super().__init__(context, 'ResNetClassifier', 'ResNet')
2725
+ else:
2726
+ super().__init__(context, 'ResNet', 'ResNet')
2727
+ self.model: Optional[ResNetSklearn] = None
2728
+ self.enable_distributed_optuna = bool(context.config.use_resn_ddp)
2729
+
2730
+ # ========= 交叉验证(BayesOpt 用) =========
2731
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2732
+ # 针对 ResNet 的交叉验证流程,重点控制显存:
2733
+ # - 每个 fold 单独创建 ResNetSklearn,结束立刻释放资源;
2734
+ # - fold 完成后迁移模型到 CPU,删除对象并调用 gc/empty_cache;
2735
+ # - 可选:BayesOpt 期间只抽样部分训练集以减少显存压力。
2736
+
2737
+ base_tw_power = None
2738
+ if self.ctx.task_type == 'regression':
2739
+ if self.ctx.obj == 'count:poisson':
2740
+ base_tw_power = 1.0
2741
+ elif self.ctx.obj == 'reg:gamma':
2742
+ base_tw_power = 2.0
2743
+ else:
2744
+ base_tw_power = 1.5
2745
+
2746
+ def data_provider():
2747
+ data = self.ctx.train_oht_data if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data
2748
+ assert data is not None, "Preprocessed training data is missing."
2749
+ return data[self.ctx.var_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2750
+
2751
+ metric_ctx: Dict[str, Any] = {}
2752
+
2753
+ def model_builder(params):
2754
+ power = params.get("tw_power", base_tw_power)
2755
+ metric_ctx["tw_power"] = power
2756
+ return ResNetSklearn(
2757
+ model_nme=self.ctx.model_nme,
2758
+ input_dim=len(self.ctx.var_nmes),
2759
+ hidden_dim=params["hidden_dim"],
2760
+ block_num=params["block_num"],
2761
+ task_type=self.ctx.task_type,
2762
+ epochs=self.ctx.epochs,
2763
+ tweedie_power=power,
2764
+ learning_rate=params["learning_rate"],
2765
+ patience=5,
2766
+ use_layernorm=True,
2767
+ dropout=0.1,
2768
+ residual_scale=0.1,
2769
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2770
+ use_ddp=self.ctx.config.use_resn_ddp
2771
+ )
2772
+
2773
+ def preprocess_fn(X_train, X_val):
2774
+ X_train_s, X_val_s, _ = self._standardize_fold(
2775
+ X_train, X_val, self.ctx.num_features)
2776
+ return X_train_s, X_val_s
2777
+
2778
+ def fit_predict(model, X_train, y_train, w_train, X_val, y_val, w_val, trial_obj):
2779
+ model.fit(
2780
+ X_train, y_train, w_train,
2781
+ X_val, y_val, w_val,
2782
+ trial=trial_obj
2783
+ )
2784
+ return model.predict(X_val)
2785
+
2786
+ def metric_fn(y_true, y_pred, weight):
2787
+ if self.ctx.task_type == 'regression':
2788
+ return mean_tweedie_deviance(
2789
+ y_true,
2790
+ y_pred,
2791
+ sample_weight=weight,
2792
+ power=metric_ctx.get("tw_power", base_tw_power)
2793
+ )
2794
+ return log_loss(y_true, y_pred, sample_weight=weight)
2795
+
2796
+ sample_cap = data_provider()[0]
2797
+ max_rows_for_resnet_bo = min(100000, int(len(sample_cap)/5))
2798
+
2799
+ return self.cross_val_generic(
2800
+ trial=trial,
2801
+ hyperparameter_space={
2802
+ "learning_rate": lambda t: t.suggest_float('learning_rate', 1e-6, 1e-2, log=True),
2803
+ "hidden_dim": lambda t: t.suggest_int('hidden_dim', 8, 32, step=2),
2804
+ "block_num": lambda t: t.suggest_int('block_num', 2, 10),
2805
+ **({"tw_power": lambda t: t.suggest_float('tw_power', 1.0, 2.0)} if self.ctx.task_type == 'regression' and self.ctx.obj == 'reg:tweedie' else {})
2806
+ },
2807
+ data_provider=data_provider,
2808
+ model_builder=model_builder,
2809
+ metric_fn=metric_fn,
2810
+ sample_limit=max_rows_for_resnet_bo if len(
2811
+ sample_cap) > max_rows_for_resnet_bo > 0 else None,
2812
+ preprocess_fn=preprocess_fn,
2813
+ fit_predict_fn=fit_predict,
2814
+ cleanup_fn=lambda m: getattr(
2815
+ getattr(m, "resnet", None), "to", lambda *_args, **_kwargs: None)("cpu")
2816
+ )
2817
+
2818
+ # ========= 用最优超参训练最终 ResNet =========
2819
+ def train(self) -> None:
2820
+ if not self.best_params:
2821
+ raise RuntimeError('请先运行 tune() 以获得 ResNet 最优参数。')
2822
+
2823
+ self.model = ResNetSklearn(
2824
+ model_nme=self.ctx.model_nme,
2825
+ input_dim=self.ctx.train_oht_scl_data[self.ctx.var_nmes].shape[1],
2826
+ task_type=self.ctx.task_type,
2827
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2828
+ use_ddp=self.ctx.config.use_resn_ddp
2829
+ )
2830
+ self.model.set_params(self.best_params)
2831
+
2832
+ self._fit_predict_cache(
2833
+ self.model,
2834
+ self.ctx.train_oht_scl_data[self.ctx.var_nmes],
2835
+ self.ctx.train_oht_scl_data[self.ctx.resp_nme],
2836
+ sample_weight=self.ctx.train_oht_scl_data[self.ctx.weight_nme],
2837
+ pred_prefix='resn',
2838
+ use_oht=True,
2839
+ sample_weight_arg='w_train'
2840
+ )
2841
+
2842
+ # 方便外部调用
2843
+ self.ctx.resn_best = self.model
2844
+
2845
+ # ========= 保存 / 加载 =========
2846
+ # ResNet 以 state_dict 形式保存,需要专用的加载流程,因此保留自定义加载方法
2847
+ # 保存逻辑已在 TrainerBase 中实现(会自动检查 .resnet 属性)
2848
+
2849
+ def load(self) -> None:
2850
+ # 将磁盘中的 ResNet 权重加载到当前设备,保持与上下文一致。
2851
+ path = self.output.model_path(self._get_model_filename())
2852
+ if os.path.exists(path):
2853
+ resn_loaded = ResNetSklearn(
2854
+ model_nme=self.ctx.model_nme,
2855
+ input_dim=self.ctx.train_oht_scl_data[self.ctx.var_nmes].shape[1],
2856
+ task_type=self.ctx.task_type,
2857
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2858
+ use_ddp=self.ctx.config.use_resn_ddp
2859
+ )
2860
+ state_dict = torch.load(path, map_location='cpu')
2861
+ resn_loaded.resnet.load_state_dict(state_dict)
2862
+
2863
+ self._move_to_device(resn_loaded)
2864
+ self.model = resn_loaded
2865
+ self.ctx.resn_best = self.model
2866
+ else:
2867
+ print(f"[ResNetTrainer.load] 未找到模型文件:{path}")
2868
+
2869
+
2870
+ class FTTrainer(TrainerBase):
2871
+ def __init__(self, context: "BayesOptModel") -> None:
2872
+ if context.task_type == 'classification':
2873
+ super().__init__(context, 'FTTransformerClassifier', 'FTTransformer')
2874
+ else:
2875
+ super().__init__(context, 'FTTransformer', 'FTTransformer')
2876
+ self.model: Optional[FTTransformerSklearn] = None
2877
+ self.enable_distributed_optuna = bool(context.config.use_ft_ddp)
2878
+
2879
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2880
+ # 针对 FT-Transformer 的交叉验证,重点同样在显存控制:
2881
+ # - 收缩超参搜索空间,防止不必要的超大模型;
2882
+ # - 每个 fold 结束后立即释放 GPU 显存,确保下一个 trial 顺利进行。
2883
+ # 超参空间适当缩小一点,避免特别大的模型
2884
+ param_space: Dict[str, Callable[[optuna.trial.Trial], Any]] = {
2885
+ "learning_rate": lambda t: t.suggest_float('learning_rate', 1e-5, 5e-4, log=True),
2886
+ "d_model": lambda t: t.suggest_int('d_model', 8, 64, step=8),
2887
+ "n_heads": lambda t: t.suggest_categorical('n_heads', [2, 4, 8]),
2888
+ "n_layers": lambda t: t.suggest_int('n_layers', 2, 8),
2889
+ "dropout": lambda t: t.suggest_float('dropout', 0.0, 0.2)
2890
+ }
2891
+ if self.ctx.task_type == 'regression' and self.ctx.obj == 'reg:tweedie':
2892
+ param_space["tw_power"] = lambda t: t.suggest_float(
2893
+ 'tw_power', 1.0, 2.0)
2894
+ geo_enabled = bool(
2895
+ self.ctx.geo_token_cols or self.ctx.config.geo_feature_nmes)
2896
+ if geo_enabled:
2897
+ # 仅在启用地理 token 时调节 GNN 相关超参
2898
+ param_space.update({
2899
+ "geo_token_hidden_dim": lambda t: t.suggest_int('geo_token_hidden_dim', 16, 128, step=16),
2900
+ "geo_token_layers": lambda t: t.suggest_int('geo_token_layers', 1, 4),
2901
+ "geo_token_k_neighbors": lambda t: t.suggest_int('geo_token_k_neighbors', 5, 20),
2902
+ "geo_token_dropout": lambda t: t.suggest_float('geo_token_dropout', 0.0, 0.3),
2903
+ "geo_token_learning_rate": lambda t: t.suggest_float('geo_token_learning_rate', 1e-4, 5e-3, log=True),
2904
+ })
2905
+
2906
+ metric_ctx: Dict[str, Any] = {}
2907
+ geo_tokens_cache = self.ctx.train_geo_tokens
2908
+
2909
+ def data_provider():
2910
+ data = self.ctx.train_data
2911
+ return data[self.ctx.factor_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2912
+
2913
+ def model_builder(params):
2914
+ d_model = params["d_model"]
2915
+ n_layers = params["n_layers"]
2916
+ token_count = len(self.ctx.factor_nmes) + \
2917
+ (1 if self.ctx.geo_token_cols else 0)
2918
+ approx_units = d_model * n_layers * max(1, token_count)
2919
+ if approx_units > 12_000_000:
2920
+ print(
2921
+ f"[FTTrainer] Trial pruned early: d_model={d_model}, n_layers={n_layers} -> approx_units={approx_units}")
2922
+ raise optuna.TrialPruned(
2923
+ "config exceeds safe memory budget; prune before training")
2924
+ geo_params_local = {k: v for k, v in params.items()
2925
+ if k.startswith("geo_token_")}
2926
+
2927
+ tw_power = params.get("tw_power")
2928
+ if self.ctx.task_type == 'regression':
2929
+ if self.ctx.obj == 'count:poisson':
2930
+ tw_power = 1.0
2931
+ elif self.ctx.obj == 'reg:gamma':
2932
+ tw_power = 2.0
2933
+ elif tw_power is None:
2934
+ tw_power = 1.5
2935
+ metric_ctx["tw_power"] = tw_power
2936
+
2937
+ return FTTransformerSklearn(
2938
+ model_nme=self.ctx.model_nme,
2939
+ num_cols=self.ctx.num_features,
2940
+ cat_cols=self.ctx.cate_list,
2941
+ d_model=d_model,
2942
+ n_heads=params["n_heads"],
2943
+ n_layers=n_layers,
2944
+ dropout=params["dropout"],
2945
+ task_type=self.ctx.task_type,
2946
+ epochs=self.ctx.epochs,
2947
+ tweedie_power=tw_power,
2948
+ learning_rate=params["learning_rate"],
2949
+ patience=5,
2950
+ use_data_parallel=self.ctx.config.use_ft_data_parallel,
2951
+ use_ddp=self.ctx.config.use_ft_ddp
2952
+ ).set_params({"_geo_params": geo_params_local} if geo_enabled else {})
2953
+
2954
+ def fit_predict(model, X_train, y_train, w_train, X_val, y_val, w_val, trial_obj):
2955
+ geo_train = geo_val = None
2956
+ if geo_enabled:
2957
+ geo_params = getattr(model, "_geo_params", {})
2958
+ built = self.ctx._build_geo_tokens(geo_params)
2959
+ if built is not None:
2960
+ geo_train_full, _, _, _ = built
2961
+ geo_train = geo_train_full.loc[X_train.index]
2962
+ geo_val = geo_train_full.loc[X_val.index]
2963
+ elif geo_tokens_cache is not None:
2964
+ # fallback to cached tokens if available
2965
+ geo_train = geo_tokens_cache.loc[X_train.index]
2966
+ geo_val = geo_tokens_cache.loc[X_val.index]
2967
+ model.fit(
2968
+ X_train, y_train, w_train,
2969
+ X_val, y_val, w_val,
2970
+ trial=trial_obj,
2971
+ geo_train=geo_train,
2972
+ geo_val=geo_val
2973
+ )
2974
+ return model.predict(X_val, geo_tokens=geo_val)
2975
+
2976
+ def metric_fn(y_true, y_pred, weight):
2977
+ if self.ctx.task_type == 'regression':
2978
+ return mean_tweedie_deviance(
2979
+ y_true,
2980
+ y_pred,
2981
+ sample_weight=weight,
2982
+ power=metric_ctx.get("tw_power", 1.5)
2983
+ )
2984
+ return log_loss(y_true, y_pred, sample_weight=weight)
2985
+
2986
+ data_for_cap = data_provider()[0]
2987
+ max_rows_for_ft_bo = min(1000000, int(len(data_for_cap)/2))
2988
+
2989
+ return self.cross_val_generic(
2990
+ trial=trial,
2991
+ hyperparameter_space=param_space,
2992
+ data_provider=data_provider,
2993
+ model_builder=model_builder,
2994
+ metric_fn=metric_fn,
2995
+ sample_limit=max_rows_for_ft_bo if len(
2996
+ data_for_cap) > max_rows_for_ft_bo > 0 else None,
2997
+ fit_predict_fn=fit_predict,
2998
+ cleanup_fn=lambda m: getattr(
2999
+ getattr(m, "ft", None), "to", lambda *_args, **_kwargs: None)("cpu")
3000
+ )
3001
+
3002
+ def train(self) -> None:
3003
+ if not self.best_params:
3004
+ raise RuntimeError('请先运行 tune() 以获得 FT-Transformer 最优参数。')
3005
+ self.model = FTTransformerSklearn(
3006
+ model_nme=self.ctx.model_nme,
3007
+ num_cols=self.ctx.num_features,
3008
+ cat_cols=self.ctx.cate_list,
3009
+ task_type=self.ctx.task_type,
3010
+ use_data_parallel=self.ctx.config.use_ft_data_parallel,
3011
+ use_ddp=self.ctx.config.use_ft_ddp
3012
+ )
3013
+ self.model.set_params(self.best_params)
3014
+ geo_train = self.ctx.train_geo_tokens
3015
+ geo_test = self.ctx.test_geo_tokens
3016
+ fit_kwargs = {}
3017
+ predict_kwargs_train = None
3018
+ predict_kwargs_test = None
3019
+ if geo_train is not None and geo_test is not None:
3020
+ fit_kwargs["geo_train"] = geo_train
3021
+ predict_kwargs_train = {"geo_tokens": geo_train}
3022
+ predict_kwargs_test = {"geo_tokens": geo_test}
3023
+ self._fit_predict_cache(
3024
+ self.model,
3025
+ self.ctx.train_data[self.ctx.factor_nmes],
3026
+ self.ctx.train_data[self.ctx.resp_nme],
3027
+ sample_weight=self.ctx.train_data[self.ctx.weight_nme],
3028
+ pred_prefix='ft',
3029
+ sample_weight_arg='w_train',
3030
+ fit_kwargs=fit_kwargs,
3031
+ predict_kwargs_train=predict_kwargs_train,
3032
+ predict_kwargs_test=predict_kwargs_test
3033
+ )
3034
+ self.ctx.ft_best = self.model
3035
+
3036
+
3037
+ # =============================================================================
3038
+ # BayesOpt 调度与 SHAP 工具集
3039
+ # =============================================================================
3040
+ class BayesOptModel:
3041
+ def __init__(self, train_data, test_data,
3042
+ model_nme, resp_nme, weight_nme, factor_nmes, task_type='regression',
3043
+ binary_resp_nme=None,
3044
+ cate_list=None, prop_test=0.25, rand_seed=None,
3045
+ epochs=100, use_gpu=True,
3046
+ use_resn_data_parallel: bool = False, use_ft_data_parallel: bool = False,
3047
+ use_gnn_data_parallel: bool = False,
3048
+ use_resn_ddp: bool = False, use_ft_ddp: bool = False,
3049
+ use_gnn_ddp: bool = False,
3050
+ output_dir: Optional[str] = None,
3051
+ gnn_use_approx_knn: bool = True,
3052
+ gnn_approx_knn_threshold: int = 50000,
3053
+ gnn_graph_cache: Optional[str] = None,
3054
+ gnn_max_gpu_knn_nodes: Optional[int] = 200000,
3055
+ gnn_knn_gpu_mem_ratio: float = 0.9,
3056
+ gnn_knn_gpu_mem_overhead: float = 2.0):
3057
+ """封装各类训练器的 BayesOpt 调度入口。
3058
+
3059
+ 参数:
3060
+ train_data: 训练集 DataFrame。
3061
+ test_data: 测试集 DataFrame。
3062
+ model_nme: 模型名称前缀,用于输出文件。
3063
+ resp_nme: 目标列名。
3064
+ weight_nme: 样本权重列名。
3065
+ factor_nmes: 特征列名列表。
3066
+ task_type: 'regression' 或 'classification'。
3067
+ binary_resp_nme: 可选的二分类目标,用于成交率曲线。
3068
+ cate_list: 类别型特征列表。
3069
+ prop_test: 交叉验证中验证集的占比。
3070
+ rand_seed: 随机种子。
3071
+ epochs: 神经网络训练轮数。
3072
+ use_gpu: 是否优先使用 GPU。
3073
+ use_resn_data_parallel: ResNet 是否启用 DataParallel。
3074
+ use_ft_data_parallel: FTTransformer 是否启用 DataParallel。
3075
+ use_gnn_data_parallel: GNN 是否启用 DataParallel。
3076
+ use_resn_ddp: ResNet 是否启用 DDP。
3077
+ use_ft_ddp: FTTransformer 是否启用 DDP。
3078
+ use_gnn_ddp: GNN 是否启用 DDP。
3079
+ output_dir: 模型、结果与图表的输出根目录。
3080
+ gnn_use_approx_knn: 是否在可用时使用近似 kNN。
3081
+ gnn_approx_knn_threshold: 触发近似 kNN 的行数阈值。
3082
+ gnn_graph_cache: 可选的邻接矩阵缓存路径。
3083
+ gnn_max_gpu_knn_nodes: 超过该节点数则强制使用 CPU kNN 以避免 GPU OOM。
3084
+ gnn_knn_gpu_mem_ratio: GPU kNN 允许使用的可用显存比例。
3085
+ gnn_knn_gpu_mem_overhead: GPU kNN 估算的临时显存放大倍数。
3086
+ """
3087
+ cfg = BayesOptConfig(
3088
+ model_nme=model_nme,
3089
+ task_type=task_type,
3090
+ resp_nme=resp_nme,
3091
+ weight_nme=weight_nme,
3092
+ factor_nmes=list(factor_nmes),
3093
+ binary_resp_nme=binary_resp_nme,
3094
+ cate_list=list(cate_list) if cate_list else None,
3095
+ prop_test=prop_test,
3096
+ rand_seed=rand_seed,
3097
+ epochs=epochs,
3098
+ use_gpu=use_gpu,
3099
+ use_resn_data_parallel=use_resn_data_parallel,
3100
+ use_ft_data_parallel=use_ft_data_parallel,
3101
+ use_resn_ddp=use_resn_ddp,
3102
+ use_gnn_data_parallel=use_gnn_data_parallel,
3103
+ use_ft_ddp=use_ft_ddp,
3104
+ use_gnn_ddp=use_gnn_ddp,
3105
+ gnn_use_approx_knn=gnn_use_approx_knn,
3106
+ gnn_approx_knn_threshold=gnn_approx_knn_threshold,
3107
+ gnn_graph_cache=gnn_graph_cache,
3108
+ gnn_max_gpu_knn_nodes=gnn_max_gpu_knn_nodes,
3109
+ gnn_knn_gpu_mem_ratio=gnn_knn_gpu_mem_ratio,
3110
+ gnn_knn_gpu_mem_overhead=gnn_knn_gpu_mem_overhead,
3111
+ output_dir=output_dir
3112
+ )
3113
+ self.config = cfg
3114
+ self.model_nme = cfg.model_nme
3115
+ self.task_type = cfg.task_type
3116
+ self.resp_nme = cfg.resp_nme
3117
+ self.weight_nme = cfg.weight_nme
3118
+ self.factor_nmes = cfg.factor_nmes
3119
+ self.binary_resp_nme = cfg.binary_resp_nme
3120
+ self.cate_list = list(cfg.cate_list or [])
3121
+ self.prop_test = cfg.prop_test
3122
+ self.epochs = cfg.epochs
3123
+ self.rand_seed = cfg.rand_seed if cfg.rand_seed is not None else np.random.randint(
3124
+ 1, 10000)
3125
+ self.use_gpu = bool(cfg.use_gpu and torch.cuda.is_available())
3126
+ self.output_manager = OutputManager(
3127
+ cfg.output_dir or os.getcwd(), self.model_nme)
3128
+
3129
+ preprocessor = DatasetPreprocessor(train_data, test_data, cfg).run()
3130
+ self.train_data = preprocessor.train_data
3131
+ self.test_data = preprocessor.test_data
3132
+ self.train_oht_data = preprocessor.train_oht_data
3133
+ self.test_oht_data = preprocessor.test_oht_data
3134
+ self.train_oht_scl_data = preprocessor.train_oht_scl_data
3135
+ self.test_oht_scl_data = preprocessor.test_oht_scl_data
3136
+ self.var_nmes = preprocessor.var_nmes
3137
+ self.num_features = preprocessor.num_features
3138
+ self.cat_categories_for_shap = preprocessor.cat_categories_for_shap
3139
+ self.geo_token_cols: List[str] = []
3140
+ self.train_geo_tokens: Optional[pd.DataFrame] = None
3141
+ self.test_geo_tokens: Optional[pd.DataFrame] = None
3142
+ self.geo_gnn_model: Optional[GraphNeuralNetSklearn] = None
3143
+ self._prepare_geo_tokens()
3144
+
3145
+ self.cv = ShuffleSplit(n_splits=int(1/self.prop_test),
3146
+ test_size=self.prop_test,
3147
+ random_state=self.rand_seed)
3148
+ if self.task_type == 'classification':
3149
+ self.obj = 'binary:logistic'
3150
+ else: # 回归任务
3151
+ if 'f' in self.model_nme:
3152
+ self.obj = 'count:poisson'
3153
+ elif 's' in self.model_nme:
3154
+ self.obj = 'reg:gamma'
3155
+ elif 'bc' in self.model_nme:
3156
+ self.obj = 'reg:tweedie'
3157
+ else:
3158
+ self.obj = 'reg:tweedie'
3159
+ self.fit_params = {
3160
+ 'sample_weight': self.train_data[self.weight_nme].values
3161
+ }
3162
+ self.model_label: List[str] = []
3163
+ self.optuna_storage = cfg.optuna_storage
3164
+ self.optuna_study_prefix = cfg.optuna_study_prefix or "bayesopt"
3165
+
3166
+ # 记录各模型训练器,后续统一通过标签访问,方便扩展新模型
3167
+ self.trainers: Dict[str, TrainerBase] = {
3168
+ 'glm': GLMTrainer(self),
3169
+ 'xgb': XGBTrainer(self),
3170
+ 'resn': ResNetTrainer(self),
3171
+ 'ft': FTTrainer(self)
3172
+ }
3173
+ self.xgb_best = None
3174
+ self.resn_best = None
3175
+ self.glm_best = None
3176
+ self.ft_best = None
3177
+ self.best_xgb_params = None
3178
+ self.best_resn_params = None
3179
+ self.best_ft_params = None
3180
+ self.best_xgb_trial = None
3181
+ self.best_resn_trial = None
3182
+ self.best_ft_trial = None
3183
+ self.best_glm_params = None
3184
+ self.best_glm_trial = None
3185
+ self.xgb_load = None
3186
+ self.resn_load = None
3187
+ self.ft_load = None
3188
+
3189
+ def _build_geo_tokens(self, params_override: Optional[Dict[str, Any]] = None):
3190
+ """内部构建函数,支持传入 trial 覆盖超参,失败则返回 None。"""
3191
+ geo_cols = list(self.config.geo_feature_nmes or [])
3192
+ if not geo_cols:
3193
+ return None
3194
+
3195
+ available = [c for c in geo_cols if c in self.train_data.columns]
3196
+ if not available:
3197
+ return None
3198
+
3199
+ # 预处理文本/数值:数值填中位数,文本做标签编码,未知映射到额外索引
3200
+ proc_train = {}
3201
+ proc_test = {}
3202
+ for col in available:
3203
+ s_train = self.train_data[col]
3204
+ s_test = self.test_data[col]
3205
+ if pd.api.types.is_numeric_dtype(s_train):
3206
+ tr = pd.to_numeric(s_train, errors="coerce")
3207
+ te = pd.to_numeric(s_test, errors="coerce")
3208
+ med = np.nanmedian(tr)
3209
+ proc_train[col] = np.nan_to_num(tr, nan=med).astype(np.float32)
3210
+ proc_test[col] = np.nan_to_num(te, nan=med).astype(np.float32)
3211
+ else:
3212
+ cats = pd.Categorical(s_train.astype(str))
3213
+ tr_codes = cats.codes.astype(np.float32, copy=True)
3214
+ tr_codes[tr_codes < 0] = len(cats.categories)
3215
+ te_cats = pd.Categorical(
3216
+ s_test.astype(str), categories=cats.categories)
3217
+ te_codes = te_cats.codes.astype(np.float32, copy=True)
3218
+ te_codes[te_codes < 0] = len(cats.categories)
3219
+ proc_train[col] = tr_codes
3220
+ proc_test[col] = te_codes
3221
+
3222
+ train_geo_raw = pd.DataFrame(proc_train, index=self.train_data.index)
3223
+ test_geo_raw = pd.DataFrame(proc_test, index=self.test_data.index)
3224
+
3225
+ scaler = StandardScaler()
3226
+ train_geo = pd.DataFrame(
3227
+ scaler.fit_transform(train_geo_raw),
3228
+ columns=available,
3229
+ index=self.train_data.index
3230
+ )
3231
+ test_geo = pd.DataFrame(
3232
+ scaler.transform(test_geo_raw),
3233
+ columns=available,
3234
+ index=self.test_data.index
3235
+ )
3236
+
3237
+ tw_power = None
3238
+ if self.task_type == 'regression':
3239
+ if 'f' in self.model_nme:
3240
+ tw_power = 1.0
3241
+ elif 's' in self.model_nme:
3242
+ tw_power = 2.0
3243
+ else:
3244
+ tw_power = 1.5
3245
+
3246
+ cfg = params_override or {}
3247
+ try:
3248
+ geo_gnn = GraphNeuralNetSklearn(
3249
+ model_nme=f"{self.model_nme}_geo",
3250
+ input_dim=len(available),
3251
+ hidden_dim=cfg.get("geo_token_hidden_dim",
3252
+ self.config.geo_token_hidden_dim),
3253
+ num_layers=cfg.get("geo_token_layers",
3254
+ self.config.geo_token_layers),
3255
+ k_neighbors=cfg.get("geo_token_k_neighbors",
3256
+ self.config.geo_token_k_neighbors),
3257
+ dropout=cfg.get("geo_token_dropout",
3258
+ self.config.geo_token_dropout),
3259
+ learning_rate=cfg.get(
3260
+ "geo_token_learning_rate", self.config.geo_token_learning_rate),
3261
+ epochs=int(cfg.get("geo_token_epochs",
3262
+ self.config.geo_token_epochs)),
3263
+ patience=5,
3264
+ task_type=self.task_type,
3265
+ tweedie_power=tw_power,
3266
+ use_data_parallel=False,
3267
+ use_ddp=False,
3268
+ use_approx_knn=self.config.gnn_use_approx_knn,
3269
+ approx_knn_threshold=self.config.gnn_approx_knn_threshold,
3270
+ graph_cache_path=None,
3271
+ max_gpu_knn_nodes=self.config.gnn_max_gpu_knn_nodes,
3272
+ knn_gpu_mem_ratio=self.config.gnn_knn_gpu_mem_ratio,
3273
+ knn_gpu_mem_overhead=self.config.gnn_knn_gpu_mem_overhead
3274
+ )
3275
+ geo_gnn.fit(
3276
+ train_geo,
3277
+ self.train_data[self.resp_nme],
3278
+ self.train_data[self.weight_nme]
3279
+ )
3280
+ train_embed = geo_gnn.encode(train_geo)
3281
+ test_embed = geo_gnn.encode(test_geo)
3282
+ cols = [f"geo_token_{i}" for i in range(train_embed.shape[1])]
3283
+ train_tokens = pd.DataFrame(
3284
+ train_embed, index=self.train_data.index, columns=cols)
3285
+ test_tokens = pd.DataFrame(
3286
+ test_embed, index=self.test_data.index, columns=cols)
3287
+ return train_tokens, test_tokens, cols, geo_gnn
3288
+ except Exception as exc:
3289
+ print(f"[GeoToken] 生成失败:{exc}")
3290
+ return None
3291
+
3292
+ def _prepare_geo_tokens(self) -> None:
3293
+ """使用配置默认值构建并持久化地理 token。"""
3294
+ result = self._build_geo_tokens()
3295
+ if result is None:
3296
+ return
3297
+ train_tokens, test_tokens, cols, geo_gnn = result
3298
+ self.train_geo_tokens = train_tokens
3299
+ self.test_geo_tokens = test_tokens
3300
+ self.geo_token_cols = cols
3301
+ self.geo_gnn_model = geo_gnn
3302
+ print(f"[GeoToken] 已生成 {len(cols)} 维地理 token,将注入 FT。")
3303
+
3304
+ # 定义单因素画图函数
3305
+ def plot_oneway(self, n_bins=10):
3306
+ for c in self.factor_nmes:
3307
+ fig = plt.figure(figsize=(7, 5))
3308
+ if c in self.cate_list:
3309
+ group_col = c
3310
+ plot_source = self.train_data
3311
+ else:
3312
+ group_col = f'{c}_bins'
3313
+ bins = pd.qcut(
3314
+ self.train_data[c],
3315
+ n_bins,
3316
+ duplicates='drop' # 注意:如果分位数重复会丢 bin,避免异常终止
3317
+ )
3318
+ plot_source = self.train_data.assign(**{group_col: bins})
3319
+ plot_data = plot_source.groupby(
3320
+ [group_col], observed=True).sum(numeric_only=True)
3321
+ plot_data.reset_index(inplace=True)
3322
+ plot_data['act_v'] = plot_data['w_act'] / \
3323
+ plot_data[self.weight_nme]
3324
+ ax = fig.add_subplot(111)
3325
+ ax.plot(plot_data.index, plot_data['act_v'],
3326
+ label='Actual', color='red')
3327
+ ax.set_title(
3328
+ 'Analysis of %s : Train Data' % group_col,
3329
+ fontsize=8)
3330
+ plt.xticks(plot_data.index,
3331
+ list(plot_data[group_col].astype(str)),
3332
+ rotation=90)
3333
+ if len(list(plot_data[group_col].astype(str))) > 50:
3334
+ plt.xticks(fontsize=3)
3335
+ else:
3336
+ plt.xticks(fontsize=6)
3337
+ plt.yticks(fontsize=6)
3338
+ ax2 = ax.twinx()
3339
+ ax2.bar(plot_data.index,
3340
+ plot_data[self.weight_nme],
3341
+ alpha=0.5, color='seagreen')
3342
+ plt.yticks(fontsize=6)
3343
+ plt.margins(0.05)
3344
+ plt.subplots_adjust(wspace=0.3)
3345
+ save_path = self.output_manager.plot_path(
3346
+ f'00_{self.model_nme}_{group_col}_oneway.png')
3347
+ plt.savefig(save_path, dpi=300)
3348
+ plt.close(fig)
3349
+
3350
+ # 定义通用优化函数
3351
+ def optimize_model(self, model_key: str, max_evals: int = 100):
3352
+ if model_key not in self.trainers:
3353
+ print(f"Warning: Unknown model key: {model_key}")
3354
+ return
3355
+
3356
+ trainer = self.trainers[model_key]
3357
+ trainer.tune(max_evals)
3358
+ trainer.train()
3359
+
3360
+ # 更新上下文字段,保证历史接口的兼容性
3361
+ setattr(self, f"{model_key}_best", trainer.model)
3362
+ setattr(self, f"best_{model_key}_params", trainer.best_params)
3363
+ setattr(self, f"best_{model_key}_trial", trainer.best_trial)
3364
+
3365
+ # 定义GLM贝叶斯优化函数
3366
+ def bayesopt_glm(self, max_evals=50):
3367
+ self.optimize_model('glm', max_evals)
3368
+
3369
+ # 定义Xgboost贝叶斯优化函数
3370
+ def bayesopt_xgb(self, max_evals=100):
3371
+ self.optimize_model('xgb', max_evals)
3372
+
3373
+ # 定义ResNet贝叶斯优化函数
3374
+ def bayesopt_resnet(self, max_evals=100):
3375
+ self.optimize_model('resn', max_evals)
3376
+
3377
+ # 定义 GNN 贝叶斯优化函数
3378
+ def bayesopt_gnn(self, max_evals=50):
3379
+ print("[bayesopt_gnn] 独立 GNN 已停用,地理 GNN 仅用于生成 FT 的 geo token。")
3380
+
3381
+ # 定义 FT-Transformer 贝叶斯优化函数
3382
+ def bayesopt_ft(self, max_evals=50):
3383
+ self.optimize_model('ft', max_evals)
3384
+
3385
+ # 绘制提纯曲线
3386
+ def plot_lift(self, model_label, pred_nme, n_bins=10):
3387
+ model_map = {
3388
+ 'Xgboost': 'pred_xgb',
3389
+ 'ResNet': 'pred_resn',
3390
+ 'ResNetClassifier': 'pred_resn',
3391
+ 'FTTransformer': 'pred_ft',
3392
+ 'FTTransformerClassifier': 'pred_ft',
3393
+ 'GLM': 'pred_glm'
3394
+ }
3395
+ for k, v in model_map.items():
3396
+ if model_label.startswith(k):
3397
+ pred_nme = v
3398
+ break
3399
+
3400
+ fig = plt.figure(figsize=(11, 5))
3401
+ for pos, (title, data) in zip([121, 122],
3402
+ [('Lift Chart on Train Data', self.train_data),
3403
+ ('Lift Chart on Test Data', self.test_data)]):
3404
+ lift_df = pd.DataFrame({
3405
+ 'pred': data[pred_nme].values,
3406
+ 'w_pred': data[f'w_{pred_nme}'].values,
3407
+ 'act': data['w_act'].values,
3408
+ 'weight': data[self.weight_nme].values
3409
+ })
3410
+ plot_data = PlotUtils.split_data(lift_df, 'pred', 'weight', n_bins)
3411
+ denom = np.maximum(plot_data['weight'], EPS)
3412
+ plot_data['exp_v'] = plot_data['w_pred'] / denom
3413
+ plot_data['act_v'] = plot_data['act'] / denom
3414
+ plot_data = plot_data.reset_index()
3415
+
3416
+ ax = fig.add_subplot(pos)
3417
+ PlotUtils.plot_lift_ax(ax, plot_data, title)
3418
+
3419
+ plt.subplots_adjust(wspace=0.3)
3420
+ save_path = self.output_manager.plot_path(
3421
+ f'01_{self.model_nme}_{model_label}_lift.png')
3422
+ plt.savefig(save_path, dpi=300)
3423
+ plt.show()
3424
+ plt.close(fig)
3425
+
3426
+ # 绘制双提纯曲线
3427
+ def plot_dlift(self, model_comp: List[str] = ['xgb', 'resn'], n_bins: int = 10) -> None:
3428
+ # 绘制双提纯曲线,对比两个模型在不同分箱下的表现。
3429
+ # 参数说明:
3430
+ # model_comp: 需要对比的模型简称(如 ['xgb', 'resn'],支持 'xgb'/'resn'/'ft')。
3431
+ # n_bins: 分箱数量,用于控制 lift 曲线的粒度。
3432
+ if len(model_comp) != 2:
3433
+ raise ValueError("`model_comp` 必须包含两个模型进行对比。")
3434
+
3435
+ model_name_map = {
3436
+ 'xgb': 'Xgboost',
3437
+ 'resn': 'ResNet',
3438
+ 'ft': 'FTTransformer',
3439
+ 'glm': 'GLM'
3440
+ }
3441
+
3442
+ name1, name2 = model_comp
3443
+ if name1 not in model_name_map or name2 not in model_name_map:
3444
+ raise ValueError(f"不支持的模型简称。请从 {list(model_name_map.keys())} 中选择。")
3445
+
3446
+ fig, axes = plt.subplots(1, 2, figsize=(11, 5))
3447
+ datasets = {
3448
+ 'Train Data': self.train_data,
3449
+ 'Test Data': self.test_data
3450
+ }
3451
+
3452
+ for ax, (data_name, data) in zip(axes, datasets.items()):
3453
+ pred1_col = f'w_pred_{name1}'
3454
+ pred2_col = f'w_pred_{name2}'
3455
+
3456
+ if pred1_col not in data.columns or pred2_col not in data.columns:
3457
+ print(
3458
+ f"警告: 在 {data_name} 中找不到预测列 {pred1_col} 或 {pred2_col}。跳过绘图。")
3459
+ continue
3460
+
3461
+ lift_data = pd.DataFrame({
3462
+ 'pred1': data[pred1_col].values,
3463
+ 'pred2': data[pred2_col].values,
3464
+ 'diff_ly': data[pred1_col].values / np.maximum(data[pred2_col].values, EPS),
3465
+ 'act': data['w_act'].values,
3466
+ 'weight': data[self.weight_nme].values
3467
+ })
3468
+ plot_data = PlotUtils.split_data(
3469
+ lift_data, 'diff_ly', 'weight', n_bins)
3470
+ denom = np.maximum(plot_data['act'], EPS)
3471
+ plot_data['exp_v1'] = plot_data['pred1'] / denom
3472
+ plot_data['exp_v2'] = plot_data['pred2'] / denom
3473
+ plot_data['act_v'] = plot_data['act'] / denom
3474
+ plot_data.reset_index(inplace=True)
3475
+
3476
+ label1 = model_name_map[name1]
3477
+ label2 = model_name_map[name2]
3478
+
3479
+ PlotUtils.plot_dlift_ax(
3480
+ ax, plot_data, f'Double Lift Chart on {data_name}', label1, label2)
3481
+
3482
+ plt.subplots_adjust(bottom=0.25, top=0.95, right=0.8, wspace=0.3)
3483
+ save_path = self.output_manager.plot_path(
3484
+ f'02_{self.model_nme}_dlift_{name1}_vs_{name2}.png')
3485
+ plt.savefig(save_path, dpi=300)
3486
+ plt.show()
3487
+ plt.close(fig)
3488
+
3489
+ # 绘制成交率提升曲线
3490
+ def plot_conversion_lift(self, model_pred_col: str, n_bins: int = 20):
3491
+ if not self.binary_resp_nme:
3492
+ print("错误: 未在 BayesOptModel 初始化时提供 `binary_resp_nme`。无法绘制成交率曲线。")
3493
+ return
3494
+
3495
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6), sharey=True)
3496
+ datasets = {
3497
+ 'Train Data': self.train_data,
3498
+ 'Test Data': self.test_data
3499
+ }
3500
+
3501
+ for ax, (data_name, data) in zip(axes, datasets.items()):
3502
+ if model_pred_col not in data.columns:
3503
+ print(f"警告: 在 {data_name} 中找不到预测列 '{model_pred_col}'。跳过绘图。")
3504
+ continue
3505
+
3506
+ # 按模型预测分排序,并计算分箱
3507
+ plot_data = data.sort_values(by=model_pred_col).copy()
3508
+ plot_data['cum_weight'] = plot_data[self.weight_nme].cumsum()
3509
+ total_weight = plot_data[self.weight_nme].sum()
3510
+
3511
+ if total_weight > EPS:
3512
+ plot_data['bin'] = pd.cut(
3513
+ plot_data['cum_weight'],
3514
+ bins=n_bins,
3515
+ labels=False,
3516
+ right=False
3517
+ )
3518
+ else:
3519
+ plot_data['bin'] = 0
3520
+
3521
+ # 按分箱聚合
3522
+ lift_agg = plot_data.groupby('bin').agg(
3523
+ total_weight=(self.weight_nme, 'sum'),
3524
+ actual_conversions=(self.binary_resp_nme, 'sum'),
3525
+ weighted_conversions=('w_binary_act', 'sum'),
3526
+ avg_pred=(model_pred_col, 'mean')
3527
+ ).reset_index()
3528
+
3529
+ # 计算成交率
3530
+ lift_agg['conversion_rate'] = lift_agg['weighted_conversions'] / \
3531
+ lift_agg['total_weight']
3532
+
3533
+ # 计算整体平均成交率
3534
+ overall_conversion_rate = data['w_binary_act'].sum(
3535
+ ) / data[self.weight_nme].sum()
3536
+ ax.axhline(y=overall_conversion_rate, color='gray', linestyle='--',
3537
+ label=f'Overall Avg Rate ({overall_conversion_rate:.2%})')
3538
+
3539
+ ax.plot(lift_agg['bin'], lift_agg['conversion_rate'],
3540
+ marker='o', linestyle='-', label='Actual Conversion Rate')
3541
+ ax.set_title(f'Conversion Rate Lift Chart on {data_name}')
3542
+ ax.set_xlabel(f'Model Score Decile (based on {model_pred_col})')
3543
+ ax.set_ylabel('Conversion Rate')
3544
+ ax.grid(True, linestyle='--', alpha=0.6)
3545
+ ax.legend()
3546
+
3547
+ plt.tight_layout()
3548
+ plt.show()
3549
+
3550
+ # 保存模型
3551
+ def save_model(self, model_name=None):
3552
+ keys = [model_name] if model_name else self.trainers.keys()
3553
+ for key in keys:
3554
+ if key in self.trainers:
3555
+ self.trainers[key].save()
3556
+ else:
3557
+ if model_name: # 仅在用户指定模型名时输出告警
3558
+ print(f"[save_model] Warning: Unknown model key {key}")
3559
+
3560
+ def load_model(self, model_name=None):
3561
+ keys = [model_name] if model_name else self.trainers.keys()
3562
+ for key in keys:
3563
+ if key in self.trainers:
3564
+ self.trainers[key].load()
3565
+ # 同步上下文字段
3566
+ trainer = self.trainers[key]
3567
+ if trainer.model is not None:
3568
+ setattr(self, f"{key}_best", trainer.model)
3569
+ # 如需兼容旧版字段,也同步更新 xxx_load
3570
+ # 旧版只维护 xgb_load/resn_load/ft_load,未包含 glm_load
3571
+ if key in ['xgb', 'resn', 'ft']:
3572
+ setattr(self, f"{key}_load", trainer.model)
3573
+ else:
3574
+ if model_name:
3575
+ print(f"[load_model] Warning: Unknown model key {key}")
3576
+
3577
+ def _sample_rows(self, data: pd.DataFrame, n: int) -> pd.DataFrame:
3578
+ if len(data) == 0:
3579
+ return data
3580
+ return data.sample(min(len(data), n), random_state=self.rand_seed)
3581
+
3582
+ @staticmethod
3583
+ def _shap_nsamples(arr: np.ndarray, max_nsamples: int = 300) -> int:
3584
+ min_needed = arr.shape[1] + 2
3585
+ return max(min_needed, min(max_nsamples, arr.shape[0] * arr.shape[1]))
3586
+
3587
+ def _build_ft_shap_matrix(self, data: pd.DataFrame) -> np.ndarray:
3588
+ matrices = []
3589
+ for col in self.factor_nmes:
3590
+ s = data[col]
3591
+ if col in self.cate_list:
3592
+ cats = pd.Categorical(
3593
+ s,
3594
+ categories=self.cat_categories_for_shap[col]
3595
+ )
3596
+ codes = np.asarray(cats.codes, dtype=np.float64).reshape(-1, 1)
3597
+ matrices.append(codes)
3598
+ else:
3599
+ vals = pd.to_numeric(s, errors="coerce")
3600
+ arr = vals.to_numpy(dtype=np.float64, copy=True).reshape(-1, 1)
3601
+ matrices.append(arr)
3602
+ X_mat = np.concatenate(matrices, axis=1) # 结果形状为 (N, F)
3603
+ return X_mat
3604
+
3605
+ def _decode_ft_shap_matrix_to_df(self, X_mat: np.ndarray) -> pd.DataFrame:
3606
+ data_dict = {}
3607
+ for j, col in enumerate(self.factor_nmes):
3608
+ col_vals = X_mat[:, j]
3609
+ if col in self.cate_list:
3610
+ cats = self.cat_categories_for_shap[col]
3611
+ codes = np.round(col_vals).astype(int)
3612
+ codes = np.clip(codes, -1, len(cats) - 1)
3613
+ cat_series = pd.Categorical.from_codes(
3614
+ codes,
3615
+ categories=cats
3616
+ )
3617
+ data_dict[col] = cat_series
3618
+ else:
3619
+ data_dict[col] = col_vals.astype(float)
3620
+
3621
+ df = pd.DataFrame(data_dict, columns=self.factor_nmes)
3622
+ for col in self.cate_list:
3623
+ if col in df.columns:
3624
+ df[col] = df[col].astype("category")
3625
+ return df
3626
+
3627
+ def _build_glm_design(self, data: pd.DataFrame) -> pd.DataFrame:
3628
+ X = data[self.var_nmes]
3629
+ return sm.add_constant(X, has_constant='add')
3630
+
3631
+ def _compute_shap_core(self,
3632
+ model_key: str,
3633
+ n_background: int,
3634
+ n_samples: int,
3635
+ on_train: bool,
3636
+ X_df: pd.DataFrame,
3637
+ prep_fn,
3638
+ predict_fn,
3639
+ cleanup_fn=None):
3640
+ if model_key not in self.trainers or self.trainers[model_key].model is None:
3641
+ raise RuntimeError(f"Model {model_key} not trained.")
3642
+ if cleanup_fn:
3643
+ cleanup_fn()
3644
+ bg_df = self._sample_rows(X_df, n_background)
3645
+ bg_mat = prep_fn(bg_df)
3646
+ explainer = shap.KernelExplainer(predict_fn, bg_mat)
3647
+ ex_df = self._sample_rows(X_df, n_samples)
3648
+ ex_mat = prep_fn(ex_df)
3649
+ nsample_eff = self._shap_nsamples(ex_mat)
3650
+ shap_values = explainer.shap_values(ex_mat, nsamples=nsample_eff)
3651
+ bg_pred = predict_fn(bg_mat)
3652
+ base_value = float(np.asarray(bg_pred).mean())
3653
+
3654
+ return {
3655
+ "explainer": explainer,
3656
+ "X_explain": ex_df,
3657
+ "shap_values": shap_values,
3658
+ "base_value": base_value
3659
+ }
3660
+
3661
+ # ========= GLM 的 SHAP 解释 =========
3662
+ def compute_shap_glm(self, n_background: int = 500,
3663
+ n_samples: int = 200,
3664
+ on_train: bool = True):
3665
+ data = self.train_oht_scl_data if on_train else self.test_oht_scl_data
3666
+ design_all = self._build_glm_design(data)
3667
+ design_cols = list(design_all.columns)
3668
+
3669
+ def predict_wrapper(x_np):
3670
+ x_df = pd.DataFrame(x_np, columns=design_cols)
3671
+ y_pred = self.glm_best.predict(x_df)
3672
+ return np.asarray(y_pred, dtype=np.float64).reshape(-1)
3673
+
3674
+ self.shap_glm = self._compute_shap_core(
3675
+ 'glm', n_background, n_samples, on_train,
3676
+ X_df=design_all,
3677
+ prep_fn=lambda df: df.to_numpy(dtype=np.float64),
3678
+ predict_fn=predict_wrapper
3679
+ )
3680
+ return self.shap_glm
3681
+
3682
+ # ========= XGBoost 的 SHAP 解释 =========
3683
+ def compute_shap_xgb(self, n_background: int = 500,
3684
+ n_samples: int = 200,
3685
+ on_train: bool = True):
3686
+ data = self.train_data if on_train else self.test_data
3687
+ X_raw = data[self.factor_nmes]
3688
+
3689
+ def predict_wrapper(x_mat):
3690
+ df_input = self._decode_ft_shap_matrix_to_df(x_mat)
3691
+ return self.xgb_best.predict(df_input)
3692
+
3693
+ self.shap_xgb = self._compute_shap_core(
3694
+ 'xgb', n_background, n_samples, on_train,
3695
+ X_df=X_raw,
3696
+ prep_fn=lambda df: self._build_ft_shap_matrix(
3697
+ df).astype(np.float64),
3698
+ predict_fn=predict_wrapper
3699
+ )
3700
+ return self.shap_xgb
3701
+
3702
+ # ========= ResNet 的 SHAP 解释 =========
3703
+ def _resn_predict_wrapper(self, X_np):
3704
+ model = self.resn_best.resnet.to("cpu")
3705
+ with torch.no_grad():
3706
+ X_tensor = torch.tensor(X_np, dtype=torch.float32)
3707
+ y_pred = model(X_tensor).cpu().numpy()
3708
+ y_pred = np.clip(y_pred, 1e-6, None)
3709
+ return y_pred.reshape(-1)
3710
+
3711
+ def compute_shap_resn(self, n_background: int = 500,
3712
+ n_samples: int = 200,
3713
+ on_train: bool = True):
3714
+ data = self.train_oht_scl_data if on_train else self.test_oht_scl_data
3715
+ X = data[self.var_nmes]
3716
+
3717
+ def cleanup():
3718
+ self.resn_best.device = torch.device("cpu")
3719
+ self.resn_best.resnet.to("cpu")
3720
+ if torch.cuda.is_available():
3721
+ torch.cuda.empty_cache()
3722
+
3723
+ self.shap_resn = self._compute_shap_core(
3724
+ 'resn', n_background, n_samples, on_train,
3725
+ X_df=X,
3726
+ prep_fn=lambda df: df.to_numpy(dtype=np.float64),
3727
+ predict_fn=lambda x: self._resn_predict_wrapper(x),
3728
+ cleanup_fn=cleanup
3729
+ )
3730
+ return self.shap_resn
3731
+
3732
+ # ========= FT-Transformer 的 SHAP 解释 =========
3733
+ def _ft_shap_predict_wrapper(self, X_mat: np.ndarray) -> np.ndarray:
3734
+ df_input = self._decode_ft_shap_matrix_to_df(X_mat)
3735
+ y_pred = self.ft_best.predict(df_input)
3736
+ return np.asarray(y_pred, dtype=np.float64).reshape(-1)
3737
+
3738
+ def compute_shap_ft(self, n_background: int = 500,
3739
+ n_samples: int = 200,
3740
+ on_train: bool = True):
3741
+ data = self.train_data if on_train else self.test_data
3742
+ X_raw = data[self.factor_nmes]
3743
+
3744
+ def cleanup():
3745
+ self.ft_best.device = torch.device("cpu")
3746
+ self.ft_best.ft.to("cpu")
3747
+ if torch.cuda.is_available():
3748
+ torch.cuda.empty_cache()
3749
+
3750
+ self.shap_ft = self._compute_shap_core(
3751
+ 'ft', n_background, n_samples, on_train,
3752
+ X_df=X_raw,
3753
+ prep_fn=lambda df: self._build_ft_shap_matrix(
3754
+ df).astype(np.float64),
3755
+ predict_fn=self._ft_shap_predict_wrapper,
3756
+ cleanup_fn=cleanup
3757
+ )
3758
+ return self.shap_ft