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,3719 @@
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,输出形状为 (batch, token_num, d_model)
949
+ # 约定:
950
+ # - X_num:表示数值特征,shape=(batch, num_numeric)
951
+ # - X_cat:表示类别特征,shape=(batch, num_categorical),每列是编码后的整数标签 [0, card-1]
952
+
953
+ def __init__(self, num_numeric: int, cat_cardinalities, d_model: int):
954
+ super().__init__()
955
+
956
+ self.num_numeric = num_numeric
957
+ self.has_numeric = num_numeric > 0
958
+
959
+ if self.has_numeric:
960
+ self.num_linear = nn.Linear(num_numeric, d_model)
961
+
962
+ self.embeddings = nn.ModuleList([
963
+ nn.Embedding(card, d_model) for card in cat_cardinalities
964
+ ])
965
+
966
+ def forward(self, X_num, X_cat):
967
+ tokens = []
968
+
969
+ if self.has_numeric:
970
+ # 数值特征整体映射为一个 token
971
+ # 形状为 (batch, d_model)
972
+ num_token = self.num_linear(X_num)
973
+ tokens.append(num_token)
974
+
975
+ # 每个类别特征各生成一个嵌入 token
976
+ for i, emb in enumerate(self.embeddings):
977
+ # 形状为 (batch, d_model)
978
+ tok = emb(X_cat[:, i])
979
+ tokens.append(tok)
980
+
981
+ # 拼接后得到形状为 (batch, token_num, d_model)
982
+ x = torch.stack(tokens, dim=1)
983
+ return x
984
+
985
+ # 定义具有残差缩放的Encoder层
986
+
987
+
988
+ class ScaledTransformerEncoderLayer(nn.Module):
989
+ def __init__(self, d_model: int, nhead: int, dim_feedforward: int = 2048,
990
+ dropout: float = 0.1, residual_scale_attn: float = 1.0,
991
+ residual_scale_ffn: float = 1.0, norm_first: bool = True,
992
+ ):
993
+ super().__init__()
994
+ self.self_attn = nn.MultiheadAttention(
995
+ embed_dim=d_model,
996
+ num_heads=nhead,
997
+ dropout=dropout,
998
+ batch_first=True
999
+ )
1000
+
1001
+ # 前馈网络部分
1002
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
1003
+ self.dropout = nn.Dropout(dropout)
1004
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
1005
+
1006
+ # 归一化与 Dropout
1007
+ self.norm1 = nn.LayerNorm(d_model)
1008
+ self.norm2 = nn.LayerNorm(d_model)
1009
+ self.dropout1 = nn.Dropout(dropout)
1010
+ self.dropout2 = nn.Dropout(dropout)
1011
+
1012
+ self.activation = nn.GELU()
1013
+ # 如果偏好 ReLU,可将激活函数改为:self.activation = nn.ReLU()
1014
+ self.norm_first = norm_first
1015
+
1016
+ # 残差缩放系数
1017
+ self.res_scale_attn = residual_scale_attn
1018
+ self.res_scale_ffn = residual_scale_ffn
1019
+
1020
+ def forward(self, src, src_mask=None, src_key_padding_mask=None):
1021
+ # 输入张量形状:(batch, 序列长度, d_model)
1022
+ x = src
1023
+
1024
+ if self.norm_first:
1025
+ # 先归一化再做注意力
1026
+ x = x + self._sa_block(self.norm1(x), src_mask,
1027
+ src_key_padding_mask)
1028
+ x = x + self._ff_block(self.norm2(x))
1029
+ else:
1030
+ # 后归一化(一般不启用)
1031
+ x = self.norm1(
1032
+ x + self._sa_block(x, src_mask, src_key_padding_mask))
1033
+ x = self.norm2(x + self._ff_block(x))
1034
+
1035
+ return x
1036
+
1037
+ def _sa_block(self, x, attn_mask, key_padding_mask):
1038
+ # 自注意力并附带残差缩放
1039
+ attn_out, _ = self.self_attn(
1040
+ x, x, x,
1041
+ attn_mask=attn_mask,
1042
+ key_padding_mask=key_padding_mask,
1043
+ need_weights=False
1044
+ )
1045
+ return self.res_scale_attn * self.dropout1(attn_out)
1046
+
1047
+ def _ff_block(self, x):
1048
+ # 前馈网络并附带残差缩放
1049
+ x2 = self.linear2(self.dropout(self.activation(self.linear1(x))))
1050
+ return self.res_scale_ffn * self.dropout2(x2)
1051
+
1052
+ # 定义FT-Transformer核心模型
1053
+
1054
+
1055
+ class FTTransformerCore(nn.Module):
1056
+ # 最小可用版本的 FT-Transformer,由三部分组成:
1057
+ # 1) FeatureTokenizer:将数值/类别特征转换成 token;
1058
+ # 2) TransformerEncoder:建模特征之间的交互;
1059
+ # 3) 池化 + MLP + Softplus:输出正值,方便 Tweedie/Gamma 等任务。
1060
+
1061
+ def __init__(self, num_numeric: int, cat_cardinalities, d_model: int = 64,
1062
+ n_heads: int = 8, n_layers: int = 4, dropout: float = 0.1,
1063
+ task_type: str = 'regression'
1064
+ ):
1065
+ super().__init__()
1066
+
1067
+ self.tokenizer = FeatureTokenizer(
1068
+ num_numeric=num_numeric,
1069
+ cat_cardinalities=cat_cardinalities,
1070
+ d_model=d_model
1071
+ )
1072
+ scale = 1.0 / math.sqrt(n_layers) # 推荐一个默认值
1073
+ encoder_layer = ScaledTransformerEncoderLayer(
1074
+ d_model=d_model,
1075
+ nhead=n_heads,
1076
+ dim_feedforward=d_model * 4,
1077
+ dropout=dropout,
1078
+ residual_scale_attn=scale,
1079
+ residual_scale_ffn=scale,
1080
+ norm_first=True,
1081
+ )
1082
+ self.encoder = nn.TransformerEncoder(
1083
+ encoder_layer,
1084
+ num_layers=n_layers
1085
+ )
1086
+ self.n_layers = n_layers
1087
+
1088
+ layers = [
1089
+ # 如需更深的输出头,可按需启用下方示例层:
1090
+ # nn.LayerNorm(d_model), # 额外的归一化层
1091
+ # nn.Linear(d_model, d_model), # 额外的全连接层
1092
+ # nn.GELU(), # 对应的激活层
1093
+ nn.Linear(d_model, 1),
1094
+ ]
1095
+
1096
+ if task_type == 'classification':
1097
+ # 分类任务输出 logits,与 BCEWithLogitsLoss 更匹配
1098
+ layers.append(nn.Identity())
1099
+ else:
1100
+ # 回归任务需保持正值,适配 Tweedie/Gamma
1101
+ layers.append(nn.Softplus())
1102
+
1103
+ self.head = nn.Sequential(*layers)
1104
+
1105
+ def forward(self, X_num, X_cat):
1106
+
1107
+ # 输入:
1108
+ # X_num -> (batch, 数值特征数) 的 float32 张量
1109
+ # X_cat -> (batch, 类别特征数) 的 long 张量
1110
+
1111
+ if self.training and not hasattr(self, '_printed_device'):
1112
+ print(f">>> FTTransformerCore executing on device: {X_num.device}")
1113
+ self._printed_device = True
1114
+
1115
+ # => 张量形状 (batch, token_num, d_model)
1116
+ tokens = self.tokenizer(X_num, X_cat)
1117
+ # => 张量形状 (batch, token_num, d_model)
1118
+ x = self.encoder(tokens)
1119
+
1120
+ # 对 token 做平均池化,再送入回归头
1121
+ x = x.mean(dim=1) # => 张量形状 (batch, d_model)
1122
+
1123
+ # => 张量形状 (batch, 1),Softplus 约束为正
1124
+ out = self.head(x)
1125
+ return out
1126
+
1127
+ # 定义TabularDataset类
1128
+
1129
+
1130
+ class TabularDataset(Dataset):
1131
+ def __init__(self, X_num, X_cat, y, w):
1132
+
1133
+ # 输入张量说明:
1134
+ # X_num: torch.float32,shape=(N, 数值特征数)
1135
+ # X_cat: torch.long, shape=(N, 类别特征数)
1136
+ # y: torch.float32,shape=(N, 1)
1137
+ # w: torch.float32,shape=(N, 1)
1138
+
1139
+ self.X_num = X_num
1140
+ self.X_cat = X_cat
1141
+ self.y = y
1142
+ self.w = w
1143
+
1144
+ def __len__(self):
1145
+ return self.y.shape[0]
1146
+
1147
+ def __getitem__(self, idx):
1148
+ return (
1149
+ self.X_num[idx],
1150
+ self.X_cat[idx],
1151
+ self.y[idx],
1152
+ self.w[idx],
1153
+ )
1154
+
1155
+ # 定义FTTransformer的Scikit-Learn接口类
1156
+
1157
+
1158
+ class FTTransformerSklearn(TorchTrainerMixin, nn.Module):
1159
+
1160
+ # sklearn 风格包装:
1161
+ # - num_cols:数值特征列名列表
1162
+ # - cat_cols:类别特征列名列表(需事先做标签编码,取值 ∈ [0, n_classes-1])
1163
+
1164
+ def __init__(self, model_nme: str, num_cols, cat_cols, d_model: int = 64, n_heads: int = 8,
1165
+ n_layers: int = 4, dropout: float = 0.1, batch_num: int = 100, epochs: int = 100,
1166
+ task_type: str = 'regression',
1167
+ tweedie_power: float = 1.5, learning_rate: float = 1e-3, patience: int = 10,
1168
+ use_data_parallel: bool = True,
1169
+ use_ddp: bool = False
1170
+ ):
1171
+ super().__init__()
1172
+
1173
+ self.use_ddp = use_ddp
1174
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = (
1175
+ False, 0, 0, 1)
1176
+ if self.use_ddp:
1177
+ self.is_ddp_enabled, self.local_rank, self.rank, self.world_size = DistributedUtils.setup_ddp()
1178
+
1179
+ self.model_nme = model_nme
1180
+ self.num_cols = list(num_cols)
1181
+ self.cat_cols = list(cat_cols)
1182
+ self.d_model = d_model
1183
+ self.n_heads = n_heads
1184
+ self.n_layers = n_layers
1185
+ self.dropout = dropout
1186
+ self.batch_num = batch_num
1187
+ self.epochs = epochs
1188
+ self.learning_rate = learning_rate
1189
+ self.task_type = task_type
1190
+ self.patience = patience
1191
+ if self.task_type == 'classification':
1192
+ self.tw_power = None # 分类时不使用 Tweedie 幂
1193
+ elif 'f' in self.model_nme:
1194
+ self.tw_power = 1.0
1195
+ elif 's' in self.model_nme:
1196
+ self.tw_power = 2.0
1197
+ else:
1198
+ self.tw_power = tweedie_power
1199
+
1200
+ if self.is_ddp_enabled:
1201
+ self.device = torch.device(f"cuda:{self.local_rank}")
1202
+ elif torch.cuda.is_available():
1203
+ self.device = torch.device("cuda")
1204
+ elif torch.backends.mps.is_available():
1205
+ self.device = torch.device("mps")
1206
+ else:
1207
+ self.device = torch.device("cpu")
1208
+ self.cat_cardinalities = None
1209
+ self.cat_categories = {}
1210
+ self.ft = None
1211
+ self.use_data_parallel = torch.cuda.device_count() > 1 and use_data_parallel
1212
+
1213
+ def _build_model(self, X_train):
1214
+ num_numeric = len(self.num_cols)
1215
+ cat_cardinalities = []
1216
+
1217
+ for col in self.cat_cols:
1218
+ cats = X_train[col].astype('category')
1219
+ categories = cats.cat.categories
1220
+ self.cat_categories[col] = categories # 保存训练集类别全集
1221
+
1222
+ card = len(categories) + 1 # 多预留 1 类给“未知/缺失”
1223
+ cat_cardinalities.append(card)
1224
+
1225
+ self.cat_cardinalities = cat_cardinalities
1226
+
1227
+ core = FTTransformerCore(
1228
+ num_numeric=num_numeric,
1229
+ cat_cardinalities=cat_cardinalities,
1230
+ d_model=self.d_model,
1231
+ n_heads=self.n_heads,
1232
+ n_layers=self.n_layers,
1233
+ dropout=self.dropout,
1234
+ task_type=self.task_type
1235
+ )
1236
+ if self.is_ddp_enabled:
1237
+ core = core.to(self.device)
1238
+ core = DDP(core, device_ids=[
1239
+ self.local_rank], output_device=self.local_rank)
1240
+ elif self.use_data_parallel:
1241
+ core = nn.DataParallel(core, device_ids=list(
1242
+ range(torch.cuda.device_count())))
1243
+ self.device = torch.device("cuda")
1244
+ self.ft = core.to(self.device)
1245
+
1246
+ def _encode_cats(self, X):
1247
+ # 输入 DataFrame 至少需要包含所有类别特征列
1248
+ # 返回形状 (N, 类别特征数) 的 int64 数组
1249
+
1250
+ if not self.cat_cols:
1251
+ return np.zeros((len(X), 0), dtype='int64')
1252
+
1253
+ X_cat_list = []
1254
+ for col in self.cat_cols:
1255
+ # 使用训练阶段记录的类别全集
1256
+ categories = self.cat_categories[col]
1257
+ # 按固定类别构造 Categorical
1258
+ cats = pd.Categorical(X[col], categories=categories)
1259
+ codes = cats.codes.astype('int64', copy=True) # -1 表示未知或缺失
1260
+ # 未知或缺失映射到额外的“未知”索引 len(categories)
1261
+ codes[codes < 0] = len(categories)
1262
+ X_cat_list.append(codes)
1263
+
1264
+ X_cat_np = np.stack(X_cat_list, axis=1) # 形状 (N, 类别特征数)
1265
+ return X_cat_np
1266
+
1267
+ def _build_train_tensors(self, X_train, y_train, w_train):
1268
+ return self._tensorize_split(X_train, y_train, w_train)
1269
+
1270
+ def _build_val_tensors(self, X_val, y_val, w_val):
1271
+ return self._tensorize_split(X_val, y_val, w_val, allow_none=True)
1272
+
1273
+ def _tensorize_split(self, X, y, w, allow_none: bool = False):
1274
+ if X is None:
1275
+ if allow_none:
1276
+ return None, None, None, None, False
1277
+ raise ValueError("输入特征 X 不能为空。")
1278
+
1279
+ X_num = torch.tensor(
1280
+ X[self.num_cols].to_numpy(dtype=np.float32, copy=True),
1281
+ dtype=torch.float32
1282
+ )
1283
+ if self.cat_cols:
1284
+ X_cat = torch.tensor(self._encode_cats(X), dtype=torch.long)
1285
+ else:
1286
+ X_cat = torch.zeros((X_num.shape[0], 0), dtype=torch.long)
1287
+
1288
+ y_tensor = torch.tensor(
1289
+ y.values, dtype=torch.float32).view(-1, 1) if y is not None else None
1290
+ if y_tensor is None:
1291
+ w_tensor = None
1292
+ elif w is not None:
1293
+ w_tensor = torch.tensor(
1294
+ w.values, dtype=torch.float32).view(-1, 1)
1295
+ else:
1296
+ w_tensor = torch.ones_like(y_tensor)
1297
+ return X_num, X_cat, y_tensor, w_tensor, y is not None
1298
+
1299
+ def fit(self, X_train, y_train, w_train=None,
1300
+ X_val=None, y_val=None, w_val=None, trial=None):
1301
+
1302
+ # 首次拟合时需要构建底层模型结构
1303
+ if self.ft is None:
1304
+ self._build_model(X_train)
1305
+
1306
+ X_num_train, X_cat_train, y_tensor, w_tensor, _ = self._build_train_tensors(
1307
+ X_train, y_train, w_train)
1308
+ X_num_val, X_cat_val, y_val_tensor, w_val_tensor, has_val = self._build_val_tensors(
1309
+ X_val, y_val, w_val)
1310
+
1311
+ # --- 构建 DataLoader ---
1312
+ dataset = TabularDataset(
1313
+ X_num_train, X_cat_train, y_tensor, w_tensor
1314
+ )
1315
+
1316
+ dataloader, accum_steps = self._build_dataloader(
1317
+ dataset,
1318
+ N=X_num_train.shape[0],
1319
+ base_bs_gpu=(2048, 1024, 512),
1320
+ base_bs_cpu=(256, 128),
1321
+ min_bs=64,
1322
+ target_effective_cuda=2048,
1323
+ target_effective_cpu=1024
1324
+ )
1325
+
1326
+ if self.is_ddp_enabled and hasattr(dataloader.sampler, 'set_epoch'):
1327
+ self.dataloader_sampler = dataloader.sampler
1328
+ else:
1329
+ self.dataloader_sampler = None
1330
+
1331
+ optimizer = torch.optim.Adam(
1332
+ self.ft.parameters(), lr=self.learning_rate)
1333
+ scaler = GradScaler(enabled=(self.device.type == 'cuda'))
1334
+
1335
+ X_num_val_dev = X_cat_val_dev = y_val_dev = w_val_dev = None
1336
+ val_dataloader = None
1337
+ if has_val:
1338
+ val_dataset = TabularDataset(
1339
+ X_num_val, X_cat_val, y_val_tensor, w_val_tensor
1340
+ )
1341
+ val_bs = accum_steps * dataloader.batch_size
1342
+
1343
+ if os.name == 'nt':
1344
+ val_workers = 0
1345
+ else:
1346
+ val_workers = min(4, os.cpu_count() or 1)
1347
+ if getattr(self, "is_ddp_enabled", False):
1348
+ val_workers = 0 # DDP 下禁用多 worker,防止子进程冲突
1349
+
1350
+ val_dataloader = DataLoader(
1351
+ val_dataset,
1352
+ batch_size=val_bs,
1353
+ shuffle=False,
1354
+ num_workers=val_workers,
1355
+ pin_memory=(self.device.type == 'cuda'),
1356
+ persistent_workers=val_workers > 0,
1357
+ )
1358
+
1359
+ is_data_parallel = isinstance(self.ft, nn.DataParallel)
1360
+
1361
+ def forward_fn(batch):
1362
+ X_num_b, X_cat_b, y_b, w_b = batch
1363
+
1364
+ if not is_data_parallel:
1365
+ X_num_b = X_num_b.to(self.device, non_blocking=True)
1366
+ X_cat_b = X_cat_b.to(self.device, non_blocking=True)
1367
+ y_b = y_b.to(self.device, non_blocking=True)
1368
+ w_b = w_b.to(self.device, non_blocking=True)
1369
+
1370
+ y_pred = self.ft(X_num_b, X_cat_b)
1371
+ return y_pred, y_b, w_b
1372
+
1373
+ def val_forward_fn():
1374
+ total_loss = 0.0
1375
+ total_weight = 0.0
1376
+ for batch in val_dataloader:
1377
+ X_num_b, X_cat_b, y_b, w_b = batch
1378
+ if not is_data_parallel:
1379
+ X_num_b = X_num_b.to(self.device, non_blocking=True)
1380
+ X_cat_b = X_cat_b.to(self.device, non_blocking=True)
1381
+ y_b = y_b.to(self.device, non_blocking=True)
1382
+ w_b = w_b.to(self.device, non_blocking=True)
1383
+
1384
+ y_pred = self.ft(X_num_b, X_cat_b)
1385
+
1386
+ # 手动计算验证损失
1387
+ task = getattr(self, "task_type", "regression")
1388
+ if task == 'classification':
1389
+ loss_fn = nn.BCEWithLogitsLoss(reduction='none')
1390
+ losses = loss_fn(y_pred, y_b).view(-1)
1391
+ else:
1392
+ # 模型输出已通过 Softplus,无需再次应用
1393
+ y_pred_clamped = torch.clamp(y_pred, min=1e-6)
1394
+ power = getattr(self, "tw_power", 1.5)
1395
+ losses = tweedie_loss(
1396
+ y_pred_clamped, y_b, p=power).view(-1)
1397
+
1398
+ batch_weight_sum = torch.clamp(w_b.sum(), min=EPS)
1399
+ batch_weighted_loss_sum = (losses * w_b.view(-1)).sum()
1400
+
1401
+ total_loss += batch_weighted_loss_sum.item()
1402
+ total_weight += batch_weight_sum.item()
1403
+
1404
+ return total_loss / max(total_weight, EPS)
1405
+
1406
+ clip_fn = None
1407
+ if self.device.type == 'cuda':
1408
+ def clip_fn(): return (scaler.unscale_(optimizer),
1409
+ clip_grad_norm_(self.ft.parameters(), max_norm=1.0))
1410
+
1411
+ best_state = self._train_model(
1412
+ self.ft,
1413
+ dataloader,
1414
+ accum_steps,
1415
+ optimizer,
1416
+ scaler,
1417
+ forward_fn,
1418
+ val_forward_fn if has_val else None,
1419
+ apply_softplus=False,
1420
+ clip_fn=clip_fn,
1421
+ trial=trial
1422
+ )
1423
+
1424
+ if has_val and best_state is not None:
1425
+ self.ft.load_state_dict(best_state)
1426
+
1427
+ def predict(self, X_test):
1428
+ # X_test 需要包含所有数值列与类别列
1429
+
1430
+ self.ft.eval()
1431
+ X_num, X_cat, _, _, _ = self._tensorize_split(
1432
+ X_test, None, None, allow_none=True)
1433
+
1434
+ with torch.no_grad():
1435
+ X_num = X_num.to(self.device, non_blocking=True)
1436
+ X_cat = X_cat.to(self.device, non_blocking=True)
1437
+ y_pred = self.ft(X_num, X_cat).cpu().numpy()
1438
+
1439
+ if self.task_type == 'classification':
1440
+ # 从 logits 转换为概率
1441
+ y_pred = 1 / (1 + np.exp(-y_pred))
1442
+ else:
1443
+ # 模型已含 softplus,若需要可按需做 log-exp 平滑:y_pred = log(1 + exp(y_pred))
1444
+ y_pred = np.clip(y_pred, 1e-6, None)
1445
+ return y_pred.ravel()
1446
+
1447
+ def set_params(self, params: dict):
1448
+
1449
+ # 和 sklearn 风格保持一致。
1450
+ # 注意:对结构性参数(如 d_model/n_heads)修改后,需要重新 fit 才会生效。
1451
+
1452
+ for key, value in params.items():
1453
+ if hasattr(self, key):
1454
+ setattr(self, key, value)
1455
+ else:
1456
+ raise ValueError(f"Parameter {key} not found in model.")
1457
+ return self
1458
+
1459
+
1460
+ # =============================================================================
1461
+ # 图神经网络 (GNN) 简化实现
1462
+ # =============================================================================
1463
+
1464
+
1465
+ class SimpleGraphLayer(nn.Module):
1466
+ def __init__(self, in_dim: int, out_dim: int, dropout: float = 0.1):
1467
+ super().__init__()
1468
+ self.linear = nn.Linear(in_dim, out_dim)
1469
+ self.activation = nn.ReLU(inplace=True)
1470
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
1471
+
1472
+ def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
1473
+ # 基于归一化稀疏邻接矩阵的消息传递:A_hat * X * W
1474
+ h = torch.sparse.mm(adj, x)
1475
+ h = self.linear(h)
1476
+ h = self.activation(h)
1477
+ return self.dropout(h)
1478
+
1479
+
1480
+ class SimpleGNN(nn.Module):
1481
+ def __init__(self, input_dim: int, hidden_dim: int = 64, num_layers: int = 2,
1482
+ dropout: float = 0.1, task_type: str = 'regression'):
1483
+ super().__init__()
1484
+ layers = []
1485
+ dim_in = input_dim
1486
+ for _ in range(max(1, num_layers)):
1487
+ layers.append(SimpleGraphLayer(
1488
+ dim_in, hidden_dim, dropout=dropout))
1489
+ dim_in = hidden_dim
1490
+ self.layers = nn.ModuleList(layers)
1491
+ self.output = nn.Linear(hidden_dim, 1)
1492
+ if task_type == 'classification':
1493
+ self.output_act = nn.Identity()
1494
+ else:
1495
+ self.output_act = nn.Softplus()
1496
+ self.task_type = task_type
1497
+ # 用 buffer 保持邻接矩阵,便于 DataParallel 复制
1498
+ self.register_buffer("adj_buffer", torch.empty(0))
1499
+
1500
+ def forward(self, x: torch.Tensor, adj: Optional[torch.Tensor] = None) -> torch.Tensor:
1501
+ adj_used = adj if adj is not None else getattr(
1502
+ self, "adj_buffer", None)
1503
+ if adj_used is None or adj_used.numel() == 0:
1504
+ raise RuntimeError("Adjacency is not set for GNN forward.")
1505
+ h = x
1506
+ for layer in self.layers:
1507
+ h = layer(h, adj_used)
1508
+ h = torch.sparse.mm(adj_used, h)
1509
+ out = self.output(h)
1510
+ return self.output_act(out)
1511
+
1512
+
1513
+ class GraphNeuralNetSklearn(TorchTrainerMixin, nn.Module):
1514
+ def __init__(self, model_nme: str, input_dim: int, hidden_dim: int = 64,
1515
+ num_layers: int = 2, k_neighbors: int = 10, dropout: float = 0.1,
1516
+ learning_rate: float = 1e-3, epochs: int = 100, patience: int = 10,
1517
+ task_type: str = 'regression', tweedie_power: float = 1.5,
1518
+ use_data_parallel: bool = False, use_ddp: bool = False,
1519
+ use_approx_knn: bool = True, approx_knn_threshold: int = 50000,
1520
+ graph_cache_path: Optional[str] = None,
1521
+ max_gpu_knn_nodes: Optional[int] = None,
1522
+ knn_gpu_mem_ratio: float = 0.9,
1523
+ knn_gpu_mem_overhead: float = 2.0) -> None:
1524
+ super().__init__()
1525
+ self.model_nme = model_nme
1526
+ self.input_dim = input_dim
1527
+ self.hidden_dim = hidden_dim
1528
+ self.num_layers = num_layers
1529
+ self.k_neighbors = max(1, k_neighbors)
1530
+ self.dropout = dropout
1531
+ self.learning_rate = learning_rate
1532
+ self.epochs = epochs
1533
+ self.patience = patience
1534
+ self.task_type = task_type
1535
+ self.use_approx_knn = use_approx_knn
1536
+ self.approx_knn_threshold = approx_knn_threshold
1537
+ self.graph_cache_path = Path(
1538
+ graph_cache_path) if graph_cache_path else None
1539
+ self.max_gpu_knn_nodes = max_gpu_knn_nodes
1540
+ self.knn_gpu_mem_ratio = max(0.0, min(1.0, knn_gpu_mem_ratio))
1541
+ self.knn_gpu_mem_overhead = max(1.0, knn_gpu_mem_overhead)
1542
+ self._knn_warning_emitted = False
1543
+
1544
+ if self.task_type == 'classification':
1545
+ self.tw_power = None
1546
+ elif 'f' in self.model_nme:
1547
+ self.tw_power = 1.0
1548
+ elif 's' in self.model_nme:
1549
+ self.tw_power = 2.0
1550
+ else:
1551
+ self.tw_power = tweedie_power
1552
+
1553
+ self.ddp_enabled = False
1554
+ self.local_rank = 0
1555
+ self.data_parallel_enabled = False
1556
+
1557
+ # DDP 仅在 CUDA 下有效;若未初始化成功则自动回退单卡
1558
+ if use_ddp and torch.cuda.is_available():
1559
+ ddp_ok, local_rank, _, _ = DistributedUtils.setup_ddp()
1560
+ if ddp_ok:
1561
+ self.ddp_enabled = True
1562
+ self.local_rank = local_rank
1563
+ self.device = torch.device(f'cuda:{local_rank}')
1564
+ else:
1565
+ self.device = torch.device('cuda')
1566
+ elif torch.cuda.is_available():
1567
+ self.device = torch.device('cuda')
1568
+ elif torch.backends.mps.is_available():
1569
+ self.device = torch.device('mps')
1570
+ else:
1571
+ self.device = torch.device('cpu')
1572
+ self.use_pyg_knn = self.device.type == 'cuda' and _PYG_AVAILABLE
1573
+
1574
+ self.gnn = SimpleGNN(
1575
+ input_dim=self.input_dim,
1576
+ hidden_dim=self.hidden_dim,
1577
+ num_layers=self.num_layers,
1578
+ dropout=self.dropout,
1579
+ task_type=self.task_type
1580
+ ).to(self.device)
1581
+
1582
+ # DataParallel 会将完整图复制到每张卡并按特征拆分,适合中等规模图
1583
+ if (not self.ddp_enabled) and use_data_parallel and (self.device.type == 'cuda') and (torch.cuda.device_count() > 1):
1584
+ self.data_parallel_enabled = True
1585
+ self.gnn = nn.DataParallel(
1586
+ self.gnn, device_ids=list(range(torch.cuda.device_count())))
1587
+ self.device = torch.device('cuda')
1588
+
1589
+ if self.ddp_enabled:
1590
+ self.gnn = DDP(
1591
+ self.gnn,
1592
+ device_ids=[self.local_rank],
1593
+ output_device=self.local_rank,
1594
+ find_unused_parameters=False
1595
+ )
1596
+
1597
+ def _unwrap_gnn(self) -> nn.Module:
1598
+ return self.gnn.module if isinstance(self.gnn, DDP) else self.gnn
1599
+
1600
+ def _set_adj_buffer(self, adj: torch.Tensor) -> None:
1601
+ base = self._unwrap_gnn()
1602
+ if hasattr(base, "adj_buffer"):
1603
+ base.adj_buffer = adj
1604
+ else:
1605
+ base.register_buffer("adj_buffer", adj)
1606
+
1607
+ def _load_cached_adj(self) -> Optional[torch.Tensor]:
1608
+ if self.graph_cache_path and self.graph_cache_path.exists():
1609
+ try:
1610
+ adj = torch.load(self.graph_cache_path,
1611
+ map_location=self.device)
1612
+ return adj.to(self.device)
1613
+ except Exception as exc:
1614
+ print(
1615
+ f"[GNN] Failed to load cached graph from {self.graph_cache_path}: {exc}")
1616
+ return None
1617
+
1618
+ def _build_edge_index_cpu(self, X_np: np.ndarray) -> torch.Tensor:
1619
+ n_samples = X_np.shape[0]
1620
+ k = min(self.k_neighbors, max(1, n_samples - 1))
1621
+ n_neighbors = min(k + 1, n_samples)
1622
+ use_approx = (self.use_approx_knn or n_samples >=
1623
+ self.approx_knn_threshold) and _PYNN_AVAILABLE
1624
+ indices = None
1625
+ if use_approx:
1626
+ try:
1627
+ nn_index = pynndescent.NNDescent(
1628
+ X_np,
1629
+ n_neighbors=n_neighbors,
1630
+ random_state=0
1631
+ )
1632
+ indices, _ = nn_index.neighbor_graph
1633
+ except Exception as exc:
1634
+ print(
1635
+ f"[GNN] Approximate kNN failed ({exc}); falling back to exact search.")
1636
+ use_approx = False
1637
+
1638
+ if indices is None:
1639
+ nbrs = NearestNeighbors(n_neighbors=n_neighbors, algorithm="auto")
1640
+ nbrs.fit(X_np)
1641
+ _, indices = nbrs.kneighbors(X_np)
1642
+
1643
+ indices = np.asarray(indices)
1644
+
1645
+ rows = []
1646
+ cols = []
1647
+ for i in range(n_samples):
1648
+ for j in indices[i]:
1649
+ if i == j:
1650
+ continue
1651
+ rows.append(i)
1652
+ cols.append(j)
1653
+ rows.append(j)
1654
+ cols.append(i)
1655
+
1656
+ # 添加自环,避免度为 0 的节点
1657
+ rows.extend(range(n_samples))
1658
+ cols.extend(range(n_samples))
1659
+
1660
+ edge_index = torch.tensor(
1661
+ [rows, cols], dtype=torch.long, device=self.device)
1662
+ return edge_index
1663
+
1664
+ def _build_edge_index_gpu(self, X_tensor: torch.Tensor) -> torch.Tensor:
1665
+ if not self.use_pyg_knn or knn_graph is None or add_self_loops is None or to_undirected is None:
1666
+ # 防御式编程:调用前应检查 use_pyg_knn
1667
+ raise RuntimeError(
1668
+ "GPU graph builder requested but PyG is unavailable.")
1669
+
1670
+ n_samples = X_tensor.size(0)
1671
+ k = min(self.k_neighbors, max(1, n_samples - 1))
1672
+
1673
+ # knn_graph 运行在 GPU 上,避免 CPU 构图成为瓶颈
1674
+ edge_index = knn_graph(
1675
+ X_tensor,
1676
+ k=k,
1677
+ loop=False
1678
+ )
1679
+ edge_index = to_undirected(edge_index, num_nodes=n_samples)
1680
+ edge_index, _ = add_self_loops(edge_index, num_nodes=n_samples)
1681
+ return edge_index
1682
+
1683
+ def _log_knn_fallback(self, reason: str) -> None:
1684
+ if self._knn_warning_emitted:
1685
+ return
1686
+ if (not self.ddp_enabled) or self.local_rank == 0:
1687
+ print(f"[GNN] Falling back to CPU kNN builder: {reason}")
1688
+ self._knn_warning_emitted = True
1689
+
1690
+ def _should_use_gpu_knn(self, n_samples: int, X_tensor: torch.Tensor) -> bool:
1691
+ if not self.use_pyg_knn:
1692
+ return False
1693
+
1694
+ reason = None
1695
+ if self.max_gpu_knn_nodes is not None and n_samples > self.max_gpu_knn_nodes:
1696
+ reason = f"node count {n_samples} exceeds max_gpu_knn_nodes={self.max_gpu_knn_nodes}"
1697
+ elif self.device.type == 'cuda' and torch.cuda.is_available():
1698
+ try:
1699
+ device_index = self.device.index
1700
+ if device_index is None:
1701
+ device_index = torch.cuda.current_device()
1702
+ free_mem, total_mem = torch.cuda.mem_get_info(device_index)
1703
+ feature_bytes = X_tensor.element_size() * X_tensor.nelement()
1704
+ required = int(feature_bytes * self.knn_gpu_mem_overhead)
1705
+ budget = int(free_mem * self.knn_gpu_mem_ratio)
1706
+ if required > budget:
1707
+ required_gb = required / (1024 ** 3)
1708
+ budget_gb = budget / (1024 ** 3)
1709
+ reason = (f"requires ~{required_gb:.2f} GiB temporary GPU memory "
1710
+ f"but only {budget_gb:.2f} GiB free on cuda:{device_index}")
1711
+ except Exception:
1712
+ # 在较老版本或某些环境下 mem_get_info 可能不可用,默认继续尝试 GPU
1713
+ reason = None
1714
+
1715
+ if reason:
1716
+ self._log_knn_fallback(reason)
1717
+ return False
1718
+ return True
1719
+
1720
+ def _normalized_adj(self, edge_index: torch.Tensor, num_nodes: int) -> torch.Tensor:
1721
+ values = torch.ones(edge_index.shape[1], device=self.device)
1722
+ adj = torch.sparse_coo_tensor(
1723
+ edge_index.to(self.device), values, (num_nodes, num_nodes))
1724
+ adj = adj.coalesce()
1725
+
1726
+ deg = torch.sparse.sum(adj, dim=1).to_dense()
1727
+ deg_inv_sqrt = torch.pow(deg + 1e-8, -0.5)
1728
+ row, col = adj.indices()
1729
+ norm_values = deg_inv_sqrt[row] * adj.values() * deg_inv_sqrt[col]
1730
+ adj_norm = torch.sparse_coo_tensor(
1731
+ adj.indices(), norm_values, size=adj.shape)
1732
+ return adj_norm
1733
+
1734
+ def _tensorize_split(self, X, y, w, allow_none: bool = False):
1735
+ if X is None and allow_none:
1736
+ return None, None, None
1737
+ X_np = X.values.astype(np.float32)
1738
+ X_tensor = torch.tensor(X_np, dtype=torch.float32, device=self.device)
1739
+ if y is None:
1740
+ y_tensor = None
1741
+ else:
1742
+ y_tensor = torch.tensor(
1743
+ y.values, dtype=torch.float32, device=self.device).view(-1, 1)
1744
+ if w is None:
1745
+ w_tensor = torch.ones(
1746
+ (len(X), 1), dtype=torch.float32, device=self.device)
1747
+ else:
1748
+ w_tensor = torch.tensor(
1749
+ w.values, dtype=torch.float32, device=self.device).view(-1, 1)
1750
+ return X_tensor, y_tensor, w_tensor
1751
+
1752
+ def _build_graph_from_df(self, X_df: pd.DataFrame, X_tensor: Optional[torch.Tensor] = None) -> torch.Tensor:
1753
+ if X_tensor is None:
1754
+ X_tensor = torch.tensor(
1755
+ X_df.values.astype(np.float32),
1756
+ dtype=torch.float32,
1757
+ device=self.device
1758
+ )
1759
+ if self.graph_cache_path:
1760
+ cached = self._load_cached_adj()
1761
+ if cached is not None:
1762
+ return cached
1763
+ use_gpu_knn = self._should_use_gpu_knn(X_df.shape[0], X_tensor)
1764
+ if use_gpu_knn:
1765
+ edge_index = self._build_edge_index_gpu(X_tensor)
1766
+ else:
1767
+ edge_index = self._build_edge_index_cpu(
1768
+ X_df.values.astype(np.float32))
1769
+ adj_norm = self._normalized_adj(edge_index, X_df.shape[0])
1770
+ if self.graph_cache_path:
1771
+ try:
1772
+ IOUtils.ensure_parent_dir(str(self.graph_cache_path))
1773
+ torch.save(adj_norm.cpu(), self.graph_cache_path)
1774
+ except Exception as exc:
1775
+ print(
1776
+ f"[GNN] Failed to cache graph to {self.graph_cache_path}: {exc}")
1777
+ return adj_norm
1778
+
1779
+ def fit(self, X_train, y_train, w_train=None,
1780
+ X_val=None, y_val=None, w_val=None,
1781
+ trial: Optional[optuna.trial.Trial] = None):
1782
+
1783
+ X_train_tensor, y_train_tensor, w_train_tensor = self._tensorize_split(
1784
+ X_train, y_train, w_train, allow_none=False)
1785
+ has_val = X_val is not None and y_val is not None
1786
+ if has_val:
1787
+ X_val_tensor, y_val_tensor, w_val_tensor = self._tensorize_split(
1788
+ X_val, y_val, w_val, allow_none=False)
1789
+ else:
1790
+ X_val_tensor = y_val_tensor = w_val_tensor = None
1791
+
1792
+ adj_train = self._build_graph_from_df(X_train, X_train_tensor)
1793
+ adj_val = self._build_graph_from_df(
1794
+ X_val, X_val_tensor) if has_val else None
1795
+ # DataParallel 需要将邻接矩阵缓存在模型上,避免被 scatter
1796
+ self._set_adj_buffer(adj_train)
1797
+
1798
+ base_gnn = self._unwrap_gnn()
1799
+ optimizer = torch.optim.Adam(
1800
+ base_gnn.parameters(), lr=self.learning_rate)
1801
+ scaler = GradScaler(enabled=(self.device.type == 'cuda'))
1802
+
1803
+ best_loss = float('inf')
1804
+ best_state = None
1805
+ patience_counter = 0
1806
+
1807
+ for epoch in range(1, self.epochs + 1):
1808
+ self.gnn.train()
1809
+ optimizer.zero_grad()
1810
+ with autocast(enabled=(self.device.type == 'cuda')):
1811
+ if self.data_parallel_enabled:
1812
+ y_pred = self.gnn(X_train_tensor)
1813
+ else:
1814
+ y_pred = self.gnn(X_train_tensor, adj_train)
1815
+ loss = self._compute_weighted_loss(
1816
+ y_pred, y_train_tensor, w_train_tensor, apply_softplus=False)
1817
+ scaler.scale(loss).backward()
1818
+ scaler.unscale_(optimizer)
1819
+ clip_grad_norm_(self.gnn.parameters(), max_norm=1.0)
1820
+ scaler.step(optimizer)
1821
+ scaler.update()
1822
+
1823
+ if has_val:
1824
+ self.gnn.eval()
1825
+ if self.data_parallel_enabled and adj_val is not None:
1826
+ self._set_adj_buffer(adj_val)
1827
+ with torch.no_grad(), autocast(enabled=(self.device.type == 'cuda')):
1828
+ if self.data_parallel_enabled:
1829
+ y_val_pred = self.gnn(X_val_tensor)
1830
+ else:
1831
+ y_val_pred = self.gnn(X_val_tensor, adj_val)
1832
+ val_loss = self._compute_weighted_loss(
1833
+ y_val_pred, y_val_tensor, w_val_tensor, apply_softplus=False)
1834
+ if self.data_parallel_enabled:
1835
+ # 恢复训练邻接矩阵
1836
+ self._set_adj_buffer(adj_train)
1837
+
1838
+ best_loss, best_state, patience_counter, stop_training = self._early_stop_update(
1839
+ val_loss, best_loss, best_state, patience_counter, base_gnn,
1840
+ ignore_keys=["adj_buffer"])
1841
+
1842
+ if trial is not None:
1843
+ trial.report(val_loss, epoch)
1844
+ if trial.should_prune():
1845
+ raise optuna.TrialPruned()
1846
+ if stop_training:
1847
+ break
1848
+
1849
+ if best_state is not None:
1850
+ base_gnn.load_state_dict(best_state, strict=False)
1851
+
1852
+ def predict(self, X: pd.DataFrame) -> np.ndarray:
1853
+ self.gnn.eval()
1854
+ X_tensor, _, _ = self._tensorize_split(
1855
+ X, None, None, allow_none=False)
1856
+ adj = self._build_graph_from_df(X, X_tensor)
1857
+ if self.data_parallel_enabled:
1858
+ self._set_adj_buffer(adj)
1859
+ with torch.no_grad():
1860
+ if self.data_parallel_enabled:
1861
+ y_pred = self.gnn(X_tensor).cpu().numpy()
1862
+ else:
1863
+ y_pred = self.gnn(X_tensor, adj).cpu().numpy()
1864
+ if self.task_type == 'classification':
1865
+ y_pred = 1 / (1 + np.exp(-y_pred))
1866
+ else:
1867
+ y_pred = np.clip(y_pred, 1e-6, None)
1868
+ return y_pred.ravel()
1869
+
1870
+ def set_params(self, params: Dict[str, Any]):
1871
+ for key, value in params.items():
1872
+ if hasattr(self, key):
1873
+ setattr(self, key, value)
1874
+ else:
1875
+ raise ValueError(f"Parameter {key} not found in GNN model.")
1876
+ # 结构参数变化后需要重建骨架
1877
+ self.gnn = SimpleGNN(
1878
+ input_dim=self.input_dim,
1879
+ hidden_dim=self.hidden_dim,
1880
+ num_layers=self.num_layers,
1881
+ dropout=self.dropout,
1882
+ task_type=self.task_type
1883
+ ).to(self.device)
1884
+ return self
1885
+
1886
+
1887
+ # ===== 基础组件与训练封装 =====================================================
1888
+
1889
+ # =============================================================================
1890
+ # 配置、预处理与训练器基类
1891
+ # =============================================================================
1892
+ @dataclass
1893
+ class BayesOptConfig:
1894
+ model_nme: str
1895
+ resp_nme: str
1896
+ weight_nme: str
1897
+ factor_nmes: List[str]
1898
+ task_type: str = 'regression'
1899
+ binary_resp_nme: Optional[str] = None
1900
+ cate_list: Optional[List[str]] = None
1901
+ prop_test: float = 0.25
1902
+ rand_seed: Optional[int] = None
1903
+ epochs: int = 100
1904
+ use_gpu: bool = True
1905
+ use_resn_data_parallel: bool = False
1906
+ use_ft_data_parallel: bool = False
1907
+ use_resn_ddp: bool = False
1908
+ use_ft_ddp: bool = False
1909
+ use_gnn_data_parallel: bool = False
1910
+ use_gnn_ddp: bool = False
1911
+ gnn_use_approx_knn: bool = True
1912
+ gnn_approx_knn_threshold: int = 50000
1913
+ gnn_graph_cache: Optional[str] = None
1914
+ gnn_max_gpu_knn_nodes: Optional[int] = 200000
1915
+ gnn_knn_gpu_mem_ratio: float = 0.9
1916
+ gnn_knn_gpu_mem_overhead: float = 2.0
1917
+ output_dir: Optional[str] = None
1918
+ optuna_storage: Optional[str] = None
1919
+ optuna_study_prefix: Optional[str] = None
1920
+
1921
+
1922
+ class OutputManager:
1923
+ # 统一管理结果、图表与模型的输出路径
1924
+
1925
+ def __init__(self, root: Optional[str] = None, model_name: str = "model") -> None:
1926
+ self.root = Path(root or os.getcwd())
1927
+ self.model_name = model_name
1928
+ self.plot_dir = self.root / 'plot'
1929
+ self.result_dir = self.root / 'Results'
1930
+ self.model_dir = self.root / 'model'
1931
+
1932
+ def _prepare(self, path: Path) -> str:
1933
+ ensure_parent_dir(str(path))
1934
+ return str(path)
1935
+
1936
+ def plot_path(self, filename: str) -> str:
1937
+ return self._prepare(self.plot_dir / filename)
1938
+
1939
+ def result_path(self, filename: str) -> str:
1940
+ return self._prepare(self.result_dir / filename)
1941
+
1942
+ def model_path(self, filename: str) -> str:
1943
+ return self._prepare(self.model_dir / filename)
1944
+
1945
+
1946
+ class DatasetPreprocessor:
1947
+ # 为各训练器准备通用的训练/测试数据视图
1948
+
1949
+ def __init__(self, train_df: pd.DataFrame, test_df: pd.DataFrame,
1950
+ config: BayesOptConfig) -> None:
1951
+ self.config = config
1952
+ self.train_data = train_df.copy(deep=True)
1953
+ self.test_data = test_df.copy(deep=True)
1954
+ self.num_features: List[str] = []
1955
+ self.train_oht_data: Optional[pd.DataFrame] = None
1956
+ self.test_oht_data: Optional[pd.DataFrame] = None
1957
+ self.train_oht_scl_data: Optional[pd.DataFrame] = None
1958
+ self.test_oht_scl_data: Optional[pd.DataFrame] = None
1959
+ self.var_nmes: List[str] = []
1960
+ self.cat_categories_for_shap: Dict[str, List[Any]] = {}
1961
+
1962
+ def run(self) -> "DatasetPreprocessor":
1963
+ """执行预处理:类别编码、目标值裁剪以及数值特征标准化。"""
1964
+ cfg = self.config
1965
+ # 预先计算加权实际值,后续画图、校验都依赖该字段
1966
+ self.train_data.loc[:, 'w_act'] = self.train_data[cfg.resp_nme] * \
1967
+ self.train_data[cfg.weight_nme]
1968
+ self.test_data.loc[:, 'w_act'] = self.test_data[cfg.resp_nme] * \
1969
+ self.test_data[cfg.weight_nme]
1970
+ if cfg.binary_resp_nme:
1971
+ self.train_data.loc[:, 'w_binary_act'] = self.train_data[cfg.binary_resp_nme] * \
1972
+ self.train_data[cfg.weight_nme]
1973
+ self.test_data.loc[:, 'w_binary_act'] = self.test_data[cfg.binary_resp_nme] * \
1974
+ self.test_data[cfg.weight_nme]
1975
+ # 高分位裁剪用来吸收离群值;若删除会导致极端点主导损失
1976
+ q99 = self.train_data[cfg.resp_nme].quantile(0.999)
1977
+ self.train_data[cfg.resp_nme] = self.train_data[cfg.resp_nme].clip(
1978
+ upper=q99)
1979
+ cate_list = list(cfg.cate_list or [])
1980
+ if cate_list:
1981
+ for cate in cate_list:
1982
+ self.train_data[cate] = self.train_data[cate].astype(
1983
+ 'category')
1984
+ self.test_data[cate] = self.test_data[cate].astype('category')
1985
+ cats = self.train_data[cate].cat.categories
1986
+ self.cat_categories_for_shap[cate] = list(cats)
1987
+ self.num_features = [
1988
+ nme for nme in cfg.factor_nmes if nme not in cate_list]
1989
+ train_oht = self.train_data[cfg.factor_nmes +
1990
+ [cfg.weight_nme] + [cfg.resp_nme]].copy()
1991
+ test_oht = self.test_data[cfg.factor_nmes +
1992
+ [cfg.weight_nme] + [cfg.resp_nme]].copy()
1993
+ train_oht = pd.get_dummies(
1994
+ train_oht,
1995
+ columns=cate_list,
1996
+ drop_first=True,
1997
+ dtype=np.int8
1998
+ )
1999
+ test_oht = pd.get_dummies(
2000
+ test_oht,
2001
+ columns=cate_list,
2002
+ drop_first=True,
2003
+ dtype=np.int8
2004
+ )
2005
+
2006
+ # 重新索引时将缺失的哑变量列补零,避免测试集列数与训练集不一致
2007
+ test_oht = test_oht.reindex(columns=train_oht.columns, fill_value=0)
2008
+
2009
+ # 保留未缩放的 one-hot 数据,供交叉验证时按折内标准化避免泄露
2010
+ self.train_oht_data = train_oht.copy(deep=True)
2011
+ self.test_oht_data = test_oht.copy(deep=True)
2012
+
2013
+ train_oht_scaled = train_oht.copy(deep=True)
2014
+ test_oht_scaled = test_oht.copy(deep=True)
2015
+ for num_chr in self.num_features:
2016
+ # 逐列标准化保障每个特征在同一量级,否则神经网络会难以收敛
2017
+ scaler = StandardScaler()
2018
+ train_oht_scaled[num_chr] = scaler.fit_transform(
2019
+ train_oht_scaled[num_chr].values.reshape(-1, 1))
2020
+ test_oht_scaled[num_chr] = scaler.transform(
2021
+ test_oht_scaled[num_chr].values.reshape(-1, 1))
2022
+ # 重新索引时将缺失的哑变量列补零,避免测试集列数与训练集不一致
2023
+ test_oht_scaled = test_oht_scaled.reindex(
2024
+ columns=train_oht_scaled.columns, fill_value=0)
2025
+ self.train_oht_scl_data = train_oht_scaled
2026
+ self.test_oht_scl_data = test_oht_scaled
2027
+ self.var_nmes = list(
2028
+ set(list(train_oht_scaled.columns)) -
2029
+ set([cfg.weight_nme, cfg.resp_nme])
2030
+ )
2031
+ return self
2032
+
2033
+ # =============================================================================
2034
+ # 训练器体系
2035
+ # =============================================================================
2036
+
2037
+
2038
+ class TrainerBase:
2039
+ def __init__(self, context: "BayesOptModel", label: str, model_name_prefix: str) -> None:
2040
+ self.ctx = context
2041
+ self.label = label
2042
+ self.model_name_prefix = model_name_prefix
2043
+ self.model = None
2044
+ self.best_params: Optional[Dict[str, Any]] = None
2045
+ self.best_trial = None
2046
+ self.enable_distributed_optuna: bool = False
2047
+ self._distributed_forced_params: Optional[Dict[str, Any]] = None
2048
+
2049
+ @property
2050
+ def config(self) -> BayesOptConfig:
2051
+ return self.ctx.config
2052
+
2053
+ @property
2054
+ def output(self) -> OutputManager:
2055
+ return self.ctx.output_manager
2056
+
2057
+ def _get_model_filename(self) -> str:
2058
+ ext = 'pkl' if self.label in ['Xgboost', 'GLM'] else 'pth'
2059
+ return f'01_{self.ctx.model_nme}_{self.model_name_prefix}.{ext}'
2060
+
2061
+ def tune(self, max_evals: int, objective_fn=None) -> None:
2062
+ # 通用的 Optuna 调参循环流程。
2063
+ if objective_fn is None:
2064
+ # 若子类未显式提供 objective_fn,则默认使用 cross_val 作为优化目标
2065
+ objective_fn = self.cross_val
2066
+
2067
+ if self._should_use_distributed_optuna():
2068
+ self._distributed_tune(max_evals, objective_fn)
2069
+ return
2070
+
2071
+ total_trials = max(1, int(max_evals))
2072
+ progress_counter = {"count": 0}
2073
+
2074
+ def objective_wrapper(trial: optuna.trial.Trial) -> float:
2075
+ should_log = DistributedUtils.is_main_process()
2076
+ if should_log:
2077
+ current_idx = progress_counter["count"] + 1
2078
+ print(
2079
+ f"[Optuna][{self.label}] Trial {current_idx}/{total_trials} started "
2080
+ f"(trial_id={trial.number})."
2081
+ )
2082
+ try:
2083
+ result = objective_fn(trial)
2084
+ except RuntimeError as exc:
2085
+ if "out of memory" in str(exc).lower():
2086
+ print(
2087
+ f"[Optuna][{self.label}] OOM detected. Pruning trial and clearing CUDA cache."
2088
+ )
2089
+ self._clean_gpu()
2090
+ raise optuna.TrialPruned() from exc
2091
+ raise
2092
+ finally:
2093
+ self._clean_gpu()
2094
+ if should_log:
2095
+ progress_counter["count"] = progress_counter["count"] + 1
2096
+ trial_state = getattr(trial, "state", None)
2097
+ state_repr = getattr(trial_state, "name", "OK")
2098
+ print(
2099
+ f"[Optuna][{self.label}] Trial {progress_counter['count']}/{total_trials} finished "
2100
+ f"(status={state_repr})."
2101
+ )
2102
+ return result
2103
+
2104
+ study = optuna.create_study(
2105
+ direction='minimize',
2106
+ sampler=optuna.samplers.TPESampler(seed=self.ctx.rand_seed)
2107
+ )
2108
+ study.optimize(objective_wrapper, n_trials=max_evals)
2109
+ self.best_params = study.best_params
2110
+ self.best_trial = study.best_trial
2111
+
2112
+ # 将最优参数保存为 CSV,方便复现
2113
+ params_path = self.output.result_path(
2114
+ f'{self.ctx.model_nme}_bestparams_{self.label.lower()}.csv'
2115
+ )
2116
+ pd.DataFrame(self.best_params, index=[0]).to_csv(params_path)
2117
+
2118
+ def train(self) -> None:
2119
+ raise NotImplementedError
2120
+
2121
+ def save(self) -> None:
2122
+ if self.model is None:
2123
+ print(f"[save] Warning: No model to save for {self.label}")
2124
+ return
2125
+
2126
+ path = self.output.model_path(self._get_model_filename())
2127
+ if self.label in ['Xgboost', 'GLM']:
2128
+ joblib.dump(self.model, path)
2129
+ else:
2130
+ # PyTorch 模型既可以只存 state_dict,也可以整个对象一起序列化
2131
+ # 兼容历史行为:ResNetTrainer 保存 state_dict,FTTrainer 保存完整对象
2132
+ if hasattr(self.model, 'resnet'): # ResNetSklearn 模型
2133
+ torch.save(self.model.resnet.state_dict(), path)
2134
+ else: # FTTransformerSklearn 或其他 PyTorch 模型
2135
+ torch.save(self.model, path)
2136
+
2137
+ def load(self) -> None:
2138
+ path = self.output.model_path(self._get_model_filename())
2139
+ if not os.path.exists(path):
2140
+ print(f"[load] Warning: Model file not found: {path}")
2141
+ return
2142
+
2143
+ if self.label in ['Xgboost', 'GLM']:
2144
+ self.model = joblib.load(path)
2145
+ else:
2146
+ # PyTorch 模型的加载需要根据结构区别处理
2147
+ if self.label == 'ResNet' or self.label == 'ResNetClassifier':
2148
+ # ResNet 需要重新构建骨架,结构参数依赖 ctx,因此交由子类处理
2149
+ pass
2150
+ else:
2151
+ # FT-Transformer 序列化了整个对象,可直接加载后迁移到目标设备
2152
+ loaded = torch.load(path, map_location='cpu')
2153
+ self._move_to_device(loaded)
2154
+ self.model = loaded
2155
+
2156
+ def _move_to_device(self, model_obj):
2157
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
2158
+ if hasattr(model_obj, 'device'):
2159
+ model_obj.device = device
2160
+ if hasattr(model_obj, 'to'):
2161
+ model_obj.to(device)
2162
+ # 若对象内部还包含 ft/resnet 子模块,也要同时迁移设备
2163
+ if hasattr(model_obj, 'ft'):
2164
+ model_obj.ft.to(device)
2165
+ if hasattr(model_obj, 'resnet'):
2166
+ model_obj.resnet.to(device)
2167
+ if hasattr(model_obj, 'gnn'):
2168
+ model_obj.gnn.to(device)
2169
+
2170
+ def _should_use_distributed_optuna(self) -> bool:
2171
+ if not self.enable_distributed_optuna:
2172
+ return False
2173
+ try:
2174
+ world_env = int(os.environ.get("WORLD_SIZE", "1"))
2175
+ except Exception:
2176
+ world_env = 1
2177
+ return world_env > 1
2178
+
2179
+ def _distributed_is_main(self) -> bool:
2180
+ return DistributedUtils.is_main_process()
2181
+
2182
+ def _distributed_send_command(self, payload: Dict[str, Any]) -> None:
2183
+ if not self._should_use_distributed_optuna() or not self._distributed_is_main():
2184
+ return
2185
+ DistributedUtils.setup_ddp()
2186
+ message = [payload]
2187
+ dist.broadcast_object_list(message, src=0)
2188
+
2189
+ def _distributed_prepare_trial(self, params: Dict[str, Any]) -> None:
2190
+ if not self._should_use_distributed_optuna():
2191
+ return
2192
+ if not self._distributed_is_main():
2193
+ return
2194
+ self._distributed_send_command({"type": "RUN", "params": params})
2195
+ dist.barrier()
2196
+
2197
+ def _distributed_worker_loop(self, objective_fn: Callable[[Optional[optuna.trial.Trial]], float]) -> None:
2198
+ DistributedUtils.setup_ddp()
2199
+ while True:
2200
+ message = [None]
2201
+ dist.broadcast_object_list(message, src=0)
2202
+ payload = message[0]
2203
+ if not isinstance(payload, dict):
2204
+ continue
2205
+ cmd = payload.get("type")
2206
+ if cmd == "STOP":
2207
+ best_params = payload.get("best_params")
2208
+ if best_params is not None:
2209
+ self.best_params = best_params
2210
+ break
2211
+ if cmd == "RUN":
2212
+ params = payload.get("params") or {}
2213
+ self._distributed_forced_params = params
2214
+ dist.barrier()
2215
+ try:
2216
+ objective_fn(None)
2217
+ except optuna.TrialPruned:
2218
+ pass
2219
+ except Exception as exc:
2220
+ print(
2221
+ f"[Optuna][Worker][{self.label}] Exception: {exc}", flush=True)
2222
+ finally:
2223
+ self._clean_gpu()
2224
+ dist.barrier()
2225
+
2226
+ def _distributed_tune(self, max_evals: int, objective_fn: Callable[[optuna.trial.Trial], float]) -> None:
2227
+ DistributedUtils.setup_ddp()
2228
+ if not self._distributed_is_main():
2229
+ self._distributed_worker_loop(objective_fn)
2230
+ return
2231
+
2232
+ total_trials = max(1, int(max_evals))
2233
+ progress_counter = {"count": 0}
2234
+
2235
+ def objective_wrapper(trial: optuna.trial.Trial) -> float:
2236
+ should_log = True
2237
+ if should_log:
2238
+ current_idx = progress_counter["count"] + 1
2239
+ print(
2240
+ f"[Optuna][{self.label}] Trial {current_idx}/{total_trials} started "
2241
+ f"(trial_id={trial.number})."
2242
+ )
2243
+ try:
2244
+ result = objective_fn(trial)
2245
+ except RuntimeError as exc:
2246
+ if "out of memory" in str(exc).lower():
2247
+ print(
2248
+ f"[Optuna][{self.label}] OOM detected. Pruning trial and clearing CUDA cache."
2249
+ )
2250
+ self._clean_gpu()
2251
+ raise optuna.TrialPruned() from exc
2252
+ raise
2253
+ finally:
2254
+ self._clean_gpu()
2255
+ if should_log:
2256
+ progress_counter["count"] = progress_counter["count"] + 1
2257
+ trial_state = getattr(trial, "state", None)
2258
+ state_repr = getattr(trial_state, "name", "OK")
2259
+ print(
2260
+ f"[Optuna][{self.label}] Trial {progress_counter['count']}/{total_trials} finished "
2261
+ f"(status={state_repr})."
2262
+ )
2263
+ dist.barrier()
2264
+ return result
2265
+
2266
+ study = optuna.create_study(
2267
+ direction='minimize',
2268
+ sampler=optuna.samplers.TPESampler(seed=self.ctx.rand_seed)
2269
+ )
2270
+ try:
2271
+ study.optimize(objective_wrapper, n_trials=max_evals)
2272
+ self.best_params = study.best_params
2273
+ self.best_trial = study.best_trial
2274
+ params_path = self.output.result_path(
2275
+ f'{self.ctx.model_nme}_bestparams_{self.label.lower()}.csv'
2276
+ )
2277
+ pd.DataFrame(self.best_params, index=[0]).to_csv(params_path)
2278
+ finally:
2279
+ self._distributed_send_command(
2280
+ {"type": "STOP", "best_params": self.best_params})
2281
+
2282
+ def _clean_gpu(self):
2283
+ gc.collect()
2284
+ if torch.cuda.is_available():
2285
+ device = None
2286
+ try:
2287
+ device = getattr(self, "device", None)
2288
+ except Exception:
2289
+ device = None
2290
+ if isinstance(device, torch.device):
2291
+ try:
2292
+ torch.cuda.set_device(device)
2293
+ except Exception:
2294
+ pass
2295
+ torch.cuda.empty_cache()
2296
+ torch.cuda.ipc_collect()
2297
+ torch.cuda.synchronize()
2298
+
2299
+ def _standardize_fold(self,
2300
+ X_train: pd.DataFrame,
2301
+ X_val: pd.DataFrame,
2302
+ columns: Optional[List[str]] = None
2303
+ ) -> Tuple[pd.DataFrame, pd.DataFrame, StandardScaler]:
2304
+ """在训练折上拟合 StandardScaler,并同步变换训练/验证特征。
2305
+
2306
+ 参数:
2307
+ X_train: 训练集特征。
2308
+ X_val: 验证集特征。
2309
+ columns: 需要缩放的列名;默认对全部列进行缩放。
2310
+
2311
+ 返回:
2312
+ 缩放后的训练/验证特征,以及已拟合好的 scaler 对象。
2313
+ """
2314
+ scaler = StandardScaler()
2315
+ cols = list(columns) if columns else list(X_train.columns)
2316
+ X_train_scaled = X_train.copy(deep=True)
2317
+ X_val_scaled = X_val.copy(deep=True)
2318
+ if cols:
2319
+ scaler.fit(X_train_scaled[cols])
2320
+ X_train_scaled[cols] = scaler.transform(X_train_scaled[cols])
2321
+ X_val_scaled[cols] = scaler.transform(X_val_scaled[cols])
2322
+ return X_train_scaled, X_val_scaled, scaler
2323
+
2324
+ def cross_val_generic(
2325
+ self,
2326
+ trial: optuna.trial.Trial,
2327
+ hyperparameter_space: Dict[str, Callable[[optuna.trial.Trial], Any]],
2328
+ data_provider: Callable[[], Tuple[pd.DataFrame, pd.Series, Optional[pd.Series]]],
2329
+ model_builder: Callable[[Dict[str, Any]], Any],
2330
+ metric_fn: Callable[[pd.Series, np.ndarray, Optional[pd.Series]], float],
2331
+ sample_limit: Optional[int] = None,
2332
+ preprocess_fn: Optional[Callable[[
2333
+ pd.DataFrame, pd.DataFrame], Tuple[pd.DataFrame, pd.DataFrame]]] = None,
2334
+ fit_predict_fn: Optional[
2335
+ Callable[[Any, pd.DataFrame, pd.Series, Optional[pd.Series],
2336
+ pd.DataFrame, pd.Series, Optional[pd.Series],
2337
+ optuna.trial.Trial], np.ndarray]
2338
+ ] = None,
2339
+ cleanup_fn: Optional[Callable[[Any], None]] = None,
2340
+ splitter: Optional[Iterable[Tuple[np.ndarray, np.ndarray]]] = None) -> float:
2341
+ """通用的留出/交叉验证辅助函数,用于复用调参流程。
2342
+
2343
+ 参数:
2344
+ trial: 当前 Optuna trial。
2345
+ hyperparameter_space: 参数采样器字典,键为参数名。
2346
+ data_provider: 返回 (X, y, sample_weight) 的回调。
2347
+ model_builder: 每个折构造新模型的回调。
2348
+ metric_fn: 计算损失或得分的函数,入参为 y_true、y_pred、weight。
2349
+ sample_limit: 可选样本上限,超出时随机抽样。
2350
+ preprocess_fn: 可选的折内预处理函数,输入 (X_train, X_val)。
2351
+ fit_predict_fn: 可选自定义训练与预测逻辑,返回验证集预测。
2352
+ cleanup_fn: 可选清理函数,每个折结束后调用。
2353
+ splitter: 可选的 (train_idx, val_idx) 迭代器;默认使用单个 ShuffleSplit。
2354
+
2355
+ 返回:
2356
+ 各折验证指标的平均值。
2357
+ """
2358
+ params: Optional[Dict[str, Any]] = None
2359
+ if self._distributed_forced_params is not None:
2360
+ params = self._distributed_forced_params
2361
+ self._distributed_forced_params = None
2362
+ else:
2363
+ if trial is None:
2364
+ raise RuntimeError(
2365
+ "Missing Optuna trial for parameter sampling.")
2366
+ params = {name: sampler(trial)
2367
+ for name, sampler in hyperparameter_space.items()}
2368
+ if self._should_use_distributed_optuna():
2369
+ self._distributed_prepare_trial(params)
2370
+ X_all, y_all, w_all = data_provider()
2371
+ if sample_limit is not None and len(X_all) > sample_limit:
2372
+ sampled_idx = X_all.sample(
2373
+ n=sample_limit,
2374
+ random_state=self.ctx.rand_seed
2375
+ ).index
2376
+ X_all = X_all.loc[sampled_idx]
2377
+ y_all = y_all.loc[sampled_idx]
2378
+ w_all = w_all.loc[sampled_idx] if w_all is not None else None
2379
+
2380
+ splits = splitter or [next(ShuffleSplit(
2381
+ n_splits=int(1 / self.ctx.prop_test),
2382
+ test_size=self.ctx.prop_test,
2383
+ random_state=self.ctx.rand_seed
2384
+ ).split(X_all))]
2385
+
2386
+ losses: List[float] = []
2387
+ for train_idx, val_idx in splits:
2388
+ X_train = X_all.iloc[train_idx]
2389
+ y_train = y_all.iloc[train_idx]
2390
+ X_val = X_all.iloc[val_idx]
2391
+ y_val = y_all.iloc[val_idx]
2392
+ w_train = w_all.iloc[train_idx] if w_all is not None else None
2393
+ w_val = w_all.iloc[val_idx] if w_all is not None else None
2394
+
2395
+ if preprocess_fn:
2396
+ X_train, X_val = preprocess_fn(X_train, X_val)
2397
+
2398
+ model = model_builder(params)
2399
+ try:
2400
+ if fit_predict_fn:
2401
+ y_pred = fit_predict_fn(
2402
+ model, X_train, y_train, w_train,
2403
+ X_val, y_val, w_val, trial
2404
+ )
2405
+ else:
2406
+ fit_kwargs = {}
2407
+ if w_train is not None:
2408
+ fit_kwargs["sample_weight"] = w_train
2409
+ model.fit(X_train, y_train, **fit_kwargs)
2410
+ y_pred = model.predict(X_val)
2411
+ losses.append(metric_fn(y_val, y_pred, w_val))
2412
+ finally:
2413
+ if cleanup_fn:
2414
+ cleanup_fn(model)
2415
+ self._clean_gpu()
2416
+
2417
+ return float(np.mean(losses))
2418
+
2419
+ # 预测 + 缓存逻辑
2420
+ def _predict_and_cache(self,
2421
+ model,
2422
+ pred_prefix: str,
2423
+ use_oht: bool = False,
2424
+ design_fn=None) -> None:
2425
+ if design_fn:
2426
+ X_train = design_fn(train=True)
2427
+ X_test = design_fn(train=False)
2428
+ elif use_oht:
2429
+ X_train = self.ctx.train_oht_scl_data[self.ctx.var_nmes]
2430
+ X_test = self.ctx.test_oht_scl_data[self.ctx.var_nmes]
2431
+ else:
2432
+ X_train = self.ctx.train_data[self.ctx.factor_nmes]
2433
+ X_test = self.ctx.test_data[self.ctx.factor_nmes]
2434
+
2435
+ preds_train = model.predict(X_train)
2436
+ preds_test = model.predict(X_test)
2437
+
2438
+ self.ctx.train_data[f'pred_{pred_prefix}'] = preds_train
2439
+ self.ctx.test_data[f'pred_{pred_prefix}'] = preds_test
2440
+ self.ctx.train_data[f'w_pred_{pred_prefix}'] = (
2441
+ self.ctx.train_data[f'pred_{pred_prefix}'] *
2442
+ self.ctx.train_data[self.ctx.weight_nme]
2443
+ )
2444
+ self.ctx.test_data[f'w_pred_{pred_prefix}'] = (
2445
+ self.ctx.test_data[f'pred_{pred_prefix}'] *
2446
+ self.ctx.test_data[self.ctx.weight_nme]
2447
+ )
2448
+
2449
+ def _fit_predict_cache(self,
2450
+ model,
2451
+ X_train,
2452
+ y_train,
2453
+ sample_weight,
2454
+ pred_prefix: str,
2455
+ use_oht: bool = False,
2456
+ design_fn=None,
2457
+ fit_kwargs: Optional[Dict[str, Any]] = None,
2458
+ sample_weight_arg: Optional[str] = 'sample_weight') -> None:
2459
+ fit_kwargs = fit_kwargs.copy() if fit_kwargs else {}
2460
+ if sample_weight is not None and sample_weight_arg:
2461
+ fit_kwargs.setdefault(sample_weight_arg, sample_weight)
2462
+ model.fit(X_train, y_train, **fit_kwargs)
2463
+ self.ctx.model_label.append(self.label)
2464
+ self._predict_and_cache(
2465
+ model, pred_prefix, use_oht=use_oht, design_fn=design_fn)
2466
+
2467
+
2468
+ class XGBTrainer(TrainerBase):
2469
+ def __init__(self, context: "BayesOptModel") -> None:
2470
+ super().__init__(context, 'Xgboost', 'Xgboost')
2471
+ self.model: Optional[xgb.XGBRegressor] = None
2472
+
2473
+ def _build_estimator(self) -> xgb.XGBRegressor:
2474
+ params = dict(
2475
+ objective=self.ctx.obj,
2476
+ random_state=self.ctx.rand_seed,
2477
+ subsample=0.9,
2478
+ tree_method='gpu_hist' if self.ctx.use_gpu else 'hist',
2479
+ enable_categorical=True,
2480
+ predictor='gpu_predictor' if self.ctx.use_gpu else 'cpu_predictor'
2481
+ )
2482
+ if self.ctx.use_gpu:
2483
+ params['gpu_id'] = 0
2484
+ print(f">>> XGBoost using GPU ID: 0 (Single GPU Mode)")
2485
+ return xgb.XGBRegressor(**params)
2486
+
2487
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2488
+ learning_rate = trial.suggest_float(
2489
+ 'learning_rate', 1e-5, 1e-1, log=True)
2490
+ gamma = trial.suggest_float('gamma', 0, 10000)
2491
+ max_depth = trial.suggest_int('max_depth', 3, 25)
2492
+ n_estimators = trial.suggest_int('n_estimators', 10, 500, step=10)
2493
+ min_child_weight = trial.suggest_int(
2494
+ 'min_child_weight', 100, 10000, step=100)
2495
+ reg_alpha = trial.suggest_float('reg_alpha', 1e-10, 1, log=True)
2496
+ reg_lambda = trial.suggest_float('reg_lambda', 1e-10, 1, log=True)
2497
+ if self.ctx.obj == 'reg:tweedie':
2498
+ tweedie_variance_power = trial.suggest_float(
2499
+ 'tweedie_variance_power', 1, 2)
2500
+ elif self.ctx.obj == 'count:poisson':
2501
+ tweedie_variance_power = 1
2502
+ elif self.ctx.obj == 'reg:gamma':
2503
+ tweedie_variance_power = 2
2504
+ else:
2505
+ tweedie_variance_power = 1.5
2506
+ clf = self._build_estimator()
2507
+ params = {
2508
+ 'learning_rate': learning_rate,
2509
+ 'gamma': gamma,
2510
+ 'max_depth': max_depth,
2511
+ 'n_estimators': n_estimators,
2512
+ 'min_child_weight': min_child_weight,
2513
+ 'reg_alpha': reg_alpha,
2514
+ 'reg_lambda': reg_lambda
2515
+ }
2516
+ if self.ctx.obj == 'reg:tweedie':
2517
+ params['tweedie_variance_power'] = tweedie_variance_power
2518
+ clf.set_params(**params)
2519
+ n_jobs = 1 if self.ctx.use_gpu else int(1 / self.ctx.prop_test)
2520
+ acc = cross_val_score(
2521
+ clf,
2522
+ self.ctx.train_data[self.ctx.factor_nmes],
2523
+ self.ctx.train_data[self.ctx.resp_nme].values,
2524
+ fit_params=self.ctx.fit_params,
2525
+ cv=self.ctx.cv,
2526
+ scoring=make_scorer(
2527
+ mean_tweedie_deviance,
2528
+ power=tweedie_variance_power,
2529
+ greater_is_better=False),
2530
+ error_score='raise',
2531
+ n_jobs=n_jobs
2532
+ ).mean()
2533
+ return -acc
2534
+
2535
+ def train(self) -> None:
2536
+ if not self.best_params:
2537
+ raise RuntimeError('请先运行 tune() 以获得 XGB 最优参数。')
2538
+ self.model = self._build_estimator()
2539
+ self.model.set_params(**self.best_params)
2540
+ self._fit_predict_cache(
2541
+ self.model,
2542
+ self.ctx.train_data[self.ctx.factor_nmes],
2543
+ self.ctx.train_data[self.ctx.resp_nme].values,
2544
+ sample_weight=None,
2545
+ pred_prefix='xgb',
2546
+ fit_kwargs=self.ctx.fit_params,
2547
+ sample_weight_arg=None # 样本权重已通过 fit_kwargs 传入
2548
+ )
2549
+ self.ctx.xgb_best = self.model
2550
+
2551
+
2552
+ class GLMTrainer(TrainerBase):
2553
+ def __init__(self, context: "BayesOptModel") -> None:
2554
+ super().__init__(context, 'GLM', 'GLM')
2555
+ self.model = None
2556
+
2557
+ def _select_family(self, tweedie_power: Optional[float] = None):
2558
+ if self.ctx.task_type == 'classification':
2559
+ return sm.families.Binomial()
2560
+ if self.ctx.obj == 'count:poisson':
2561
+ return sm.families.Poisson()
2562
+ if self.ctx.obj == 'reg:gamma':
2563
+ return sm.families.Gamma()
2564
+ power = tweedie_power if tweedie_power is not None else 1.5
2565
+ return sm.families.Tweedie(var_power=power, link=sm.families.links.log())
2566
+
2567
+ def _prepare_design(self, data: pd.DataFrame) -> pd.DataFrame:
2568
+ # 为 statsmodels 设计矩阵添加截距项
2569
+ X = data[self.ctx.var_nmes]
2570
+ return sm.add_constant(X, has_constant='add')
2571
+
2572
+ def _metric_power(self, family, tweedie_power: Optional[float]) -> float:
2573
+ if isinstance(family, sm.families.Poisson):
2574
+ return 1.0
2575
+ if isinstance(family, sm.families.Gamma):
2576
+ return 2.0
2577
+ if isinstance(family, sm.families.Tweedie):
2578
+ return tweedie_power if tweedie_power is not None else getattr(family, 'var_power', 1.5)
2579
+ return 1.5
2580
+
2581
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2582
+ param_space = {
2583
+ "alpha": lambda t: t.suggest_float('alpha', 1e-6, 1e2, log=True),
2584
+ "l1_ratio": lambda t: t.suggest_float('l1_ratio', 0.0, 1.0)
2585
+ }
2586
+ if self.ctx.task_type == 'regression' and self.ctx.obj == 'reg:tweedie':
2587
+ param_space["tweedie_power"] = lambda t: t.suggest_float(
2588
+ 'tweedie_power', 1.0, 2.0)
2589
+
2590
+ def data_provider():
2591
+ data = self.ctx.train_oht_data if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data
2592
+ assert data is not None, "Preprocessed training data is missing."
2593
+ return data[self.ctx.var_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2594
+
2595
+ def preprocess_fn(X_train, X_val):
2596
+ X_train_s, X_val_s, _ = self._standardize_fold(
2597
+ X_train, X_val, self.ctx.num_features)
2598
+ return self._prepare_design(X_train_s), self._prepare_design(X_val_s)
2599
+
2600
+ metric_ctx: Dict[str, Any] = {}
2601
+
2602
+ def model_builder(params):
2603
+ family = self._select_family(params.get("tweedie_power"))
2604
+ metric_ctx["family"] = family
2605
+ metric_ctx["tweedie_power"] = params.get("tweedie_power")
2606
+ return {
2607
+ "family": family,
2608
+ "alpha": params["alpha"],
2609
+ "l1_ratio": params["l1_ratio"],
2610
+ "tweedie_power": params.get("tweedie_power")
2611
+ }
2612
+
2613
+ def fit_predict(model_cfg, X_train, y_train, w_train, X_val, y_val, w_val, _trial):
2614
+ glm = sm.GLM(y_train, X_train,
2615
+ family=model_cfg["family"],
2616
+ freq_weights=w_train)
2617
+ result = glm.fit_regularized(
2618
+ alpha=model_cfg["alpha"],
2619
+ L1_wt=model_cfg["l1_ratio"],
2620
+ maxiter=200
2621
+ )
2622
+ return result.predict(X_val)
2623
+
2624
+ def metric_fn(y_true, y_pred, weight):
2625
+ if self.ctx.task_type == 'classification':
2626
+ y_pred_clipped = np.clip(y_pred, EPS, 1 - EPS)
2627
+ return log_loss(y_true, y_pred_clipped, sample_weight=weight)
2628
+ y_pred_safe = np.maximum(y_pred, EPS)
2629
+ return mean_tweedie_deviance(
2630
+ y_true,
2631
+ y_pred_safe,
2632
+ sample_weight=weight,
2633
+ power=self._metric_power(
2634
+ metric_ctx.get("family"), metric_ctx.get("tweedie_power"))
2635
+ )
2636
+
2637
+ return self.cross_val_generic(
2638
+ trial=trial,
2639
+ hyperparameter_space=param_space,
2640
+ data_provider=data_provider,
2641
+ model_builder=model_builder,
2642
+ metric_fn=metric_fn,
2643
+ preprocess_fn=preprocess_fn,
2644
+ fit_predict_fn=fit_predict,
2645
+ splitter=self.ctx.cv.split(self.ctx.train_oht_data[self.ctx.var_nmes]
2646
+ if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data[self.ctx.var_nmes])
2647
+ )
2648
+
2649
+ def train(self) -> None:
2650
+ if not self.best_params:
2651
+ raise RuntimeError('请先运行 tune() 以获得 GLM 最优参数。')
2652
+ tweedie_power = self.best_params.get('tweedie_power')
2653
+ family = self._select_family(tweedie_power)
2654
+
2655
+ X_train = self._prepare_design(self.ctx.train_oht_scl_data)
2656
+ y_train = self.ctx.train_oht_scl_data[self.ctx.resp_nme]
2657
+ w_train = self.ctx.train_oht_scl_data[self.ctx.weight_nme]
2658
+
2659
+ glm = sm.GLM(y_train, X_train, family=family,
2660
+ freq_weights=w_train)
2661
+ self.model = glm.fit_regularized(
2662
+ alpha=self.best_params['alpha'],
2663
+ L1_wt=self.best_params['l1_ratio'],
2664
+ maxiter=300
2665
+ )
2666
+
2667
+ self.ctx.glm_best = self.model
2668
+ self.ctx.model_label += [self.label]
2669
+ self._predict_and_cache(
2670
+ self.model,
2671
+ 'glm',
2672
+ design_fn=lambda train: self._prepare_design(
2673
+ self.ctx.train_oht_scl_data if train else self.ctx.test_oht_scl_data
2674
+ )
2675
+ )
2676
+
2677
+
2678
+ class ResNetTrainer(TrainerBase):
2679
+ def __init__(self, context: "BayesOptModel") -> None:
2680
+ if context.task_type == 'classification':
2681
+ super().__init__(context, 'ResNetClassifier', 'ResNet')
2682
+ else:
2683
+ super().__init__(context, 'ResNet', 'ResNet')
2684
+ self.model: Optional[ResNetSklearn] = None
2685
+ self.enable_distributed_optuna = bool(context.config.use_resn_ddp)
2686
+
2687
+ # ========= 交叉验证(BayesOpt 用) =========
2688
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2689
+ # 针对 ResNet 的交叉验证流程,重点控制显存:
2690
+ # - 每个 fold 单独创建 ResNetSklearn,结束立刻释放资源;
2691
+ # - fold 完成后迁移模型到 CPU,删除对象并调用 gc/empty_cache;
2692
+ # - 可选:BayesOpt 期间只抽样部分训练集以减少显存压力。
2693
+
2694
+ base_tw_power = None
2695
+ if self.ctx.task_type == 'regression':
2696
+ if self.ctx.obj == 'count:poisson':
2697
+ base_tw_power = 1.0
2698
+ elif self.ctx.obj == 'reg:gamma':
2699
+ base_tw_power = 2.0
2700
+ else:
2701
+ base_tw_power = 1.5
2702
+
2703
+ def data_provider():
2704
+ data = self.ctx.train_oht_data if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data
2705
+ assert data is not None, "Preprocessed training data is missing."
2706
+ return data[self.ctx.var_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2707
+
2708
+ metric_ctx: Dict[str, Any] = {}
2709
+
2710
+ def model_builder(params):
2711
+ power = params.get("tw_power", base_tw_power)
2712
+ metric_ctx["tw_power"] = power
2713
+ return ResNetSklearn(
2714
+ model_nme=self.ctx.model_nme,
2715
+ input_dim=len(self.ctx.var_nmes),
2716
+ hidden_dim=params["hidden_dim"],
2717
+ block_num=params["block_num"],
2718
+ task_type=self.ctx.task_type,
2719
+ epochs=self.ctx.epochs,
2720
+ tweedie_power=power,
2721
+ learning_rate=params["learning_rate"],
2722
+ patience=5,
2723
+ use_layernorm=True,
2724
+ dropout=0.1,
2725
+ residual_scale=0.1,
2726
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2727
+ use_ddp=self.ctx.config.use_resn_ddp
2728
+ )
2729
+
2730
+ def preprocess_fn(X_train, X_val):
2731
+ X_train_s, X_val_s, _ = self._standardize_fold(
2732
+ X_train, X_val, self.ctx.num_features)
2733
+ return X_train_s, X_val_s
2734
+
2735
+ def fit_predict(model, X_train, y_train, w_train, X_val, y_val, w_val, trial_obj):
2736
+ model.fit(
2737
+ X_train, y_train, w_train,
2738
+ X_val, y_val, w_val,
2739
+ trial=trial_obj
2740
+ )
2741
+ return model.predict(X_val)
2742
+
2743
+ def metric_fn(y_true, y_pred, weight):
2744
+ if self.ctx.task_type == 'regression':
2745
+ return mean_tweedie_deviance(
2746
+ y_true,
2747
+ y_pred,
2748
+ sample_weight=weight,
2749
+ power=metric_ctx.get("tw_power", base_tw_power)
2750
+ )
2751
+ return log_loss(y_true, y_pred, sample_weight=weight)
2752
+
2753
+ sample_cap = data_provider()[0]
2754
+ max_rows_for_resnet_bo = min(100000, int(len(sample_cap)/5))
2755
+
2756
+ return self.cross_val_generic(
2757
+ trial=trial,
2758
+ hyperparameter_space={
2759
+ "learning_rate": lambda t: t.suggest_float('learning_rate', 1e-6, 1e-2, log=True),
2760
+ "hidden_dim": lambda t: t.suggest_int('hidden_dim', 8, 32, step=2),
2761
+ "block_num": lambda t: t.suggest_int('block_num', 2, 10),
2762
+ **({"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 {})
2763
+ },
2764
+ data_provider=data_provider,
2765
+ model_builder=model_builder,
2766
+ metric_fn=metric_fn,
2767
+ sample_limit=max_rows_for_resnet_bo if len(
2768
+ sample_cap) > max_rows_for_resnet_bo > 0 else None,
2769
+ preprocess_fn=preprocess_fn,
2770
+ fit_predict_fn=fit_predict,
2771
+ cleanup_fn=lambda m: getattr(
2772
+ getattr(m, "resnet", None), "to", lambda *_args, **_kwargs: None)("cpu")
2773
+ )
2774
+
2775
+ # ========= 用最优超参训练最终 ResNet =========
2776
+ def train(self) -> None:
2777
+ if not self.best_params:
2778
+ raise RuntimeError('请先运行 tune() 以获得 ResNet 最优参数。')
2779
+
2780
+ self.model = ResNetSklearn(
2781
+ model_nme=self.ctx.model_nme,
2782
+ input_dim=self.ctx.train_oht_scl_data[self.ctx.var_nmes].shape[1],
2783
+ task_type=self.ctx.task_type,
2784
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2785
+ use_ddp=self.ctx.config.use_resn_ddp
2786
+ )
2787
+ self.model.set_params(self.best_params)
2788
+
2789
+ self._fit_predict_cache(
2790
+ self.model,
2791
+ self.ctx.train_oht_scl_data[self.ctx.var_nmes],
2792
+ self.ctx.train_oht_scl_data[self.ctx.resp_nme],
2793
+ sample_weight=self.ctx.train_oht_scl_data[self.ctx.weight_nme],
2794
+ pred_prefix='resn',
2795
+ use_oht=True,
2796
+ sample_weight_arg='w_train'
2797
+ )
2798
+
2799
+ # 方便外部调用
2800
+ self.ctx.resn_best = self.model
2801
+
2802
+ # ========= 保存 / 加载 =========
2803
+ # ResNet 以 state_dict 形式保存,需要专用的加载流程,因此保留自定义加载方法
2804
+ # 保存逻辑已在 TrainerBase 中实现(会自动检查 .resnet 属性)
2805
+
2806
+ def load(self) -> None:
2807
+ # 将磁盘中的 ResNet 权重加载到当前设备,保持与上下文一致。
2808
+ path = self.output.model_path(self._get_model_filename())
2809
+ if os.path.exists(path):
2810
+ resn_loaded = ResNetSklearn(
2811
+ model_nme=self.ctx.model_nme,
2812
+ input_dim=self.ctx.train_oht_scl_data[self.ctx.var_nmes].shape[1],
2813
+ task_type=self.ctx.task_type,
2814
+ use_data_parallel=self.ctx.config.use_resn_data_parallel,
2815
+ use_ddp=self.ctx.config.use_resn_ddp
2816
+ )
2817
+ state_dict = torch.load(path, map_location='cpu')
2818
+ resn_loaded.resnet.load_state_dict(state_dict)
2819
+
2820
+ self._move_to_device(resn_loaded)
2821
+ self.model = resn_loaded
2822
+ self.ctx.resn_best = self.model
2823
+ else:
2824
+ print(f"[ResNetTrainer.load] 未找到模型文件:{path}")
2825
+
2826
+
2827
+ class FTTrainer(TrainerBase):
2828
+ def __init__(self, context: "BayesOptModel") -> None:
2829
+ if context.task_type == 'classification':
2830
+ super().__init__(context, 'FTTransformerClassifier', 'FTTransformer')
2831
+ else:
2832
+ super().__init__(context, 'FTTransformer', 'FTTransformer')
2833
+ self.model: Optional[FTTransformerSklearn] = None
2834
+ self.enable_distributed_optuna = bool(context.config.use_ft_ddp)
2835
+
2836
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2837
+ # 针对 FT-Transformer 的交叉验证,重点同样在显存控制:
2838
+ # - 收缩超参搜索空间,防止不必要的超大模型;
2839
+ # - 每个 fold 结束后立即释放 GPU 显存,确保下一个 trial 顺利进行。
2840
+ # 超参空间适当缩小一点,避免特别大的模型
2841
+ param_space: Dict[str, Callable[[optuna.trial.Trial], Any]] = {
2842
+ "learning_rate": lambda t: t.suggest_float('learning_rate', 1e-5, 5e-4, log=True),
2843
+ "d_model": lambda t: t.suggest_int('d_model', 8, 64, step=8),
2844
+ "n_heads": lambda t: t.suggest_categorical('n_heads', [2, 4, 8]),
2845
+ "n_layers": lambda t: t.suggest_int('n_layers', 2, 8),
2846
+ "dropout": lambda t: t.suggest_float('dropout', 0.0, 0.2)
2847
+ }
2848
+ if self.ctx.task_type == 'regression' and self.ctx.obj == 'reg:tweedie':
2849
+ param_space["tw_power"] = lambda t: t.suggest_float(
2850
+ 'tw_power', 1.0, 2.0)
2851
+
2852
+ metric_ctx: Dict[str, Any] = {}
2853
+
2854
+ def data_provider():
2855
+ data = self.ctx.train_data
2856
+ return data[self.ctx.factor_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2857
+
2858
+ def model_builder(params):
2859
+ d_model = params["d_model"]
2860
+ n_layers = params["n_layers"]
2861
+ approx_units = d_model * n_layers * \
2862
+ max(1, len(self.ctx.factor_nmes))
2863
+ if approx_units > 12_000_000:
2864
+ print(
2865
+ f"[FTTrainer] Trial pruned early: d_model={d_model}, n_layers={n_layers} -> approx_units={approx_units}")
2866
+ raise optuna.TrialPruned(
2867
+ "config exceeds safe memory budget; prune before training")
2868
+
2869
+ tw_power = params.get("tw_power")
2870
+ if self.ctx.task_type == 'regression':
2871
+ if self.ctx.obj == 'count:poisson':
2872
+ tw_power = 1.0
2873
+ elif self.ctx.obj == 'reg:gamma':
2874
+ tw_power = 2.0
2875
+ elif tw_power is None:
2876
+ tw_power = 1.5
2877
+ metric_ctx["tw_power"] = tw_power
2878
+
2879
+ return FTTransformerSklearn(
2880
+ model_nme=self.ctx.model_nme,
2881
+ num_cols=self.ctx.num_features,
2882
+ cat_cols=self.ctx.cate_list,
2883
+ d_model=d_model,
2884
+ n_heads=params["n_heads"],
2885
+ n_layers=n_layers,
2886
+ dropout=params["dropout"],
2887
+ task_type=self.ctx.task_type,
2888
+ epochs=self.ctx.epochs,
2889
+ tweedie_power=tw_power,
2890
+ learning_rate=params["learning_rate"],
2891
+ patience=5,
2892
+ use_data_parallel=self.ctx.config.use_ft_data_parallel,
2893
+ use_ddp=self.ctx.config.use_ft_ddp
2894
+ )
2895
+
2896
+ def fit_predict(model, X_train, y_train, w_train, X_val, y_val, w_val, trial_obj):
2897
+ model.fit(
2898
+ X_train, y_train, w_train,
2899
+ X_val, y_val, w_val,
2900
+ trial=trial_obj
2901
+ )
2902
+ return model.predict(X_val)
2903
+
2904
+ def metric_fn(y_true, y_pred, weight):
2905
+ if self.ctx.task_type == 'regression':
2906
+ return mean_tweedie_deviance(
2907
+ y_true,
2908
+ y_pred,
2909
+ sample_weight=weight,
2910
+ power=metric_ctx.get("tw_power", 1.5)
2911
+ )
2912
+ return log_loss(y_true, y_pred, sample_weight=weight)
2913
+
2914
+ data_for_cap = data_provider()[0]
2915
+ max_rows_for_ft_bo = min(1000000, int(len(data_for_cap)/2))
2916
+
2917
+ return self.cross_val_generic(
2918
+ trial=trial,
2919
+ hyperparameter_space=param_space,
2920
+ data_provider=data_provider,
2921
+ model_builder=model_builder,
2922
+ metric_fn=metric_fn,
2923
+ sample_limit=max_rows_for_ft_bo if len(
2924
+ data_for_cap) > max_rows_for_ft_bo > 0 else None,
2925
+ fit_predict_fn=fit_predict,
2926
+ cleanup_fn=lambda m: getattr(
2927
+ getattr(m, "ft", None), "to", lambda *_args, **_kwargs: None)("cpu")
2928
+ )
2929
+
2930
+ def train(self) -> None:
2931
+ if not self.best_params:
2932
+ raise RuntimeError('请先运行 tune() 以获得 FT-Transformer 最优参数。')
2933
+ self.model = FTTransformerSklearn(
2934
+ model_nme=self.ctx.model_nme,
2935
+ num_cols=self.ctx.num_features,
2936
+ cat_cols=self.ctx.cate_list,
2937
+ task_type=self.ctx.task_type,
2938
+ use_data_parallel=self.ctx.config.use_ft_data_parallel,
2939
+ use_ddp=self.ctx.config.use_ft_ddp
2940
+ )
2941
+ self.model.set_params(self.best_params)
2942
+ self._fit_predict_cache(
2943
+ self.model,
2944
+ self.ctx.train_data[self.ctx.factor_nmes],
2945
+ self.ctx.train_data[self.ctx.resp_nme],
2946
+ sample_weight=self.ctx.train_data[self.ctx.weight_nme],
2947
+ pred_prefix='ft',
2948
+ sample_weight_arg='w_train'
2949
+ )
2950
+ self.ctx.ft_best = self.model
2951
+
2952
+
2953
+ class GNNTrainer(TrainerBase):
2954
+ def __init__(self, context: "BayesOptModel") -> None:
2955
+ if context.task_type == 'classification':
2956
+ super().__init__(context, 'GNNClassifier', 'GNN')
2957
+ else:
2958
+ super().__init__(context, 'GNN', 'GNN')
2959
+ self.model: Optional[GraphNeuralNetSklearn] = None
2960
+ self.enable_distributed_optuna = bool(context.config.use_gnn_ddp)
2961
+
2962
+ def cross_val(self, trial: optuna.trial.Trial) -> float:
2963
+ base_tw_power = None
2964
+ if self.ctx.task_type == 'regression':
2965
+ if self.ctx.obj == 'count:poisson':
2966
+ base_tw_power = 1.0
2967
+ elif self.ctx.obj == 'reg:gamma':
2968
+ base_tw_power = 2.0
2969
+ else:
2970
+ base_tw_power = 1.5
2971
+
2972
+ metric_ctx: Dict[str, Any] = {}
2973
+
2974
+ def data_provider():
2975
+ data = self.ctx.train_oht_data if self.ctx.train_oht_data is not None else self.ctx.train_oht_scl_data
2976
+ assert data is not None, "Preprocessed training data is missing."
2977
+ return data[self.ctx.var_nmes], data[self.ctx.resp_nme], data[self.ctx.weight_nme]
2978
+
2979
+ def preprocess_fn(X_train, X_val):
2980
+ X_train_s, X_val_s, _ = self._standardize_fold(
2981
+ X_train, X_val, self.ctx.num_features)
2982
+ return X_train_s, X_val_s
2983
+
2984
+ def model_builder(params):
2985
+ power = params.get("tw_power", base_tw_power)
2986
+ metric_ctx["tw_power"] = power
2987
+ return GraphNeuralNetSklearn(
2988
+ model_nme=self.ctx.model_nme,
2989
+ input_dim=len(self.ctx.var_nmes),
2990
+ hidden_dim=params["hidden_dim"],
2991
+ num_layers=params["num_layers"],
2992
+ k_neighbors=params["k_neighbors"],
2993
+ dropout=params["dropout"],
2994
+ learning_rate=params["learning_rate"],
2995
+ epochs=self.ctx.epochs,
2996
+ patience=5,
2997
+ task_type=self.ctx.task_type,
2998
+ tweedie_power=power if power is not None else 1.5,
2999
+ use_ddp=False, # BO 阶段默认单卡,避免多进程与 Optuna 冲突
3000
+ use_approx_knn=self.ctx.config.gnn_use_approx_knn,
3001
+ approx_knn_threshold=self.ctx.config.gnn_approx_knn_threshold,
3002
+ max_gpu_knn_nodes=self.ctx.config.gnn_max_gpu_knn_nodes,
3003
+ knn_gpu_mem_ratio=self.ctx.config.gnn_knn_gpu_mem_ratio,
3004
+ knn_gpu_mem_overhead=self.ctx.config.gnn_knn_gpu_mem_overhead
3005
+ )
3006
+
3007
+ def fit_predict(model, X_train, y_train, w_train, X_val, y_val, w_val, trial_obj):
3008
+ model.fit(
3009
+ X_train, y_train, w_train,
3010
+ X_val, y_val, w_val,
3011
+ trial=trial_obj
3012
+ )
3013
+ return model.predict(X_val)
3014
+
3015
+ def metric_fn(y_true, y_pred, weight):
3016
+ if self.ctx.task_type == 'regression':
3017
+ return mean_tweedie_deviance(
3018
+ y_true,
3019
+ y_pred,
3020
+ sample_weight=weight,
3021
+ power=metric_ctx.get("tw_power", 1.5)
3022
+ )
3023
+ return log_loss(y_true, y_pred, sample_weight=weight)
3024
+
3025
+ base_X = data_provider()[0]
3026
+ max_rows_for_gnn_bo = min(50_000, max(1, int(len(base_X) / 5)))
3027
+
3028
+ return self.cross_val_generic(
3029
+ trial=trial,
3030
+ hyperparameter_space={
3031
+ "learning_rate": lambda t: t.suggest_float('learning_rate', 1e-5, 5e-3, log=True),
3032
+ "hidden_dim": lambda t: t.suggest_int('hidden_dim', 16, 128, step=16),
3033
+ "num_layers": lambda t: t.suggest_int('num_layers', 1, 4),
3034
+ "k_neighbors": lambda t: t.suggest_int('k_neighbors', 5, 20),
3035
+ "dropout": lambda t: t.suggest_float('dropout', 0.0, 0.3),
3036
+ **({"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 {})
3037
+ },
3038
+ data_provider=data_provider,
3039
+ model_builder=model_builder,
3040
+ metric_fn=metric_fn,
3041
+ sample_limit=max_rows_for_gnn_bo if len(
3042
+ base_X) > max_rows_for_gnn_bo > 0 else None,
3043
+ preprocess_fn=preprocess_fn,
3044
+ fit_predict_fn=fit_predict,
3045
+ cleanup_fn=lambda m: getattr(
3046
+ getattr(m, "gnn", None), "to", lambda *_args, **_kwargs: None)("cpu")
3047
+ )
3048
+
3049
+ def train(self) -> None:
3050
+ if not self.best_params:
3051
+ raise RuntimeError('请先运行 tune() 以获得 GNN 最优参数。')
3052
+
3053
+ self.model = GraphNeuralNetSklearn(
3054
+ model_nme=self.ctx.model_nme,
3055
+ input_dim=self.ctx.train_oht_scl_data[self.ctx.var_nmes].shape[1],
3056
+ task_type=self.ctx.task_type,
3057
+ use_data_parallel=self.ctx.config.use_gnn_data_parallel,
3058
+ use_ddp=self.ctx.config.use_gnn_ddp,
3059
+ use_approx_knn=self.ctx.config.gnn_use_approx_knn,
3060
+ approx_knn_threshold=self.ctx.config.gnn_approx_knn_threshold,
3061
+ graph_cache_path=self.ctx.config.gnn_graph_cache,
3062
+ max_gpu_knn_nodes=self.ctx.config.gnn_max_gpu_knn_nodes,
3063
+ knn_gpu_mem_ratio=self.ctx.config.gnn_knn_gpu_mem_ratio,
3064
+ knn_gpu_mem_overhead=self.ctx.config.gnn_knn_gpu_mem_overhead
3065
+ )
3066
+ self.model.set_params(self.best_params)
3067
+
3068
+ self._fit_predict_cache(
3069
+ self.model,
3070
+ self.ctx.train_oht_scl_data[self.ctx.var_nmes],
3071
+ self.ctx.train_oht_scl_data[self.ctx.resp_nme],
3072
+ sample_weight=self.ctx.train_oht_scl_data[self.ctx.weight_nme],
3073
+ pred_prefix='gnn',
3074
+ use_oht=True,
3075
+ sample_weight_arg='w_train'
3076
+ )
3077
+ self.ctx.gnn_best = self.model
3078
+
3079
+
3080
+ # =============================================================================
3081
+ # BayesOpt 调度与 SHAP 工具集
3082
+ # =============================================================================
3083
+ class BayesOptModel:
3084
+ def __init__(self, train_data, test_data,
3085
+ model_nme, resp_nme, weight_nme, factor_nmes, task_type='regression',
3086
+ binary_resp_nme=None,
3087
+ cate_list=None, prop_test=0.25, rand_seed=None,
3088
+ epochs=100, use_gpu=True,
3089
+ use_resn_data_parallel: bool = False, use_ft_data_parallel: bool = False,
3090
+ use_gnn_data_parallel: bool = False,
3091
+ use_resn_ddp: bool = False, use_ft_ddp: bool = False,
3092
+ use_gnn_ddp: bool = False,
3093
+ output_dir: Optional[str] = None,
3094
+ gnn_use_approx_knn: bool = True,
3095
+ gnn_approx_knn_threshold: int = 50000,
3096
+ gnn_graph_cache: Optional[str] = None,
3097
+ gnn_max_gpu_knn_nodes: Optional[int] = 200000,
3098
+ gnn_knn_gpu_mem_ratio: float = 0.9,
3099
+ gnn_knn_gpu_mem_overhead: float = 2.0):
3100
+ """封装各类训练器的 BayesOpt 调度入口。
3101
+
3102
+ 参数:
3103
+ train_data: 训练集 DataFrame。
3104
+ test_data: 测试集 DataFrame。
3105
+ model_nme: 模型名称前缀,用于输出文件。
3106
+ resp_nme: 目标列名。
3107
+ weight_nme: 样本权重列名。
3108
+ factor_nmes: 特征列名列表。
3109
+ task_type: 'regression' 或 'classification'。
3110
+ binary_resp_nme: 可选的二分类目标,用于成交率曲线。
3111
+ cate_list: 类别型特征列表。
3112
+ prop_test: 交叉验证中验证集的占比。
3113
+ rand_seed: 随机种子。
3114
+ epochs: 神经网络训练轮数。
3115
+ use_gpu: 是否优先使用 GPU。
3116
+ use_resn_data_parallel: ResNet 是否启用 DataParallel。
3117
+ use_ft_data_parallel: FTTransformer 是否启用 DataParallel。
3118
+ use_gnn_data_parallel: GNN 是否启用 DataParallel。
3119
+ use_resn_ddp: ResNet 是否启用 DDP。
3120
+ use_ft_ddp: FTTransformer 是否启用 DDP。
3121
+ use_gnn_ddp: GNN 是否启用 DDP。
3122
+ output_dir: 模型、结果与图表的输出根目录。
3123
+ gnn_use_approx_knn: 是否在可用时使用近似 kNN。
3124
+ gnn_approx_knn_threshold: 触发近似 kNN 的行数阈值。
3125
+ gnn_graph_cache: 可选的邻接矩阵缓存路径。
3126
+ gnn_max_gpu_knn_nodes: 超过该节点数则强制使用 CPU kNN 以避免 GPU OOM。
3127
+ gnn_knn_gpu_mem_ratio: GPU kNN 允许使用的可用显存比例。
3128
+ gnn_knn_gpu_mem_overhead: GPU kNN 估算的临时显存放大倍数。
3129
+ """
3130
+ cfg = BayesOptConfig(
3131
+ model_nme=model_nme,
3132
+ task_type=task_type,
3133
+ resp_nme=resp_nme,
3134
+ weight_nme=weight_nme,
3135
+ factor_nmes=list(factor_nmes),
3136
+ binary_resp_nme=binary_resp_nme,
3137
+ cate_list=list(cate_list) if cate_list else None,
3138
+ prop_test=prop_test,
3139
+ rand_seed=rand_seed,
3140
+ epochs=epochs,
3141
+ use_gpu=use_gpu,
3142
+ use_resn_data_parallel=use_resn_data_parallel,
3143
+ use_ft_data_parallel=use_ft_data_parallel,
3144
+ use_resn_ddp=use_resn_ddp,
3145
+ use_gnn_data_parallel=use_gnn_data_parallel,
3146
+ use_ft_ddp=use_ft_ddp,
3147
+ use_gnn_ddp=use_gnn_ddp,
3148
+ gnn_use_approx_knn=gnn_use_approx_knn,
3149
+ gnn_approx_knn_threshold=gnn_approx_knn_threshold,
3150
+ gnn_graph_cache=gnn_graph_cache,
3151
+ gnn_max_gpu_knn_nodes=gnn_max_gpu_knn_nodes,
3152
+ gnn_knn_gpu_mem_ratio=gnn_knn_gpu_mem_ratio,
3153
+ gnn_knn_gpu_mem_overhead=gnn_knn_gpu_mem_overhead,
3154
+ output_dir=output_dir
3155
+ )
3156
+ self.config = cfg
3157
+ self.model_nme = cfg.model_nme
3158
+ self.task_type = cfg.task_type
3159
+ self.resp_nme = cfg.resp_nme
3160
+ self.weight_nme = cfg.weight_nme
3161
+ self.factor_nmes = cfg.factor_nmes
3162
+ self.binary_resp_nme = cfg.binary_resp_nme
3163
+ self.cate_list = list(cfg.cate_list or [])
3164
+ self.prop_test = cfg.prop_test
3165
+ self.epochs = cfg.epochs
3166
+ self.rand_seed = cfg.rand_seed if cfg.rand_seed is not None else np.random.randint(
3167
+ 1, 10000)
3168
+ self.use_gpu = bool(cfg.use_gpu and torch.cuda.is_available())
3169
+ self.output_manager = OutputManager(
3170
+ cfg.output_dir or os.getcwd(), self.model_nme)
3171
+
3172
+ preprocessor = DatasetPreprocessor(train_data, test_data, cfg).run()
3173
+ self.train_data = preprocessor.train_data
3174
+ self.test_data = preprocessor.test_data
3175
+ self.train_oht_data = preprocessor.train_oht_data
3176
+ self.test_oht_data = preprocessor.test_oht_data
3177
+ self.train_oht_scl_data = preprocessor.train_oht_scl_data
3178
+ self.test_oht_scl_data = preprocessor.test_oht_scl_data
3179
+ self.var_nmes = preprocessor.var_nmes
3180
+ self.num_features = preprocessor.num_features
3181
+ self.cat_categories_for_shap = preprocessor.cat_categories_for_shap
3182
+
3183
+ self.cv = ShuffleSplit(n_splits=int(1/self.prop_test),
3184
+ test_size=self.prop_test,
3185
+ random_state=self.rand_seed)
3186
+ if self.task_type == 'classification':
3187
+ self.obj = 'binary:logistic'
3188
+ else: # 回归任务
3189
+ if 'f' in self.model_nme:
3190
+ self.obj = 'count:poisson'
3191
+ elif 's' in self.model_nme:
3192
+ self.obj = 'reg:gamma'
3193
+ elif 'bc' in self.model_nme:
3194
+ self.obj = 'reg:tweedie'
3195
+ else:
3196
+ self.obj = 'reg:tweedie'
3197
+ self.fit_params = {
3198
+ 'sample_weight': self.train_data[self.weight_nme].values
3199
+ }
3200
+ self.model_label: List[str] = []
3201
+ self.optuna_storage = cfg.optuna_storage
3202
+ self.optuna_study_prefix = cfg.optuna_study_prefix or "bayesopt"
3203
+
3204
+ # 记录各模型训练器,后续统一通过标签访问,方便扩展新模型
3205
+ self.trainers: Dict[str, TrainerBase] = {
3206
+ 'glm': GLMTrainer(self),
3207
+ 'xgb': XGBTrainer(self),
3208
+ 'resn': ResNetTrainer(self),
3209
+ 'gnn': GNNTrainer(self),
3210
+ 'ft': FTTrainer(self)
3211
+ }
3212
+ self.xgb_best = None
3213
+ self.resn_best = None
3214
+ self.glm_best = None
3215
+ self.ft_best = None
3216
+ self.gnn_best = None
3217
+ self.best_xgb_params = None
3218
+ self.best_resn_params = None
3219
+ self.best_ft_params = None
3220
+ self.best_gnn_params = None
3221
+ self.best_xgb_trial = None
3222
+ self.best_resn_trial = None
3223
+ self.best_ft_trial = None
3224
+ self.best_gnn_trial = None
3225
+ self.best_glm_params = None
3226
+ self.best_glm_trial = None
3227
+ self.xgb_load = None
3228
+ self.resn_load = None
3229
+ self.ft_load = None
3230
+ self.gnn_load = None
3231
+
3232
+ # 定义单因素画图函数
3233
+ def plot_oneway(self, n_bins=10):
3234
+ for c in self.factor_nmes:
3235
+ fig = plt.figure(figsize=(7, 5))
3236
+ if c in self.cate_list:
3237
+ group_col = c
3238
+ plot_source = self.train_data
3239
+ else:
3240
+ group_col = f'{c}_bins'
3241
+ bins = pd.qcut(
3242
+ self.train_data[c],
3243
+ n_bins,
3244
+ duplicates='drop' # 注意:如果分位数重复会丢 bin,避免异常终止
3245
+ )
3246
+ plot_source = self.train_data.assign(**{group_col: bins})
3247
+ plot_data = plot_source.groupby(
3248
+ [group_col], observed=True).sum(numeric_only=True)
3249
+ plot_data.reset_index(inplace=True)
3250
+ plot_data['act_v'] = plot_data['w_act'] / \
3251
+ plot_data[self.weight_nme]
3252
+ plot_data.head()
3253
+ ax = fig.add_subplot(111)
3254
+ ax.plot(plot_data.index, plot_data['act_v'],
3255
+ label='Actual', color='red')
3256
+ ax.set_title(
3257
+ 'Analysis of %s : Train Data' % group_col,
3258
+ fontsize=8)
3259
+ plt.xticks(plot_data.index,
3260
+ list(plot_data[group_col].astype(str)),
3261
+ rotation=90)
3262
+ if len(list(plot_data[group_col].astype(str))) > 50:
3263
+ plt.xticks(fontsize=3)
3264
+ else:
3265
+ plt.xticks(fontsize=6)
3266
+ plt.yticks(fontsize=6)
3267
+ ax2 = ax.twinx()
3268
+ ax2.bar(plot_data.index,
3269
+ plot_data[self.weight_nme],
3270
+ alpha=0.5, color='seagreen')
3271
+ plt.yticks(fontsize=6)
3272
+ plt.margins(0.05)
3273
+ plt.subplots_adjust(wspace=0.3)
3274
+ save_path = self.output_manager.plot_path(
3275
+ f'00_{self.model_nme}_{group_col}_oneway.png')
3276
+ plt.savefig(save_path, dpi=300)
3277
+ plt.close(fig)
3278
+
3279
+ # 定义通用优化函数
3280
+ def optimize_model(self, model_key: str, max_evals: int = 100):
3281
+ if model_key not in self.trainers:
3282
+ print(f"Warning: Unknown model key: {model_key}")
3283
+ return
3284
+
3285
+ trainer = self.trainers[model_key]
3286
+ trainer.tune(max_evals)
3287
+ trainer.train()
3288
+
3289
+ # 更新上下文字段,保证历史接口的兼容性
3290
+ setattr(self, f"{model_key}_best", trainer.model)
3291
+ setattr(self, f"best_{model_key}_params", trainer.best_params)
3292
+ setattr(self, f"best_{model_key}_trial", trainer.best_trial)
3293
+
3294
+ # 定义GLM贝叶斯优化函数
3295
+ def bayesopt_glm(self, max_evals=50):
3296
+ self.optimize_model('glm', max_evals)
3297
+
3298
+ # 定义Xgboost贝叶斯优化函数
3299
+ def bayesopt_xgb(self, max_evals=100):
3300
+ self.optimize_model('xgb', max_evals)
3301
+
3302
+ # 定义ResNet贝叶斯优化函数
3303
+ def bayesopt_resnet(self, max_evals=100):
3304
+ self.optimize_model('resn', max_evals)
3305
+
3306
+ # 定义 GNN 贝叶斯优化函数
3307
+ def bayesopt_gnn(self, max_evals=50):
3308
+ self.optimize_model('gnn', max_evals)
3309
+
3310
+ # 定义 FT-Transformer 贝叶斯优化函数
3311
+ def bayesopt_ft(self, max_evals=50):
3312
+ self.optimize_model('ft', max_evals)
3313
+
3314
+ # 绘制提纯曲线
3315
+ def plot_lift(self, model_label, pred_nme, n_bins=10):
3316
+ model_map = {
3317
+ 'Xgboost': 'pred_xgb',
3318
+ 'ResNet': 'pred_resn',
3319
+ 'ResNetClassifier': 'pred_resn',
3320
+ 'FTTransformer': 'pred_ft',
3321
+ 'FTTransformerClassifier': 'pred_ft',
3322
+ 'GLM': 'pred_glm',
3323
+ 'GNN': 'pred_gnn',
3324
+ 'GNNClassifier': 'pred_gnn'
3325
+ }
3326
+ for k, v in model_map.items():
3327
+ if model_label.startswith(k):
3328
+ pred_nme = v
3329
+ break
3330
+
3331
+ fig = plt.figure(figsize=(11, 5))
3332
+ for pos, (title, data) in zip([121, 122],
3333
+ [('Lift Chart on Train Data', self.train_data),
3334
+ ('Lift Chart on Test Data', self.test_data)]):
3335
+ lift_df = pd.DataFrame({
3336
+ 'pred': data[pred_nme].values,
3337
+ 'w_pred': data[f'w_{pred_nme}'].values,
3338
+ 'act': data['w_act'].values,
3339
+ 'weight': data[self.weight_nme].values
3340
+ })
3341
+ plot_data = PlotUtils.split_data(lift_df, 'pred', 'weight', n_bins)
3342
+ denom = np.maximum(plot_data['weight'], EPS)
3343
+ plot_data['exp_v'] = plot_data['w_pred'] / denom
3344
+ plot_data['act_v'] = plot_data['act'] / denom
3345
+ plot_data = plot_data.reset_index()
3346
+
3347
+ ax = fig.add_subplot(pos)
3348
+ PlotUtils.plot_lift_ax(ax, plot_data, title)
3349
+
3350
+ plt.subplots_adjust(wspace=0.3)
3351
+ save_path = self.output_manager.plot_path(
3352
+ f'01_{self.model_nme}_{model_label}_lift.png')
3353
+ plt.savefig(save_path, dpi=300)
3354
+ plt.show()
3355
+ plt.close(fig)
3356
+
3357
+ # 绘制双提纯曲线
3358
+ def plot_dlift(self, model_comp: List[str] = ['xgb', 'resn'], n_bins: int = 10) -> None:
3359
+ # 绘制双提纯曲线,对比两个模型在不同分箱下的表现。
3360
+ # 参数说明:
3361
+ # model_comp: 需要对比的模型简称(如 ['xgb', 'resn'],支持 'xgb'/'resn'/'ft')。
3362
+ # n_bins: 分箱数量,用于控制 lift 曲线的粒度。
3363
+ if len(model_comp) != 2:
3364
+ raise ValueError("`model_comp` 必须包含两个模型进行对比。")
3365
+
3366
+ model_name_map = {
3367
+ 'xgb': 'Xgboost',
3368
+ 'resn': 'ResNet',
3369
+ 'ft': 'FTTransformer',
3370
+ 'glm': 'GLM',
3371
+ 'gnn': 'GNN'
3372
+ }
3373
+
3374
+ name1, name2 = model_comp
3375
+ if name1 not in model_name_map or name2 not in model_name_map:
3376
+ raise ValueError(f"不支持的模型简称。请从 {list(model_name_map.keys())} 中选择。")
3377
+
3378
+ fig, axes = plt.subplots(1, 2, figsize=(11, 5))
3379
+ datasets = {
3380
+ 'Train Data': self.train_data,
3381
+ 'Test Data': self.test_data
3382
+ }
3383
+
3384
+ for ax, (data_name, data) in zip(axes, datasets.items()):
3385
+ pred1_col = f'w_pred_{name1}'
3386
+ pred2_col = f'w_pred_{name2}'
3387
+
3388
+ if pred1_col not in data.columns or pred2_col not in data.columns:
3389
+ print(
3390
+ f"警告: 在 {data_name} 中找不到预测列 {pred1_col} 或 {pred2_col}。跳过绘图。")
3391
+ continue
3392
+
3393
+ lift_data = pd.DataFrame({
3394
+ 'pred1': data[pred1_col].values,
3395
+ 'pred2': data[pred2_col].values,
3396
+ 'diff_ly': data[pred1_col].values / np.maximum(data[pred2_col].values, EPS),
3397
+ 'act': data['w_act'].values,
3398
+ 'weight': data[self.weight_nme].values
3399
+ })
3400
+ plot_data = PlotUtils.split_data(
3401
+ lift_data, 'diff_ly', 'weight', n_bins)
3402
+ denom = np.maximum(plot_data['act'], EPS)
3403
+ plot_data['exp_v1'] = plot_data['pred1'] / denom
3404
+ plot_data['exp_v2'] = plot_data['pred2'] / denom
3405
+ plot_data['act_v'] = plot_data['act'] / denom
3406
+ plot_data.reset_index(inplace=True)
3407
+
3408
+ label1 = model_name_map[name1]
3409
+ label2 = model_name_map[name2]
3410
+
3411
+ PlotUtils.plot_dlift_ax(
3412
+ ax, plot_data, f'Double Lift Chart on {data_name}', label1, label2)
3413
+
3414
+ plt.subplots_adjust(bottom=0.25, top=0.95, right=0.8, wspace=0.3)
3415
+ save_path = self.output_manager.plot_path(
3416
+ f'02_{self.model_nme}_dlift_{name1}_vs_{name2}.png')
3417
+ plt.savefig(save_path, dpi=300)
3418
+ plt.show()
3419
+ plt.close(fig)
3420
+
3421
+ # 绘制成交率提升曲线
3422
+ def plot_conversion_lift(self, model_pred_col: str, n_bins: int = 20):
3423
+ if not self.binary_resp_nme:
3424
+ print("错误: 未在 BayesOptModel 初始化时提供 `binary_resp_nme`。无法绘制成交率曲线。")
3425
+ return
3426
+
3427
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6), sharey=True)
3428
+ datasets = {
3429
+ 'Train Data': self.train_data,
3430
+ 'Test Data': self.test_data
3431
+ }
3432
+
3433
+ for ax, (data_name, data) in zip(axes, datasets.items()):
3434
+ if model_pred_col not in data.columns:
3435
+ print(f"警告: 在 {data_name} 中找不到预测列 '{model_pred_col}'。跳过绘图。")
3436
+ continue
3437
+
3438
+ # 按模型预测分排序,并计算分箱
3439
+ plot_data = data.sort_values(by=model_pred_col).copy()
3440
+ plot_data['cum_weight'] = plot_data[self.weight_nme].cumsum()
3441
+ total_weight = plot_data[self.weight_nme].sum()
3442
+
3443
+ if total_weight > EPS:
3444
+ plot_data['bin'] = pd.cut(
3445
+ plot_data['cum_weight'],
3446
+ bins=n_bins,
3447
+ labels=False,
3448
+ right=False
3449
+ )
3450
+ else:
3451
+ plot_data['bin'] = 0
3452
+
3453
+ # 按分箱聚合
3454
+ lift_agg = plot_data.groupby('bin').agg(
3455
+ total_weight=(self.weight_nme, 'sum'),
3456
+ actual_conversions=(self.binary_resp_nme, 'sum'),
3457
+ weighted_conversions=('w_binary_act', 'sum'),
3458
+ avg_pred=(model_pred_col, 'mean')
3459
+ ).reset_index()
3460
+
3461
+ # 计算成交率
3462
+ lift_agg['conversion_rate'] = lift_agg['weighted_conversions'] / \
3463
+ lift_agg['total_weight']
3464
+
3465
+ # 计算整体平均成交率
3466
+ overall_conversion_rate = data['w_binary_act'].sum(
3467
+ ) / data[self.weight_nme].sum()
3468
+ ax.axhline(y=overall_conversion_rate, color='gray', linestyle='--',
3469
+ label=f'Overall Avg Rate ({overall_conversion_rate:.2%})')
3470
+
3471
+ ax.plot(lift_agg['bin'], lift_agg['conversion_rate'],
3472
+ marker='o', linestyle='-', label='Actual Conversion Rate')
3473
+ ax.set_title(f'Conversion Rate Lift Chart on {data_name}')
3474
+ ax.set_xlabel(f'Model Score Decile (based on {model_pred_col})')
3475
+ ax.set_ylabel('Conversion Rate')
3476
+ ax.grid(True, linestyle='--', alpha=0.6)
3477
+ ax.legend()
3478
+
3479
+ plt.tight_layout()
3480
+ plt.show()
3481
+
3482
+ # 保存模型
3483
+ def save_model(self, model_name=None):
3484
+ keys = [model_name] if model_name else self.trainers.keys()
3485
+ for key in keys:
3486
+ if key in self.trainers:
3487
+ self.trainers[key].save()
3488
+ else:
3489
+ if model_name: # 仅在用户指定模型名时输出告警
3490
+ print(f"[save_model] Warning: Unknown model key {key}")
3491
+
3492
+ def load_model(self, model_name=None):
3493
+ keys = [model_name] if model_name else self.trainers.keys()
3494
+ for key in keys:
3495
+ if key in self.trainers:
3496
+ self.trainers[key].load()
3497
+ # 同步上下文字段
3498
+ trainer = self.trainers[key]
3499
+ if trainer.model is not None:
3500
+ setattr(self, f"{key}_best", trainer.model)
3501
+ # 如需兼容旧版字段,也同步更新 xxx_load
3502
+ # 旧版只维护 xgb_load/resn_load/ft_load,未包含 glm_load
3503
+ if key in ['xgb', 'resn', 'ft']:
3504
+ setattr(self, f"{key}_load", trainer.model)
3505
+ else:
3506
+ if model_name:
3507
+ print(f"[load_model] Warning: Unknown model key {key}")
3508
+
3509
+ def _sample_rows(self, data: pd.DataFrame, n: int) -> pd.DataFrame:
3510
+ if len(data) == 0:
3511
+ return data
3512
+ return data.sample(min(len(data), n), random_state=self.rand_seed)
3513
+
3514
+ @staticmethod
3515
+ def _shap_nsamples(arr: np.ndarray, max_nsamples: int = 300) -> int:
3516
+ min_needed = arr.shape[1] + 2
3517
+ return max(min_needed, min(max_nsamples, arr.shape[0] * arr.shape[1]))
3518
+
3519
+ def _build_ft_shap_matrix(self, data: pd.DataFrame) -> np.ndarray:
3520
+ matrices = []
3521
+ for col in self.factor_nmes:
3522
+ s = data[col]
3523
+ if col in self.cate_list:
3524
+ cats = pd.Categorical(
3525
+ s,
3526
+ categories=self.cat_categories_for_shap[col]
3527
+ )
3528
+ codes = np.asarray(cats.codes, dtype=np.float64).reshape(-1, 1)
3529
+ matrices.append(codes)
3530
+ else:
3531
+ vals = pd.to_numeric(s, errors="coerce")
3532
+ arr = vals.to_numpy(dtype=np.float64, copy=True).reshape(-1, 1)
3533
+ matrices.append(arr)
3534
+ X_mat = np.concatenate(matrices, axis=1) # 结果形状为 (N, F)
3535
+ return X_mat
3536
+
3537
+ def _decode_ft_shap_matrix_to_df(self, X_mat: np.ndarray) -> pd.DataFrame:
3538
+ data_dict = {}
3539
+ for j, col in enumerate(self.factor_nmes):
3540
+ col_vals = X_mat[:, j]
3541
+ if col in self.cate_list:
3542
+ cats = self.cat_categories_for_shap[col]
3543
+ codes = np.round(col_vals).astype(int)
3544
+ codes = np.clip(codes, -1, len(cats) - 1)
3545
+ cat_series = pd.Categorical.from_codes(
3546
+ codes,
3547
+ categories=cats
3548
+ )
3549
+ data_dict[col] = cat_series
3550
+ else:
3551
+ data_dict[col] = col_vals.astype(float)
3552
+
3553
+ df = pd.DataFrame(data_dict, columns=self.factor_nmes)
3554
+ for col in self.cate_list:
3555
+ if col in df.columns:
3556
+ df[col] = df[col].astype("category")
3557
+ return df
3558
+
3559
+ def _build_glm_design(self, data: pd.DataFrame) -> pd.DataFrame:
3560
+ X = data[self.var_nmes]
3561
+ return sm.add_constant(X, has_constant='add')
3562
+
3563
+ def _compute_shap_core(self,
3564
+ model_key: str,
3565
+ n_background: int,
3566
+ n_samples: int,
3567
+ on_train: bool,
3568
+ X_df: pd.DataFrame,
3569
+ prep_fn,
3570
+ predict_fn,
3571
+ cleanup_fn=None):
3572
+ if model_key not in self.trainers or self.trainers[model_key].model is None:
3573
+ raise RuntimeError(f"Model {model_key} not trained.")
3574
+ if cleanup_fn:
3575
+ cleanup_fn()
3576
+ bg_df = self._sample_rows(X_df, n_background)
3577
+ bg_mat = prep_fn(bg_df)
3578
+ explainer = shap.KernelExplainer(predict_fn, bg_mat)
3579
+ ex_df = self._sample_rows(X_df, n_samples)
3580
+ ex_mat = prep_fn(ex_df)
3581
+ nsample_eff = self._shap_nsamples(ex_mat)
3582
+ shap_values = explainer.shap_values(ex_mat, nsamples=nsample_eff)
3583
+ bg_pred = predict_fn(bg_mat)
3584
+ base_value = float(np.asarray(bg_pred).mean())
3585
+
3586
+ return {
3587
+ "explainer": explainer,
3588
+ "X_explain": ex_df,
3589
+ "shap_values": shap_values,
3590
+ "base_value": base_value
3591
+ }
3592
+
3593
+ # ========= GLM 的 SHAP 解释 =========
3594
+ def compute_shap_glm(self, n_background: int = 500,
3595
+ n_samples: int = 200,
3596
+ on_train: bool = True):
3597
+ data = self.train_oht_scl_data if on_train else self.test_oht_scl_data
3598
+ design_all = self._build_glm_design(data)
3599
+ design_cols = list(design_all.columns)
3600
+
3601
+ def predict_wrapper(x_np):
3602
+ x_df = pd.DataFrame(x_np, columns=design_cols)
3603
+ y_pred = self.glm_best.predict(x_df)
3604
+ return np.asarray(y_pred, dtype=np.float64).reshape(-1)
3605
+
3606
+ self.shap_glm = self._compute_shap_core(
3607
+ 'glm', n_background, n_samples, on_train,
3608
+ X_df=design_all,
3609
+ prep_fn=lambda df: df.to_numpy(dtype=np.float64),
3610
+ predict_fn=predict_wrapper
3611
+ )
3612
+ return self.shap_glm
3613
+
3614
+ # ========= XGBoost 的 SHAP 解释 =========
3615
+ def compute_shap_xgb(self, n_background: int = 500,
3616
+ n_samples: int = 200,
3617
+ on_train: bool = True):
3618
+ data = self.train_data if on_train else self.test_data
3619
+ X_raw = data[self.factor_nmes]
3620
+
3621
+ def predict_wrapper(x_mat):
3622
+ df_input = self._decode_ft_shap_matrix_to_df(x_mat)
3623
+ return self.xgb_best.predict(df_input)
3624
+
3625
+ self.shap_xgb = self._compute_shap_core(
3626
+ 'xgb', n_background, n_samples, on_train,
3627
+ X_df=X_raw,
3628
+ prep_fn=lambda df: self._build_ft_shap_matrix(
3629
+ df).astype(np.float64),
3630
+ predict_fn=predict_wrapper
3631
+ )
3632
+ return self.shap_xgb
3633
+
3634
+ # ========= ResNet 的 SHAP 解释 =========
3635
+ def _resn_predict_wrapper(self, X_np):
3636
+ model = self.resn_best.resnet.to("cpu")
3637
+ with torch.no_grad():
3638
+ X_tensor = torch.tensor(X_np, dtype=torch.float32)
3639
+ y_pred = model(X_tensor).cpu().numpy()
3640
+ y_pred = np.clip(y_pred, 1e-6, None)
3641
+ return y_pred.reshape(-1)
3642
+
3643
+ def compute_shap_resn(self, n_background: int = 500,
3644
+ n_samples: int = 200,
3645
+ on_train: bool = True):
3646
+ data = self.train_oht_scl_data if on_train else self.test_oht_scl_data
3647
+ X = data[self.var_nmes]
3648
+
3649
+ def cleanup():
3650
+ self.resn_best.device = torch.device("cpu")
3651
+ self.resn_best.resnet.to("cpu")
3652
+ if torch.cuda.is_available():
3653
+ torch.cuda.empty_cache()
3654
+
3655
+ self.shap_resn = self._compute_shap_core(
3656
+ 'resn', n_background, n_samples, on_train,
3657
+ X_df=X,
3658
+ prep_fn=lambda df: df.to_numpy(dtype=np.float64),
3659
+ predict_fn=lambda x: self._resn_predict_wrapper(x),
3660
+ cleanup_fn=cleanup
3661
+ )
3662
+ return self.shap_resn
3663
+
3664
+ # ========= GNN 的 SHAP 解释 =========
3665
+ def _gnn_predict_wrapper(self, X_np: np.ndarray) -> np.ndarray:
3666
+ X_df = pd.DataFrame(X_np, columns=self.var_nmes)
3667
+ y_pred = self.gnn_best.predict(X_df)
3668
+ return np.asarray(y_pred, dtype=np.float64).reshape(-1)
3669
+
3670
+ def compute_shap_gnn(self, n_background: int = 300,
3671
+ n_samples: int = 150,
3672
+ on_train: bool = True):
3673
+ data = self.train_oht_scl_data if on_train else self.test_oht_scl_data
3674
+ if data is None:
3675
+ raise RuntimeError("One-hot 标准化数据未准备好,无法计算 GNN SHAP。")
3676
+ X = data[self.var_nmes]
3677
+
3678
+ def cleanup():
3679
+ self.gnn_best.device = torch.device("cpu")
3680
+ self.gnn_best.gnn.to("cpu")
3681
+ if torch.cuda.is_available():
3682
+ torch.cuda.empty_cache()
3683
+
3684
+ self.shap_gnn = self._compute_shap_core(
3685
+ 'gnn', n_background, n_samples, on_train,
3686
+ X_df=X,
3687
+ prep_fn=lambda df: df.to_numpy(dtype=np.float64),
3688
+ predict_fn=lambda x: self._gnn_predict_wrapper(x),
3689
+ cleanup_fn=cleanup
3690
+ )
3691
+ return self.shap_gnn
3692
+
3693
+ # ========= FT-Transformer 的 SHAP 解释 =========
3694
+ def _ft_shap_predict_wrapper(self, X_mat: np.ndarray) -> np.ndarray:
3695
+ df_input = self._decode_ft_shap_matrix_to_df(X_mat)
3696
+ y_pred = self.ft_best.predict(df_input)
3697
+ return np.asarray(y_pred, dtype=np.float64).reshape(-1)
3698
+
3699
+ def compute_shap_ft(self, n_background: int = 500,
3700
+ n_samples: int = 200,
3701
+ on_train: bool = True):
3702
+ data = self.train_data if on_train else self.test_data
3703
+ X_raw = data[self.factor_nmes]
3704
+
3705
+ def cleanup():
3706
+ self.ft_best.device = torch.device("cpu")
3707
+ self.ft_best.ft.to("cpu")
3708
+ if torch.cuda.is_available():
3709
+ torch.cuda.empty_cache()
3710
+
3711
+ self.shap_ft = self._compute_shap_core(
3712
+ 'ft', n_background, n_samples, on_train,
3713
+ X_df=X_raw,
3714
+ prep_fn=lambda df: self._build_ft_shap_matrix(
3715
+ df).astype(np.float64),
3716
+ predict_fn=self._ft_shap_predict_wrapper,
3717
+ cleanup_fn=cleanup
3718
+ )
3719
+ return self.shap_ft