tf_model_train.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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, argparse
  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. train_data: pd.DataFrame,
  21. capacity: float,
  22. config: Dict[str, Any] = None,
  23. ):
  24. self.config = config
  25. self.logger = logger
  26. self.train_data = train_data
  27. self.capacity = capacity
  28. self.gpu_id = config.get('gpu_assignment')
  29. self._setup_resources()
  30. # 初始化组件
  31. self.input_file = config.get("input_file")
  32. self.opt = argparse.Namespace(**config)
  33. self.dh = DataHandler(logger, self.opt)
  34. self.ts = TSHandler(logger, self.opt)
  35. self.mgUtils = MongoUtils(logger)
  36. def _setup_resources(self):
  37. """GPU资源分配"""
  38. if self.gpu_id is not None:
  39. os.environ["CUDA_VISIBLE_DEVICES"] = str(self.gpu_id)
  40. self.logger.info(f"GPU {self.gpu_id} allocated")
  41. def train(self, pre_area=False):
  42. """执行训练流程"""
  43. # 获取程序开始时间
  44. start_time = time.time()
  45. success = 0
  46. print("aaa")
  47. # 预测编号:场站级,场站id,区域级,区域id
  48. pre_id = self.config['area_id'] if pre_area else self.config['station_id']
  49. pre_type = 'a' if pre_area else 's'
  50. output_file = os.path.join(self.opt.dqyc_base_path, self.input_file)
  51. output_file = output_file.replace('IN', 'OUT')
  52. status_file = 'STATUS.TXT'
  53. try:
  54. # ------------ 获取数据,预处理训练数据 ------------
  55. self.dh.opt.cap = self.capacity
  56. train_x, valid_x, train_y, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = self.dh.train_data_handler(self.train_data)
  57. self.ts.opt.Model['input_size'] = train_x.shape[2]
  58. # ------------ 训练模型,保存模型 ------------
  59. # 1. 如果是加强训练模式,先加载预训练模型特征参数,再预处理训练数据
  60. # 2. 如果是普通模式,先预处理训练数据,再根据训练数据特征加载模型
  61. print("bbb")
  62. model = self.ts.train_init() if self.ts.opt.Model['add_train'] else self.ts.get_keras_model(self.ts.opt)
  63. if self.ts.opt.Model['add_train']:
  64. if model:
  65. feas = json.loads(self.ts.model_params).get('features', self.dh.opt.features)
  66. if set(feas).issubset(set(self.dh.opt.features)):
  67. self.dh.opt.features = list(feas)
  68. train_x, train_y, valid_x, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = self.dh.train_data_handler(self.train_data)
  69. else:
  70. model = self.ts.get_keras_model(self.ts.opt)
  71. self.logger.info("训练数据特征,不满足,加强训练模型特征")
  72. else:
  73. model = self.ts.get_keras_model(self.ts.opt)
  74. print("ccc")
  75. # 执行训练
  76. trained_model = self.ts.training(model, [train_x, valid_x, train_y, valid_y])
  77. # 模型持久化
  78. success = 1
  79. print('ddd')
  80. # 更新算法状态:1. 启动成功
  81. write_number_to_file(os.path.join(str(output_file), status_file), 1, 1, 'rewrite')
  82. # ------------ 组装模型数据 ------------
  83. self.opt.Model['features'] = ','.join(self.dh.opt.features)
  84. self.config.update({
  85. 'params': json.dumps({'Model': self.config['Model']}),
  86. 'descr': f'南网竞赛-{pre_id}',
  87. 'gen_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
  88. 'model_table': self.config['model_table'] + f'_{pre_type}_' + str(pre_id),
  89. 'scaler_table': self.config['scaler_table'] + f'_{pre_type}_'+ str(pre_id)
  90. })
  91. self.mgUtils.insert_trained_model_into_mongo(trained_model, self.config)
  92. self.mgUtils.insert_scaler_model_into_mongo(scaled_train_bytes, scaled_target_bytes, self.config)
  93. # 更新算法状态:正常结束
  94. print("eee")
  95. write_number_to_file(os.path.join(str(output_file), status_file), 2, 2)
  96. return True
  97. except Exception as e:
  98. self._handle_error(e)
  99. return False
  100. def _handle_error(self, error: Exception):
  101. """统一错误处理"""
  102. error_msg = traceback.format_exc()
  103. self.logger.error(f"Training failed: {str(error)}\n{error_msg}")
  104. # 使用示例
  105. if __name__ == "__main__":
  106. config = {
  107. 'base_path': '/data/power_forecast',
  108. 'capacities': {
  109. '1001': 2.5,
  110. '1002': 3.0,
  111. # ... 其他场站配置
  112. },
  113. 'gpu_assignment': [0, 1, 2, 3] # 可用GPU列表
  114. }
  115. orchestrator = TrainingOrchestrator(
  116. station_ids=['1001', '1002', '1003'], # 实际场景下生成数百个ID
  117. config=config,
  118. max_workers=4 # 根据GPU数量设置
  119. )
  120. orchestrator.execute()