tf_model_train.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @FileName :tf_model_train.py
  4. # @Time :2025/4/29 14:05
  5. # @Author :David
  6. # @Company: shenyang JY
  7. import logging
  8. import os, json
  9. import time
  10. import traceback
  11. import pandas as pd
  12. from typing import Dict, Any
  13. from app.common.tf_lstm import TSHandler
  14. from app.common.dbmg import MongoUtils
  15. from app.common.data_handler import DataHandler, write_number_to_file
  16. from app.common.config import logger, parser
  17. class ModelTrainer:
  18. """模型训练器封装类"""
  19. def __init__(self,
  20. input_file,
  21. args,
  22. train_data: pd.DataFrame,
  23. capacity: float,
  24. gpu_id: int = None,
  25. config: Dict[str, Any] = None
  26. ):
  27. self.train_data = train_data
  28. self.capacity = capacity
  29. self.gpu_id = gpu_id
  30. self.config = config or {}
  31. self._setup_resources()
  32. # 初始化组件
  33. self.input_file = input_file
  34. self.args = parser.parse_args_and_yaml() # 从原始配置导入
  35. self.dh = DataHandler(logger, parser)
  36. self.ts = TSHandler(logger, parser)
  37. self.mgUtils = MongoUtils(logger)
  38. def _setup_resources(self):
  39. """GPU资源分配"""
  40. if self.gpu_id is not None:
  41. os.environ["CUDA_VISIBLE_DEVICES"] = str(self.gpu_id)
  42. self.logger.info(f"GPU {self.gpu_id} allocated")
  43. def train(self):
  44. """执行训练流程"""
  45. # 获取程序开始时间
  46. start_time = time.time()
  47. success = 0
  48. farm_id = self.input_file.split('/')[-2]
  49. output_file = self.input_file.replace('IN', 'OUT')
  50. status_file = 'STATUS.TXT'
  51. try:
  52. # ------------ 获取数据,预处理训练数据 ------------
  53. self.dh.opt.cap = self.capacity
  54. train_x, valid_x, train_y, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = self.dh.train_data_handler(self.train_data)
  55. self.ts.opt.Model['input_size'] = train_x.shape[2]
  56. # ------------ 训练模型,保存模型 ------------
  57. # 1. 如果是加强训练模式,先加载预训练模型特征参数,再预处理训练数据
  58. # 2. 如果是普通模式,先预处理训练数据,再根据训练数据特征加载模型
  59. model = self.ts.train_init() if self.ts.opt.Model['add_train'] else self.ts.get_keras_model(self.ts.opt)
  60. if self.ts.opt.Model['add_train']:
  61. if model:
  62. feas = json.loads(self.ts.model_params).get('features', self.dh.opt.features)
  63. if set(feas).issubset(set(self.dh.opt.features)):
  64. self.dh.opt.features = list(feas)
  65. train_x, train_y, valid_x, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = self.dh.train_data_handler(train_data)
  66. else:
  67. model = self.ts.get_keras_model(self.ts.opt)
  68. self.logger.info("训练数据特征,不满足,加强训练模型特征")
  69. else:
  70. model = self.ts.get_keras_model(self.ts.opt)
  71. # 执行训练
  72. trained_model = self.ts.training(model, [train_x, valid_x, train_y, valid_y])
  73. # 模型持久化
  74. success = 1
  75. # 更新算法状态:1. 启动成功
  76. write_number_to_file(os.path.join(output_file, status_file), 1, 1, 'rewrite')
  77. # ------------ 组装模型数据 ------------
  78. self.opt.Model['features'] = ','.join(self.dh.opt.features)
  79. self.args.update({
  80. 'params': json.dumps(local_params),
  81. 'descr': f'南网竞赛-{farm_id}',
  82. 'gen_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
  83. 'model_table': local_params['model_table'] + farm_id,
  84. 'scaler_table': local_params['scaler_table'] + farm_id
  85. })
  86. mgUtils.insert_trained_model_into_mongo(trained_model, local_params)
  87. mgUtils.insert_scaler_model_into_mongo(scaled_train_bytes, scaled_target_bytes, local_params)
  88. # 更新算法状态:正常结束
  89. write_number_to_file(os.path.join(output_file, status_file), 2, 2)
  90. return True
  91. except Exception as e:
  92. self._handle_error(e)
  93. return False
  94. def _initialize_model(self):
  95. """模型初始化策略"""
  96. if self.ts.opt.Model['add_train']:
  97. pretrained = self.ts.train_init()
  98. return pretrained if self._check_feature_compatibility(pretrained) else self.ts.get_keras_model()
  99. return self.ts.get_keras_model()
  100. def _check_feature_compatibility(self, model) -> bool:
  101. """检查特征兼容性"""
  102. # 原始逻辑中的特征校验实现
  103. pass
  104. def _handle_error(self, error: Exception):
  105. """统一错误处理"""
  106. error_msg = traceback.format_exc()
  107. self.logger.error(f"Training failed: {str(error)}\n{error_msg}")
  108. # 使用示例
  109. if __name__ == "__main__":
  110. config = {
  111. 'base_path': '/data/power_forecast',
  112. 'capacities': {
  113. '1001': 2.5,
  114. '1002': 3.0,
  115. # ... 其他场站配置
  116. },
  117. 'gpu_assignment': [0, 1, 2, 3] # 可用GPU列表
  118. }
  119. orchestrator = TrainingOrchestrator(
  120. station_ids=['1001', '1002', '1003'], # 实际场景下生成数百个ID
  121. config=config,
  122. max_workers=4 # 根据GPU数量设置
  123. )
  124. orchestrator.execute()