tf_lstm_train.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @FileName :tf_lstm_train.py
  4. # @Time :2025/2/13 10:52
  5. # @Author :David
  6. # @Company: shenyang JY
  7. import json, os
  8. import numpy as np
  9. import traceback
  10. import logging
  11. from app.common.logs import params
  12. from app.common.data_handler import DataHandler, write_number_to_file
  13. import time
  14. from app.common.tf_lstm import TSHandler
  15. from app.common.dbmg import MongoUtils
  16. from app.common.logs import logger
  17. np.random.seed(42) # NumPy随机种子
  18. # tf.set_random_seed(42) # TensorFlow随机种子
  19. dh = DataHandler(logger, params)
  20. ts = TSHandler(logger, params)
  21. mgUtils = MongoUtils(logger)
  22. def model_training(train_data, input_file, cap):
  23. # 获取程序开始时间
  24. start_time = time.time()
  25. success = 0
  26. logger.info("Program starts execution!")
  27. farm_id = input_file.split('/')[-2]
  28. output_file = input_file.replace('IN', 'OUT')
  29. status_file = 'STATUS.TXT'
  30. try:
  31. # ------------ 获取数据,预处理训练数据 ------------
  32. dh.opt.cap = cap
  33. train_x, valid_x, train_y, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = dh.train_data_handler(train_data)
  34. ts.opt.cap = round(scaled_cap, 2)
  35. ts.opt.Model['input_size'] = train_x.shape[2]
  36. # ------------ 训练模型,保存模型 ------------
  37. # 1. 如果是加强训练模式,先加载预训练模型特征参数,再预处理训练数据
  38. # 2. 如果是普通模式,先预处理训练数据,再根据训练数据特征加载模型
  39. model = ts.train_init() if ts.opt.Model['add_train'] else ts.get_keras_model(ts.opt)
  40. if ts.opt.Model['add_train']:
  41. if model:
  42. feas = json.loads(ts.model_params).get('features', dh.opt.features)
  43. if set(feas).issubset(set(dh.opt.features)):
  44. dh.opt.features = list(feas)
  45. train_x, train_y, valid_x, valid_y, scaled_train_bytes, scaled_target_bytes, scaled_cap = dh.train_data_handler(train_data)
  46. else:
  47. model = ts.get_keras_model(ts.opt)
  48. logger.info("训练数据特征,不满足,加强训练模型特征")
  49. else:
  50. model = ts.get_keras_model(ts.opt)
  51. ts_model = ts.training(model, [train_x, valid_x, train_y, valid_y])
  52. success = 1
  53. # 更新算法状态:1. 启动成功
  54. write_number_to_file(os.path.join(output_file, status_file), 1, 1, 'rewrite')
  55. # ------------ 组装模型数据 ------------
  56. params['Model']['features'] = ','.join(dh.opt.features)
  57. params.update({
  58. 'params': json.dumps(params),
  59. 'descr': f'南网竞赛-{farm_id}',
  60. 'gen_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
  61. 'model_table': params['model_table'] + farm_id,
  62. 'scaler_table': params['scaler_table'] + farm_id
  63. })
  64. mgUtils.insert_trained_model_into_mongo(ts_model, params)
  65. mgUtils.insert_scaler_model_into_mongo(scaled_train_bytes, scaled_target_bytes, params)
  66. # 更新算法状态:正常结束
  67. write_number_to_file(os.path.join(output_file, status_file), 2, 2)
  68. except Exception as e:
  69. # 如果算法状态没启动,不更新
  70. if success:
  71. write_number_to_file(os.path.join(output_file, status_file), 2, 3)
  72. my_exception = traceback.format_exc()
  73. my_exception.replace("\n", "\t")
  74. end_time = time.time()
  75. logger.info("lstm训练任务:用了 %s 秒 " % (end_time-start_time))
  76. if __name__ == "__main__":
  77. print("Program starts execution!")
  78. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  79. logger = logging.getLogger("model_training_bp log")
  80. from waitress import serve
  81. serve(app, host="0.0.0.0", port=10103, threads=4)
  82. print("server start!")
  83. # args_dict = {"mongodb_database": 'realtimeDq', 'scaler_table': 'j00600_scaler', 'model_name': 'lstm1',
  84. # 'model_table': 'j00600_model', 'mongodb_read_table': 'j00600', 'col_time': 'dateTime',
  85. # 'features': 'speed10,direction10,speed30,direction30,speed50,direction50,speed70,direction70,speed90,direction90,speed110,direction110,speed150,direction150,speed170,direction170'}
  86. # args_dict['features'] = args_dict['features'].split(',')
  87. # args.update(args_dict)
  88. # dh = DataHandler(logger, args)
  89. # ts = TSHandler(logger, args)
  90. # opt = argparse.Namespace(**args)
  91. # opt.Model['input_size'] = len(opt.features)
  92. # train_data = get_data_from_mongo(args_dict)
  93. # train_x, train_y, valid_x, valid_y, scaled_train_bytes, scaled_target_bytes = dh.train_data_handler(train_data)
  94. # ts_model = ts.training([train_x, train_y, valid_x, valid_y])
  95. #
  96. # args_dict['gen_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  97. # args_dict['params'] = args
  98. # args_dict['descr'] = '测试'
  99. # insert_trained_model_into_mongo(ts_model, args_dict)
  100. # insert_scaler_model_into_mongo(scaled_train_bytes, scaled_target_bytes, args_dict)