tf_lstm_zone.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # @FileName :tf_lstm.py
  4. # @Time :2025/2/12 14:03
  5. # @Author :David
  6. # @Company: shenyang JY
  7. from tensorflow.keras.layers import Input, Dense, LSTM, concatenate, Conv1D, Conv2D, MaxPooling1D, Reshape, Flatten, Add, Multiply, Concatenate
  8. from tensorflow.keras.models import Model, load_model
  9. from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, ReduceLROnPlateau
  10. from tensorflow.keras import optimizers, regularizers
  11. from models_processing.model_tf.losses import region_loss
  12. import numpy as np
  13. from common.database_dml_koi import *
  14. from models_processing.model_tf.settings import set_deterministic
  15. from threading import Lock
  16. import argparse
  17. model_lock = Lock()
  18. set_deterministic(42)
  19. class TSHandler(object):
  20. def __init__(self, logger, args):
  21. self.logger = logger
  22. self.opt = argparse.Namespace(**args)
  23. self.model = None
  24. self.model_params = None
  25. def get_model(self, args):
  26. """
  27. 单例模式+线程锁,防止在异步加载时引发线程安全
  28. """
  29. try:
  30. with model_lock:
  31. loss = region_loss(self.opt)
  32. self.model, self.model_params = get_keras_model_from_mongo(args, {type(loss).__name__: loss})
  33. except Exception as e:
  34. self.logger.info("加载模型权重失败:{}".format(e.args))
  35. @staticmethod
  36. def get_keras_model_20250515(opt, time_series=1, lstm_type=1):
  37. loss = region_loss(opt)
  38. l1_reg = regularizers.l1(opt.Model['lambda_value_1'])
  39. l2_reg = regularizers.l2(opt.Model['lambda_value_2'])
  40. nwp_input = Input(shape=(opt.Model['time_step']*time_series, opt.Model['input_size']), name='nwp')
  41. con1 = Conv1D(filters=64, kernel_size=1, strides=1, padding='valid', activation='relu', kernel_regularizer=l2_reg)(nwp_input)
  42. con1_p = MaxPooling1D(pool_size=1, strides=1, padding='valid', data_format='channels_last')(con1)
  43. nwp_lstm = LSTM(units=opt.Model['hidden_size'], return_sequences=True, kernel_regularizer=l2_reg)(con1_p)
  44. zone = Dense(len(opt.zone), name='zone')(nwp_lstm)
  45. zonef = Flatten()(zone)
  46. if lstm_type == 2:
  47. output = Dense(opt.Model['time_step'], name='cdq_output')(zonef)
  48. else:
  49. output = Dense(opt.Model['time_step']*time_series, name='cdq_output')(zonef)
  50. model = Model(nwp_input, [zone, output])
  51. adam = optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, amsgrad=True)
  52. model.compile(loss={"zone": loss, "cdq_output": loss}, loss_weights={"zone": 0.5, "cdq_output": 0.5}, optimizer=adam)
  53. return model
  54. @staticmethod
  55. def get_keras_model(opt, time_series=1, lstm_type=1):
  56. loss = region_loss(opt)
  57. l1_reg = regularizers.l1(opt.Model['lambda_value_1'])
  58. l2_reg = regularizers.l2(opt.Model['lambda_value_2'])
  59. nwp_input = Input(shape=(opt.Model['time_step'] * time_series, opt.Model['input_size']), name='nwp')
  60. con1 = Conv1D(filters=64, kernel_size=1, strides=1, padding='valid', activation='relu',
  61. kernel_regularizer=l2_reg)(nwp_input)
  62. con1_p = MaxPooling1D(pool_size=1, strides=1, padding='valid', data_format='channels_last')(con1)
  63. nwp_lstm = LSTM(units=opt.Model['hidden_size'], return_sequences=True, kernel_regularizer=l2_reg)(con1_p)
  64. # 分区A/B独立特征提取
  65. zone_a = LSTM(units=32, return_sequences=True, kernel_regularizer=l2_reg)(nwp_lstm) # 独立LSTM分支
  66. zone_b = LSTM(units=32, return_sequences=True, kernel_regularizer=l2_reg)(nwp_lstm)
  67. # 动态权重门控
  68. gate = Dense(2, activation='softmax')(nwp_lstm) # 自动学习分区重要性
  69. weighted_zone = Add()([
  70. Multiply()([gate[:, :, 0:1], zone_a]),
  71. Multiply()([gate[:, :, 1:2], zone_b])
  72. ])
  73. zone_pred = Dense(len(opt.zone), name='zone')(weighted_zone)
  74. zone_flat = Flatten()(zone_pred)
  75. # 在zone_flat后添加交叉层
  76. cross_input = Concatenate()([zone_flat, nwp_lstm[:, -1, :]]) # 融合分区特征和LSTM最后时刻状态
  77. cross_layer = Dense(64, activation='relu')(cross_input)
  78. # 最终输出层
  79. if lstm_type == 2:
  80. output = Dense(opt.Model['time_step'], name='cdq_output')(cross_layer)
  81. else:
  82. output = Dense(opt.Model['time_step'] * time_series, name='cdq_output')(cross_layer)
  83. model = Model(nwp_input, [zone_pred, output])
  84. adam = optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, amsgrad=True)
  85. model.compile(loss={"zone": loss, "cdq_output": loss}, loss_weights={"zone": 0.7, "cdq_output": 0.3},
  86. optimizer=adam)
  87. return model
  88. def train_init(self):
  89. try:
  90. # 进行加强训练,支持修模
  91. loss = region_loss(self.opt)
  92. base_train_model, self.model_params = get_keras_model_from_mongo(vars(self.opt), {type(loss).__name__: loss})
  93. base_train_model.summary()
  94. self.logger.info("已加载加强训练基础模型")
  95. return base_train_model
  96. except Exception as e:
  97. self.logger.info("加载加强训练模型权重失败:{}".format(e.args))
  98. return False
  99. def training(self, model, train_and_valid_data):
  100. model.summary()
  101. train_x, train_y, valid_x, valid_y = train_and_valid_data
  102. early_stop = EarlyStopping(monitor='val_loss', patience=self.opt.Model['patience'], mode='auto')
  103. history = model.fit(train_x, train_y, batch_size=self.opt.Model['batch_size'], epochs=self.opt.Model['epoch'],
  104. verbose=2, validation_data=(valid_x, valid_y), callbacks=[early_stop], shuffle=False)
  105. loss = np.round(history.history['loss'], decimals=5)
  106. val_loss = np.round(history.history['val_loss'], decimals=5)
  107. self.logger.info("-----模型训练经过{}轮迭代-----".format(len(loss)))
  108. self.logger.info("训练集损失函数为:{}".format(loss))
  109. self.logger.info("验证集损失函数为:{}".format(val_loss))
  110. return model
  111. def predict(self, test_x, batch_size=1):
  112. result = self.model.predict(test_x, batch_size=batch_size)
  113. self.logger.info("执行预测方法")
  114. return result
  115. if __name__ == "__main__":
  116. run_code = 0