model_training_lstm.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. train_data = data.fillna(method='ffill').fillna(method='bfill').sort_values(by=col_time)
  46. # X_train, X_test, y_train, y_test = process_data(df_clean, params)
  47. # 创建特征和目标的标准化器
  48. feature_scaler = MinMaxScaler(feature_range=(0, 1))
  49. target_scaler = MinMaxScaler(feature_range=(0, 1))
  50. # 标准化特征和目标
  51. scaled_features = feature_scaler.fit_transform(train_data[features])
  52. scaled_target = target_scaler.fit_transform(train_data[[target]])
  53. # 保存两个scaler
  54. feature_scaler_bytes = BytesIO()
  55. joblib.dump(feature_scaler, feature_scaler_bytes)
  56. feature_scaler_bytes.seek(0) # Reset pointer to the beginning of the byte stream
  57. target_scaler_bytes = BytesIO()
  58. joblib.dump(target_scaler, target_scaler_bytes)
  59. target_scaler_bytes.seek(0)
  60. X, y = create_sequences(scaled_features, scaled_target, time_steps)
  61. # 划分训练集和测试集
  62. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=43)
  63. # 构建 LSTM 模型
  64. model = Sequential()
  65. model.add(LSTM(units=50, return_sequences=False, input_shape=(time_steps, X_train.shape[2])))
  66. model.add(Dense(1)) # 输出单一值
  67. # 编译模型
  68. model.compile(optimizer='adam', loss='mean_squared_error')
  69. # 定义 EarlyStopping 和 ReduceLROnPlateau 回调
  70. early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True, verbose=1)
  71. reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1)
  72. # 训练模型
  73. history = model.fit(X_train, y_train,
  74. epochs=100,
  75. batch_size=32,
  76. validation_data=(X_test, y_test),
  77. verbose=2,
  78. callbacks=[early_stopping, reduce_lr])
  79. # draw_loss(history)
  80. return model,feature_scaler_bytes,target_scaler_bytes
  81. def str_to_list(arg):
  82. if arg == '':
  83. return []
  84. else:
  85. return arg.split(',')
  86. @app.route('/model_training_lstm', methods=['POST'])
  87. def model_training_lstm():
  88. # 获取程序开始时间
  89. start_time = time.time()
  90. result = {}
  91. success = 0
  92. print("Program starts execution!")
  93. try:
  94. args = request.values.to_dict()
  95. print('args',args)
  96. logger.info(args)
  97. power_df = get_data_from_mongo(args)
  98. model,feature_scaler_bytes,target_scaler_bytes = build_model(power_df,args)
  99. insert_h5_model_into_mongo(model,feature_scaler_bytes,target_scaler_bytes ,args)
  100. success = 1
  101. except Exception as e:
  102. my_exception = traceback.format_exc()
  103. my_exception.replace("\n","\t")
  104. result['msg'] = my_exception
  105. end_time = time.time()
  106. result['success'] = success
  107. result['args'] = args
  108. result['start_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time))
  109. result['end_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time))
  110. print("Program execution ends!")
  111. return result
  112. if __name__=="__main__":
  113. print("Program starts execution!")
  114. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  115. logger = logging.getLogger("model_training_lightgbm log")
  116. from waitress import serve
  117. serve(app, host="0.0.0.0", port=10096)
  118. print("server start!")