model_training_lstm.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import pandas as pd
  2. import numpy as np
  3. from pymongo import MongoClient
  4. from sklearn.model_selection import train_test_split
  5. from flask import Flask,request
  6. import time
  7. import traceback
  8. import logging
  9. from sklearn.preprocessing import MinMaxScaler
  10. from io import BytesIO
  11. import joblib
  12. from tensorflow.keras.models import Sequential
  13. from tensorflow.keras.layers import LSTM, Dense
  14. from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
  15. # import matplotlib.pyplot as plt
  16. import tensorflow as tf
  17. from common.database_dml import get_data_from_mongo,insert_h5_model_into_mongo
  18. app = Flask('model_training_lightgbm——service')
  19. # def draw_loss(history):
  20. # #绘制训练集和验证集损失
  21. # plt.figure(figsize=(20, 8))
  22. # plt.plot(history.history['loss'], label='Training Loss')
  23. # plt.plot(history.history['val_loss'], label='Validation Loss')
  24. # plt.title('Loss Curve')
  25. # plt.xlabel('Epochs')
  26. # plt.ylabel('Loss')
  27. # plt.legend()
  28. # plt.show()
  29. def rmse(y_true, y_pred):
  30. return tf.math.sqrt(tf.reduce_mean(tf.square(y_true - y_pred)))
  31. # 创建时间序列数据
  32. def create_sequences(data_features,data_target,time_steps):
  33. X, y = [], []
  34. if len(data_features)<time_steps:
  35. print("数据长度不能比时间步长小!")
  36. return np.array(X), np.array(y)
  37. else:
  38. for i in range(len(data_features) - time_steps+1):
  39. X.append(data_features[i:(i + time_steps)])
  40. if len(data_target)>0:
  41. y.append(data_target[i + time_steps -1])
  42. return np.array(X), np.array(y)
  43. def build_model(data, args):
  44. col_time, time_steps,features,target = args['col_time'], int(args['time_steps']), str_to_list(args['features']),args['target']
  45. if 'is_limit' in data.columns:
  46. data = data[data['is_limit']==False]
  47. train_data = data.fillna(method='ffill').fillna(method='bfill').sort_values(by=col_time)
  48. # X_train, X_test, y_train, y_test = process_data(df_clean, params)
  49. # 创建特征和目标的标准化器
  50. feature_scaler = MinMaxScaler(feature_range=(0, 1))
  51. target_scaler = MinMaxScaler(feature_range=(0, 1))
  52. # 标准化特征和目标
  53. scaled_features = feature_scaler.fit_transform(train_data[features])
  54. scaled_target = target_scaler.fit_transform(train_data[[target]])
  55. # 保存两个scaler
  56. feature_scaler_bytes = BytesIO()
  57. joblib.dump(feature_scaler, feature_scaler_bytes)
  58. feature_scaler_bytes.seek(0) # Reset pointer to the beginning of the byte stream
  59. target_scaler_bytes = BytesIO()
  60. joblib.dump(target_scaler, target_scaler_bytes)
  61. target_scaler_bytes.seek(0)
  62. X, y = create_sequences(scaled_features, scaled_target, time_steps)
  63. # 划分训练集和测试集
  64. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=43)
  65. # 构建 LSTM 模型
  66. model = Sequential()
  67. model.add(LSTM(units=50, return_sequences=False, input_shape=(time_steps, X_train.shape[2])))
  68. model.add(Dense(1)) # 输出单一值
  69. # 编译模型
  70. model.compile(optimizer='adam', loss='mean_squared_error')
  71. # 定义 EarlyStopping 和 ReduceLROnPlateau 回调
  72. early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True, verbose=1)
  73. reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1)
  74. # 训练模型
  75. history = model.fit(X_train, y_train,
  76. epochs=100,
  77. batch_size=32,
  78. validation_data=(X_test, y_test),
  79. verbose=2,
  80. callbacks=[early_stopping, reduce_lr])
  81. # draw_loss(history)
  82. return model,feature_scaler_bytes,target_scaler_bytes
  83. def str_to_list(arg):
  84. if arg == '':
  85. return []
  86. else:
  87. return arg.split(',')
  88. @app.route('/model_training_lstm', methods=['POST'])
  89. def model_training_lstm():
  90. # 获取程序开始时间
  91. start_time = time.time()
  92. result = {}
  93. success = 0
  94. print("Program starts execution!")
  95. try:
  96. args = request.values.to_dict()
  97. print('args',args)
  98. logger.info(args)
  99. power_df = get_data_from_mongo(args)
  100. model,feature_scaler_bytes,target_scaler_bytes = build_model(power_df,args)
  101. insert_h5_model_into_mongo(model,feature_scaler_bytes,target_scaler_bytes ,args)
  102. success = 1
  103. except Exception as e:
  104. my_exception = traceback.format_exc()
  105. my_exception.replace("\n","\t")
  106. result['msg'] = my_exception
  107. end_time = time.time()
  108. result['success'] = success
  109. result['args'] = args
  110. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  111. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  112. print("Program execution ends!")
  113. return result
  114. if __name__=="__main__":
  115. print("Program starts execution!")
  116. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  117. logger = logging.getLogger("model_training_lightgbm log")
  118. from waitress import serve
  119. serve(app, host="0.0.0.0", port=10096)
  120. print("server start!")