-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbayesian_optimizer.py
More file actions
1966 lines (1609 loc) · 86 KB
/
bayesian_optimizer.py
File metadata and controls
1966 lines (1609 loc) · 86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
贝叶斯优化器(BayesianOptimizer)
主要的优化协调器类,实现完整的贝叶斯优化流程:
- 建议参数 -> 评估 -> 更新模型的优化循环
- 收敛检测和停止条件
- 错误处理和恢复机制
"""
import os
import time
import logging
import numpy as np
from typing import Dict, Any, Optional, List, Tuple, Callable
from datetime import datetime, timedelta
import warnings
# 导入核心组件
from autodl_core import ParameterSpace, OptimizationHistory, OptimizationResult
from gaussian_process import GaussianProcess, create_default_gaussian_process
from acquisition_function import AcquisitionFunction, create_acquisition_function, AcquisitionOptimizer
from task_evaluator import TaskEvaluator, create_task_evaluator
from state_manager import StateManager, create_default_state_manager, CheckpointError
# 导入新的输出系统
from unified_log_manager import UnifiedLogManager, get_global_log_manager, init_global_log_manager
from structured_tag_processor import get_global_tag_processor
class ConvergenceError(Exception):
"""收敛相关错误"""
pass
class OptimizationError(Exception):
"""优化过程错误"""
pass
class BayesianOptimizer:
"""
贝叶斯优化器
协调整个优化过程,管理高斯过程模型、采集函数和任务评估器
"""
def __init__(self,
parameter_space: ParameterSpace,
task_evaluator: TaskEvaluator,
acquisition_function: Optional[AcquisitionFunction] = None,
gaussian_process: Optional[GaussianProcess] = None,
state_manager: Optional[StateManager] = None,
n_initial_points: int = 10,
random_state: Optional[int] = None,
maximize: bool = True,
# 多目标优化参数
objectives: Optional[List[str]] = None,
maximize_objectives: Optional[Dict[str, bool]] = None,
objective_weights: Optional[Dict[str, float]] = None):
"""
初始化贝叶斯优化器
Args:
parameter_space: 参数空间管理器
task_evaluator: 任务评估器
acquisition_function: 采集函数,默认使用EI
gaussian_process: 高斯过程模型,默认创建标准配置
state_manager: 状态管理器,默认创建标准配置
n_initial_points: 初始随机采样点数
random_state: 随机种子
maximize: 是否最大化目标函数,默认True(单目标时使用)
objectives: 多目标优化的目标函数名称列表
maximize_objectives: 每个目标是否最大化的字典
objective_weights: 目标权重字典(用于加权求和)
"""
self.parameter_space = parameter_space
self.task_evaluator = task_evaluator
self.n_initial_points = n_initial_points
self.random_state = random_state
self.maximize = maximize
# 多目标优化配置
self.objectives = objectives or ['primary']
self.maximize_objectives = maximize_objectives or {'primary': maximize}
# 处理目标权重归一化
if objective_weights:
total_weight = sum(objective_weights.values())
if total_weight > 0:
self.objective_weights = {k: v / total_weight for k, v in objective_weights.items()}
else:
self.objective_weights = objective_weights
else:
self.objective_weights = objective_weights
self.is_multi_objective = len(self.objectives) > 1
# 创建或使用提供的组件
self.acquisition_function = acquisition_function or create_acquisition_function('EI', xi=0.01)
self.gaussian_process = gaussian_process or create_default_gaussian_process(random_state)
self.state_manager = state_manager or create_default_state_manager()
# 创建采集函数优化器
self.acquisition_optimizer = AcquisitionOptimizer(method='L-BFGS-B', n_restarts=10)
# 初始化优化历史
self.history = OptimizationHistory(
parameter_space=parameter_space.to_dict(),
acquisition_function=self.acquisition_function.function_type,
task_type=task_evaluator.task_type,
objectives=self.objectives,
maximize_objectives=self.maximize_objectives,
objective_weights=self.objective_weights
)
# 优化状态
self.is_initialized = False
self.current_iteration = 0
self.start_time: Optional[datetime] = None
self.last_checkpoint_time: Optional[datetime] = None
# 收敛检测参数
self.convergence_window = 10 # 收敛检测窗口大小
self.convergence_threshold = 1e-4 # 收敛阈值
self.patience = 20 # 早停耐心值
self.no_improvement_count = 0 # 无改进计数
# 错误处理参数
self.max_consecutive_failures = 5 # 最大连续失败次数
self.consecutive_failures = 0 # 当前连续失败次数
self.failed_parameters: List[Dict[str, Any]] = [] # 失败的参数记录
# 获取日志管理器
self.log_manager = get_global_log_manager()
if not self.log_manager:
# 如果没有全局日志管理器,创建一个临时的
self.log_manager = init_global_log_manager(f"bayesian_optimizer_{task_evaluator.task_type}")
# 记录初始化信息
self._log_initialization_info()
def _log_initialization_info(self):
"""记录详细的初始化信息"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
self.log_manager.log_with_tag(logging.INFO, "INIT",
"========== 贝叶斯优化器初始化开始 ==========",
component_name)
# 基本配置信息
self.log_manager.log_structured(logging.INFO, "CONFIG", {
"task_type": self.task_evaluator.task_type,
"parameter_count": self.parameter_space.get_parameter_count(),
"acquisition_function": self.acquisition_function.function_type,
"n_initial_points": self.n_initial_points,
"random_state": self.random_state,
"maximize": self.maximize,
"is_multi_objective": self.is_multi_objective
}, component_name)
# 参数空间详细信息
param_details = {}
for name, config in self.parameter_space.parameters.items():
if config.param_type.value == 'continuous':
param_details[name] = f"{config.param_type.value}[{config.bounds[0]:.4f}, {config.bounds[1]:.4f}]"
else:
param_details[name] = f"{config.param_type.value}{config.values}"
self.log_manager.log_structured(logging.INFO, "PARAMS", param_details, component_name)
# 多目标优化配置
if self.is_multi_objective:
self.log_manager.log_structured(logging.INFO, "MULTI_OBJECTIVE", {
"objectives": self.objectives,
"maximize_objectives": self.maximize_objectives,
"objective_weights": self.objective_weights
}, component_name)
# 收敛检测配置
self.log_manager.log_structured(logging.INFO, "CONVERGENCE", {
"convergence_window": self.convergence_window,
"convergence_threshold": self.convergence_threshold,
"patience": self.patience,
"max_consecutive_failures": self.max_consecutive_failures
}, component_name)
# 采集函数详细信息
acq_info = self.acquisition_function.get_info()
self.log_manager.log_structured(logging.INFO, "ACQUISITION", acq_info, component_name)
# 高斯过程配置
gp_info = {
"kernel_type": str(type(self.gaussian_process.kernel).__name__),
"is_fitted": self.gaussian_process.is_fitted,
"n_restarts_optimizer": getattr(self.gaussian_process, 'n_restarts_optimizer', 'N/A')
}
self.log_manager.log_structured(logging.INFO, "GAUSSIAN_PROCESS", gp_info, component_name)
self.log_manager.log_with_tag(logging.INFO, "INIT",
"贝叶斯优化器初始化完成",
component_name)
def optimize(self,
n_iterations: int = 100,
checkpoint_freq: int = 10,
time_limit: Optional[float] = None,
target_value: Optional[float] = None,
resume_from_checkpoint: Optional[str] = None) -> OptimizationHistory:
"""
执行贝叶斯优化
Args:
n_iterations: 最大迭代次数
checkpoint_freq: 检查点保存频率
time_limit: 时间限制(秒),None表示无限制
target_value: 目标值,达到后停止优化
resume_from_checkpoint: 从检查点恢复的路径
Returns:
优化历史记录
Raises:
OptimizationError: 当优化过程出现严重错误时
"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
try:
# 恢复或初始化优化状态
if resume_from_checkpoint:
self._resume_from_checkpoint(resume_from_checkpoint)
else:
self._initialize_optimization()
# 详细的优化开始信息
self.log_manager.log_with_tag(logging.INFO, "OPTIMIZATION",
"========== 贝叶斯优化开始 ==========",
component_name)
# 优化配置信息
optimization_config = {
"max_iterations": n_iterations,
"checkpoint_frequency": checkpoint_freq,
"time_limit_seconds": time_limit,
"target_value": target_value,
"resume_from_checkpoint": resume_from_checkpoint is not None,
"current_iteration": self.current_iteration,
"total_evaluations": len(self.history.results)
}
self.log_manager.log_structured(logging.INFO, "CONFIG", optimization_config, component_name)
# 时间和目标信息
if time_limit:
time_limit_hours = time_limit / 3600
self.log_manager.log_with_tag(logging.INFO, "CONFIG",
f"时间限制: {time_limit:.1f}秒 ({time_limit_hours:.2f}小时)",
component_name)
if target_value:
self.log_manager.log_with_tag(logging.INFO, "CONFIG",
f"目标值: {target_value:.6f}",
component_name)
# 当前状态信息
if self.history.best_result:
self.log_manager.log_structured(logging.INFO, "CURRENT_STATE", {
"best_objective_value": self.history.get_best_objective_value(),
"total_evaluations": len(self.history.results),
"consecutive_failures": self.consecutive_failures,
"no_improvement_count": self.no_improvement_count
}, component_name)
# 主优化循环
self.log_manager.log_with_tag(logging.INFO, "OPTIMIZATION",
"开始主优化循环", component_name)
while self.current_iteration < n_iterations:
iteration_start_time = time.time()
try:
# 检查停止条件
if self._should_stop(time_limit, target_value):
break
# 执行一次优化迭代
self._run_single_iteration()
# 更新迭代计数
self.current_iteration += 1
# 记录迭代时间
iteration_time = time.time() - iteration_start_time
self.history.total_time += iteration_time
# 详细的迭代完成信息
iteration_info = {
"iteration": self.current_iteration,
"iteration_time": iteration_time,
"total_time": self.history.total_time,
"current_best": self.history.get_best_objective_value(),
"consecutive_failures": self.consecutive_failures,
"no_improvement_count": self.no_improvement_count
}
if self.is_multi_objective:
iteration_info["pareto_front_size"] = len(self.history.pareto_front)
self.log_manager.log_structured(logging.INFO, "ITERATION_COMPLETE",
iteration_info, component_name)
# 检查收敛
if self._check_convergence():
self.log_manager.log_with_tag(logging.INFO, "CONVERGENCE",
f"优化在第 {self.current_iteration} 次迭代后收敛",
component_name)
break
# 保存检查点
if checkpoint_freq > 0 and self.current_iteration % checkpoint_freq == 0:
self._save_checkpoint()
# 重置连续失败计数
self.consecutive_failures = 0
except Exception as e:
self._handle_iteration_error(e)
# 检查是否应该终止
if self.consecutive_failures >= self.max_consecutive_failures:
error_msg = f"连续失败 {self.consecutive_failures} 次,终止优化"
self.log_manager.log_with_tag(logging.ERROR, "ERROR", error_msg, component_name)
raise OptimizationError(error_msg)
# 优化完成
self._finalize_optimization()
# 详细的完成信息
completion_info = {
"total_iterations": self.current_iteration,
"total_evaluations": len(self.history.results),
"best_objective_value": self.history.get_best_objective_value(),
"total_time_seconds": self.history.total_time,
"total_time_hours": self.history.total_time / 3600,
"average_iteration_time": self.history.total_time / max(self.current_iteration, 1),
"convergence_detected": self._check_convergence(),
"final_consecutive_failures": self.consecutive_failures
}
if self.is_multi_objective:
completion_info.update({
"pareto_front_size": len(self.history.pareto_front),
"pareto_coverage": len(self.history.pareto_front) / max(len(self.history.results), 1)
})
self.log_manager.log_structured(logging.INFO, "OPTIMIZATION_COMPLETE",
completion_info, component_name)
self.log_manager.log_with_tag(logging.INFO, "OPTIMIZATION",
"========== 贝叶斯优化完成 ==========",
component_name)
return self.history
except Exception as e:
self.log_manager.log_with_tag(logging.ERROR, "ERROR",
f"优化过程出现严重错误: {str(e)}",
component_name)
# 尝试保存当前状态
try:
self._save_emergency_checkpoint()
except:
pass
raise OptimizationError(f"优化失败: {str(e)}") from e
def suggest_next_parameters(self) -> Dict[str, Any]:
"""
建议下一个要评估的参数组合
Returns:
参数字典
Raises:
RuntimeError: 当无法生成有效参数建议时
"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
if not self.is_initialized:
raise RuntimeError("优化器尚未初始化,请先调用optimize()或_initialize_optimization()")
self.log_manager.log_with_tag(logging.INFO, "SUGGESTION",
"开始生成参数建议", component_name)
suggestion_start_time = time.time()
try:
# 如果还在初始采样阶段
if len(self.history.results) < self.n_initial_points:
self.log_manager.log_with_tag(logging.INFO, "SUGGESTION",
f"初始采样阶段: {len(self.history.results)}/{self.n_initial_points}",
component_name)
parameters = self._suggest_initial_parameters()
suggestion_type = "初始随机采样"
else:
# 使用采集函数建议参数
self.log_manager.log_with_tag(logging.INFO, "SUGGESTION",
"使用采集函数生成参数建议", component_name)
# 记录当前高斯过程状态
gp_status = {
"is_fitted": self.gaussian_process.is_fitted,
"n_training_samples": len(self.history.results),
"best_observed_value": self.history.get_best_objective_value()
}
self.log_manager.log_structured(logging.INFO, "GP_STATUS", gp_status, component_name)
parameters = self._suggest_acquisition_parameters()
suggestion_type = f"采集函数({self.acquisition_function.function_type})"
suggestion_time = time.time() - suggestion_start_time
# 调试参数维度
self._debug_parameter_dimensions(parameters)
# 验证参数有效性
is_valid, validation_errors = self.task_evaluator.validate_parameters(parameters)
# 详细的参数建议信息
suggestion_info = {
"suggestion_type": suggestion_type,
"suggestion_time": suggestion_time,
"parameter_count": len(parameters),
"is_valid": is_valid,
"validation_errors": validation_errors if not is_valid else None,
"similar_to_previous": self._is_too_similar_to_evaluated(parameters),
"similar_to_failed": self._is_too_similar_to_failed(parameters)
}
self.log_manager.log_structured(logging.INFO, "SUGGESTION_INFO",
suggestion_info, component_name)
# 格式化参数显示
formatted_params = {}
for key, value in parameters.items():
if isinstance(value, float):
if abs(value) < 0.001:
formatted_params[key] = f"{value:.2e}"
else:
formatted_params[key] = f"{value:.6f}"
else:
formatted_params[key] = str(value)
self.log_manager.log_structured(logging.INFO, "SUGGESTED_PARAMS",
formatted_params, component_name)
# 如果使用采集函数,记录采集函数值
if suggestion_type != "初始随机采样":
try:
feature_vector = self._parameters_to_array(parameters).reshape(1, -1)
best_value = self.history.get_best_objective_value() or 0.0
acquisition_value = self.acquisition_function.evaluate(
feature_vector, self.gaussian_process, best_value
)[0]
self.log_manager.log_structured(logging.INFO, "ACQUISITION_VALUE", {
"acquisition_function": self.acquisition_function.function_type,
"acquisition_value": acquisition_value,
"best_observed_value": best_value,
"exploration_exploitation_balance": getattr(self.acquisition_function, 'xi', 'N/A')
}, component_name)
except Exception as e:
self.log_manager.log_with_tag(logging.WARNING, "WARNING",
f"无法计算采集函数值: {e}", component_name)
self.log_manager.log_with_tag(logging.INFO, "SUGGESTION",
f"参数建议生成完成 (耗时: {suggestion_time:.4f}秒)",
component_name)
return parameters
except Exception as e:
self.log_manager.log_with_tag(logging.ERROR, "ERROR",
f"参数建议失败: {str(e)}", component_name)
# 回退到随机采样
self.log_manager.log_with_tag(logging.INFO, "FALLBACK",
"使用回退策略生成参数", component_name)
fallback_params = self._suggest_fallback_parameters()
self._debug_parameter_dimensions(fallback_params)
fallback_time = time.time() - suggestion_start_time
self.log_manager.log_structured(logging.INFO, "FALLBACK_PARAMS", {
"fallback_reason": str(e),
"fallback_time": fallback_time,
"parameters": {k: (f"{v:.6f}" if isinstance(v, float) else str(v))
for k, v in fallback_params.items()}
}, component_name)
return fallback_params
def update_model(self, parameters: Dict[str, Any], objective_value: float,
metrics: Dict[str, float], evaluation_time: float = 0.0,
objective_values: Optional[Dict[str, float]] = None):
"""
使用新的评估结果更新模型
Args:
parameters: 参数组合
objective_value: 主要目标函数值
metrics: 详细指标
evaluation_time: 评估耗时
objective_values: 多目标函数值字典
"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
self.log_manager.log_with_tag(logging.INFO, "MODEL_UPDATE",
"开始更新贝叶斯优化模型", component_name)
update_start_time = time.time()
try:
# 如果是多目标优化但没有提供多目标值,从metrics中提取
if self.is_multi_objective and objective_values is None:
objective_values = self._extract_objective_values(metrics)
self.log_manager.log_with_tag(logging.INFO, "MODEL_UPDATE",
f"从指标中提取多目标值: {objective_values}",
component_name)
# 记录更新前的状态
pre_update_state = {
"total_evaluations": len(self.history.results),
"current_best": self.history.get_best_objective_value(),
"gp_fitted": self.gaussian_process.is_fitted,
"no_improvement_count": self.no_improvement_count
}
if self.is_multi_objective:
pre_update_state["pareto_front_size"] = len(self.history.pareto_front)
self.log_manager.log_structured(logging.INFO, "PRE_UPDATE_STATE",
pre_update_state, component_name)
# 创建优化结果
result = OptimizationResult(
parameters=parameters,
objective_value=objective_value,
metrics=metrics,
iteration=self.current_iteration + 1,
timestamp=datetime.now(),
evaluation_time=evaluation_time,
objective_values=objective_values
)
# 记录新结果的详细信息
result_info = {
"iteration": result.iteration,
"objective_value": objective_value,
"evaluation_time": evaluation_time,
"parameter_count": len(parameters),
"metric_count": len(metrics)
}
if objective_values:
result_info["objective_values"] = objective_values
# 显示主要指标
main_metrics = {}
for key in ['AUROC', 'AUPRC', 'F1', 'precision', 'recall', 'loss']:
if key in metrics:
main_metrics[key] = metrics[key]
if main_metrics:
result_info["main_metrics"] = main_metrics
self.log_manager.log_structured(logging.INFO, "NEW_RESULT",
result_info, component_name)
# 添加到历史记录
self.history.add_result(result, maximize=self.maximize)
# 更新高斯过程模型
gp_update_start = time.time()
if self.is_multi_objective and self.objective_weights:
# 多目标:使用加权目标值更新模型
weighted_value = self.history.get_weighted_objective_value(result)
self.log_manager.log_structured(logging.INFO, "WEIGHTED_OBJECTIVE", {
"original_value": objective_value,
"weighted_value": weighted_value,
"weights": self.objective_weights
}, component_name)
self._update_gaussian_process(parameters, weighted_value)
else:
# 单目标:使用主要目标值更新模型
self._update_gaussian_process(parameters, objective_value)
gp_update_time = time.time() - gp_update_start
# 更新无改进计数
old_no_improvement = self.no_improvement_count
self._update_improvement_tracking(result)
# 记录更新后的状态
post_update_state = {
"total_evaluations": len(self.history.results),
"current_best": self.history.get_best_objective_value(),
"gp_fitted": self.gaussian_process.is_fitted,
"gp_update_time": gp_update_time,
"no_improvement_count": self.no_improvement_count,
"improvement_detected": self.no_improvement_count < old_no_improvement
}
if self.is_multi_objective:
post_update_state.update({
"pareto_front_size": len(self.history.pareto_front),
"is_pareto_optimal": result.is_pareto_optimal if hasattr(result, 'is_pareto_optimal') else False
})
self.log_manager.log_structured(logging.INFO, "POST_UPDATE_STATE",
post_update_state, component_name)
# 分析改进情况
if len(self.history.results) > 1:
previous_best = self.history.results[-2].objective_value
improvement = objective_value - previous_best
improvement_percent = (improvement / abs(previous_best)) * 100 if previous_best != 0 else 0
improvement_analysis = {
"previous_best": previous_best,
"current_value": objective_value,
"absolute_improvement": improvement,
"relative_improvement_percent": improvement_percent,
"is_improvement": improvement > 0 if self.maximize else improvement < 0,
"improvement_magnitude": abs(improvement)
}
self.log_manager.log_structured(logging.INFO, "IMPROVEMENT_ANALYSIS",
improvement_analysis, component_name)
if improvement_analysis["is_improvement"]:
self.log_manager.log_with_tag(logging.INFO, "SUCCESS",
f"发现改进! 提升: {improvement:+.6f} ({improvement_percent:+.2f}%)",
component_name)
total_update_time = time.time() - update_start_time
# 最终更新摘要
update_summary = {
"total_update_time": total_update_time,
"gp_update_time": gp_update_time,
"history_size": len(self.history.results),
"consecutive_failures_reset": self.consecutive_failures == 0
}
if self.is_multi_objective:
update_summary["pareto_front_size"] = len(self.history.pareto_front)
self.log_manager.log_with_tag(logging.INFO, "MODEL_UPDATE",
f"模型更新完成,帕累托前沿大小: {len(self.history.pareto_front)}",
component_name)
else:
current_best = self.history.get_best_objective_value()
update_summary["current_best_value"] = current_best
self.log_manager.log_with_tag(logging.INFO, "MODEL_UPDATE",
f"模型更新完成,当前最佳值: {current_best:.6f}",
component_name)
self.log_manager.log_structured(logging.INFO, "UPDATE_SUMMARY",
update_summary, component_name)
except Exception as e:
self.log_manager.log_with_tag(logging.ERROR, "ERROR",
f"模型更新失败: {str(e)}", component_name)
# 记录失败的详细信息
failure_info = {
"error_type": type(e).__name__,
"error_message": str(e),
"parameters": {k: (f"{v:.6f}" if isinstance(v, float) else str(v))
for k, v in parameters.items()},
"objective_value": objective_value,
"metrics_count": len(metrics)
}
self.log_manager.log_structured(logging.ERROR, "UPDATE_FAILURE",
failure_info, component_name)
raise
def _extract_objective_values(self, metrics: Dict[str, float]) -> Dict[str, float]:
"""从metrics中提取多目标函数值"""
objective_values = {}
for obj_name in self.objectives:
if obj_name in metrics:
objective_values[obj_name] = metrics[obj_name]
elif obj_name == 'primary':
# 默认使用AUROC作为主要目标
objective_values[obj_name] = metrics.get('AUROC', 0.0)
else:
# 尝试映射常见的目标名称
mapping = {
'auroc': 'AUROC',
'auprc': 'AUPRC',
'f1': 'F1',
'precision': 'precision',
'recall': 'recall'
}
mapped_name = mapping.get(obj_name.lower(), obj_name)
objective_values[obj_name] = metrics.get(mapped_name, 0.0)
return objective_values
def get_best_parameters(self) -> Tuple[Optional[Dict[str, Any]], Optional[float]]:
"""
获取当前最佳参数组合和目标值
Returns:
(best_parameters, best_objective_value): 最佳参数和目标值
"""
if self.history.best_result:
return self.history.best_result.parameters, self.history.best_result.objective_value
else:
return None, None
def get_pareto_front(self) -> List[OptimizationResult]:
"""
获取帕累托前沿(多目标优化)
Returns:
帕累托最优解列表
"""
if not self.is_multi_objective:
return [self.history.best_result] if self.history.best_result else []
return self.history.pareto_front.copy()
def set_objective_weights(self, weights: Dict[str, float]):
"""
设置目标权重(用于加权求和)
Args:
weights: 目标权重字典,键为目标名称,值为权重
"""
if not self.is_multi_objective:
self.logger.warning("单目标优化不需要设置权重")
return
# 验证权重
total_weight = sum(weights.values())
if total_weight <= 0:
raise ValueError("权重总和必须大于0")
# 归一化权重
normalized_weights = {k: v / total_weight for k, v in weights.items()}
self.objective_weights = normalized_weights
self.history.objective_weights = normalized_weights
self.logger.info(f"目标权重已更新: {normalized_weights}")
def compute_hypervolume(self, reference_point: Optional[Dict[str, float]] = None) -> float:
"""
计算帕累托前沿的超体积指标
Args:
reference_point: 参考点,如果未提供则自动计算
Returns:
超体积值
"""
if not self.is_multi_objective or not self.history.pareto_front:
return 0.0
try:
import numpy as np
# 获取帕累托前沿的目标值矩阵
front_matrix = []
for result in self.history.pareto_front:
obj_vector = result.get_objective_vector(self.objectives)
# 对于最小化目标,取负值
for i, obj_name in enumerate(self.objectives):
if not self.maximize_objectives.get(obj_name, True):
obj_vector[i] = -obj_vector[i]
front_matrix.append(obj_vector)
front_matrix = np.array(front_matrix)
# 计算参考点
if reference_point is None:
ref_point = []
for i, obj_name in enumerate(self.objectives):
min_val = np.min(front_matrix[:, i])
ref_point.append(min_val - 0.1 * abs(min_val))
reference_point = ref_point
else:
ref_point = [reference_point.get(obj, 0.0) for obj in self.objectives]
# 简化的超体积计算(适用于2-3个目标)
if len(self.objectives) == 2:
return self._compute_hypervolume_2d(front_matrix, ref_point)
elif len(self.objectives) == 3:
return self._compute_hypervolume_3d(front_matrix, ref_point)
else:
self.logger.warning("超体积计算仅支持2-3个目标")
return 0.0
except Exception as e:
self.logger.error(f"超体积计算失败: {e}")
return 0.0
def _compute_hypervolume_2d(self, front: np.ndarray, ref_point: List[float]) -> float:
"""计算2D超体积"""
if len(front) == 0:
return 0.0
# 按第一个目标排序
sorted_front = front[np.argsort(front[:, 0])]
hypervolume = 0.0
prev_x = ref_point[0]
for point in sorted_front:
x, y = point[0], point[1]
if x > prev_x and y > ref_point[1]:
hypervolume += (x - prev_x) * (y - ref_point[1])
prev_x = x
return hypervolume
def _compute_hypervolume_3d(self, front: np.ndarray, ref_point: List[float]) -> float:
"""计算3D超体积(简化版本)"""
if len(front) == 0:
return 0.0
# 简化计算:使用包围盒近似
max_vals = np.max(front, axis=0)
volume = 1.0
for i in range(3):
if max_vals[i] > ref_point[i]:
volume *= (max_vals[i] - ref_point[i])
else:
return 0.0
return volume * len(front) / 10.0 # 近似修正因子
def get_optimization_status(self) -> Dict[str, Any]:
"""
获取优化状态信息
Returns:
包含优化状态的字典
"""
status = {
'is_initialized': self.is_initialized,
'current_iteration': self.current_iteration,
'total_evaluations': len(self.history.results),
'best_objective_value': self.history.get_best_objective_value(),
'total_time': self.history.total_time,
'consecutive_failures': self.consecutive_failures,
'no_improvement_count': self.no_improvement_count,
'convergence_detected': self._check_convergence() if len(self.history.results) > self.convergence_window else False,
'is_multi_objective': self.is_multi_objective,
'objectives': self.objectives
}
if self.start_time:
status['elapsed_time'] = (datetime.now() - self.start_time).total_seconds()
if self.history.best_result:
status['best_parameters'] = self.history.best_result.parameters
status['best_metrics'] = self.history.best_result.metrics
# 多目标优化状态
if self.is_multi_objective:
status['pareto_front_size'] = len(self.history.pareto_front)
status['objective_weights'] = self.objective_weights
status['pareto_metrics'] = self.history.get_pareto_front_metrics()
if self.history.pareto_front:
# 添加帕累托前沿的代表性解
status['pareto_solutions'] = []
for result in self.history.pareto_front[:5]: # 最多显示5个解
status['pareto_solutions'].append({
'parameters': result.parameters,
'objective_values': result.objective_values,
'iteration': result.iteration
})
return status
def _initialize_optimization(self):
"""初始化优化过程"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
self.log_manager.log_with_tag(logging.INFO, "INIT",
"========== 初始化贝叶斯优化过程 ==========",
component_name)
# 设置随机种子
if self.random_state is not None:
np.random.seed(self.random_state)
self.log_manager.log_with_tag(logging.INFO, "INIT",
f"设置随机种子: {self.random_state}",
component_name)
# 重置状态
self.current_iteration = 0
self.start_time = datetime.now()
self.history.start_time = self.start_time
self.consecutive_failures = 0
self.no_improvement_count = 0
self.failed_parameters.clear()
# 记录初始化状态
init_state = {
"start_time": self.start_time.isoformat(),
"current_iteration": self.current_iteration,
"consecutive_failures": self.consecutive_failures,
"no_improvement_count": self.no_improvement_count,
"failed_parameters_count": len(self.failed_parameters),
"history_results_count": len(self.history.results)
}
self.log_manager.log_structured(logging.INFO, "INIT_STATE", init_state, component_name)
# 验证组件状态
component_status = {
"parameter_space_valid": self.parameter_space is not None,
"task_evaluator_valid": self.task_evaluator is not None,
"acquisition_function_valid": self.acquisition_function is not None,
"gaussian_process_valid": self.gaussian_process is not None,
"state_manager_valid": self.state_manager is not None
}
self.log_manager.log_structured(logging.INFO, "COMPONENT_STATUS",
component_status, component_name)
# 检查组件完整性
missing_components = [name for name, valid in component_status.items() if not valid]
if missing_components:
error_msg = f"缺少必要组件: {missing_components}"
self.log_manager.log_with_tag(logging.ERROR, "ERROR", error_msg, component_name)
raise RuntimeError(error_msg)
# 标记为已初始化
self.is_initialized = True
self.log_manager.log_with_tag(logging.INFO, "INIT",
"贝叶斯优化过程初始化完成", component_name)
def _run_single_iteration(self):
"""执行单次优化迭代"""
component_name = f"BayesianOptimizer_{self.task_evaluator.task_type}"
iteration_start = time.time()
self.log_manager.log_with_tag(logging.INFO, "ITERATION",
f"========== 第 {self.current_iteration + 1} 次迭代开始 ==========",
component_name)
# 建议下一个参数组合
suggestion_start = time.time()
parameters = self.suggest_next_parameters()
suggestion_time = time.time() - suggestion_start
self.log_manager.log_structured(logging.INFO, "ITERATION_PARAMS", {
"iteration": self.current_iteration + 1,
"suggestion_time": suggestion_time,
"parameter_count": len(parameters)
}, component_name)
# 格式化参数显示
formatted_params = []
for key, value in parameters.items():
if isinstance(value, float):
if abs(value) < 0.001:
formatted_params.append(f"{key}={value:.2e}")
else:
formatted_params.append(f"{key}={value:.6f}")
else:
formatted_params.append(f"{key}={value}")
param_str = ", ".join(formatted_params)
self.log_manager.log_with_tag(logging.INFO, "ITERATION",
f"评估参数: {param_str}", component_name)
# 评估参数
self.log_manager.log_with_tag(logging.INFO, "EVALUATION",
"开始参数评估...", component_name)
evaluation_start = time.time()
metrics = self.task_evaluator.evaluate_parameters(parameters)
evaluation_time = time.time() - evaluation_start
# 提取目标值
objective_value = self.task_evaluator.get_objective_value(metrics)
# 记录评估结果
evaluation_info = {
"evaluation_time": evaluation_time,
"objective_value": objective_value,
"metrics_count": len(metrics)
}
# 添加主要指标
main_metrics = {}