
LSTM/TCN/LSTM-TCN三种方法简配不带超参数寻优import warnings warnings.filterwarnings(ignore, categoryUserWarning) warnings.filterwarnings(ignore, categoryFutureWarning) warnings.filterwarnings(ignore, categoryRuntimeWarning) import os import pandas as pd import numpy as np import matplotlib.pyplot as plt # 设置TensorFlow日志级别为ERROR os.environ[TF_CPP_MIN_LOG_LEVEL] 2 from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error from sqlalchemy import create_engine import tensorflow as tf from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Input, Conv1D, Add, Dense, LSTM, Attention, Dropout, Reshape, Flatten from tensorflow.keras.optimizers import Adam from scikeras.wrappers import KerasRegressor #######################################数据集准备####################################### engine create_engine(mysqlpymysql://root:192.168.1.22:9030/MPC?charsetutf8) data pd.read_sql_query(SELECT * FROM PV_data ORDER BY date, conengine) print(data.head()) data.describe() # # 绘制直方图 plt.figure(figsize( 12 , 6 )) plt.plot(data[date],data[power], labelreal value,alpha 0.5,colorblue, linestyle-, markero, markersize0.5, linewidth1) plt.legend() # plt.savefig(my_chart.png, dpi300) plt.show() # feature and target features data.iloc[:, 1:-1].values target data[power].values # features,target # feature engineering scaler_features MinMaxScaler() scaler_target MinMaxScaler() features_scaled scaler_features.fit_transform(features) target_scaled scaler_target.fit_transform(target.reshape(-1, 1)) # data seris def create_dataset(features, target, time_step1): X, Y [], [] for i in range(len(features) - time_step - 1): a features[i:(i time_step), :] X.append(a) Y.append(target[i time_step-1]) return np.array(X), np.array(Y) #set stemp time_step 24 X, Y create_dataset(features_scaled, target_scaled, time_step) X_train, X_test, y_train, y_test train_test_split(X, Y, shuffleFalse, test_size0.2, random_state42) #check data print(X_train shape:, X_train.shape) print(X_test shape:, y_train.shape) # #######################################LSTM####################################### def build_LSTM_model(input_shape): inputs Input(shapeinput_shape) x inputs xLSTM(units32,return_sequencesTrue,input_shape(time_step, features.shape[1]))(x) xLSTM(units12,return_sequencesFalse)(x) x Dense(60, activationrelu)(x) outputs Dense(1)(x) model Model(inputsinputs, outputsoutputs) model.compile(optimizeradam, lossmse) return model input_shape (X_test.shape[1], X_test.shape[2]) build_LSTM_modelbuild_LSTM_model(input_shape) build_LSTM_model.summary() #train history build_LSTM_model.fit(X_train, y_train, validation_data(X_test, y_test), batch_size128, epochs20) # # #######################################TCN####################################### def build_tcn_model(input_shape): inputs Input(shapeinput_shape) residual inputs x inputs x Conv1D(filters32, kernel_size3,dilation_rate1,paddingcausal,strides1,activationrelu)(x) x Conv1D(filters6, kernel_size3, dilation_rate1,paddingcausal,strides1, activationrelu)(x) x Add()([x, residual]) x Flatten()(x) x Dense(50, activationrelu)(x) outputs Dense(1)(x) model Model(inputsinputs, outputsoutputs) model.compile(optimizeradam, lossmse) return model input_shape (X_test.shape[1], X_test.shape[2]) build_tcn_model build_tcn_model(input_shape) build_tcn_model.summary() # # train history build_tcn_model.fit(X_train, y_train, validation_data(X_test, y_test), batch_size128, epochs20) ######### def build_tcn_lstm_model(input_shape): inputs Input(shapeinput_shape) residual inputs x inputs x Conv1D(filters32, kernel_size3,dilation_rate1,paddingcausal,strides1,activationrelu)(x) x Conv1D(filters6, kernel_size3, dilation_rate1,paddingcausal,strides1, activationrelu)(x) x Add()([x, residual]) xLSTM(units32,return_sequencesTrue,input_shape(time_step, features.shape[1]))(x) xLSTM(units12,return_sequencesFalse)(x) x Dense(60, activationrelu)(x) outputs Dense(1)(x) model Model(inputsinputs, outputsoutputs) model.compile(optimizeradam, lossmse) return model input_shape (X_test.shape[1], X_test.shape[2]) build_tcn_lstm_model build_tcn_lstm_model(input_shape) build_tcn_lstm_model.summary() # # train history build_tcn_lstm_model.fit(X_train, y_train, validation_data(X_test, y_test), batch_size128, epochs20) #######################################模型预测####################################### # Prediction train_LSTM_predict build_LSTM_model.predict(X_train) test_LSTM_predict build_LSTM_model.predict(X_test) train_TCN_predict build_tcn_model.predict(X_train) test_TCN_predict build_tcn_model.predict(X_test) train_TCN_LSTM_predict build_tcn_lstm_model.predict(X_train) test_TCN_LSTM_predict build_tcn_lstm_model.predict(X_test) # re_maxmin Y_train_actual scaler_target.inverse_transform(y_train) Y_test_actual scaler_target.inverse_transform(y_test) train_LSTM_predict_rescaled scaler_target.inverse_transform(train_LSTM_predict) test_LSTM_predict_rescaled scaler_target.inverse_transform(test_LSTM_predict) train_TCN_predict_rescaled scaler_target.inverse_transform(train_TCN_predict) test_TCN_predict_rescaled scaler_target.inverse_transform(test_TCN_predict) train_TCN_LSTM_predict_rescaled scaler_target.inverse_transform(train_TCN_LSTM_predict) test_TCN_LSTM_predict_rescaled scaler_target.inverse_transform(test_TCN_LSTM_predict) # # Evaluation Metrics def evaluate(Y_true, Y_pred): r2 r2_score(Y_true, Y_pred) mse mean_squared_error(Y_true, Y_pred) rmse np.sqrt(mean_squared_error(Y_true, Y_pred)) mae mean_absolute_error(Y_true, Y_pred) mape np.mean(np.abs((Y_true - Y_pred) / Y_true)) * 100 print(fTest R^2: {r2:.4f}, MSE: {mse:.4f}, RMSE: {rmse:.4f}, MAE: {mae:.4f}, MAPE: {mape:.4f}%) print(LSTM MODEL) evaluate(Y_test_actual, test_LSTM_predict_rescaled) print(TCN MODEL) evaluate(Y_test_actual, test_TCN_predict_rescaled) print(TCNLSTM MODEL) evaluate(Y_test_actual, test_TCN_LSTM_predict_rescaled) # visiluaziton plt.figure(figsize(16, 8)) plt.plot(Y_test_actual, labelreal value, colorblue, linestyle-, markero, markersize2, linewidth1) plt.plot(test_LSTM_predict_rescaled, labelLSTM Predict, colorred, linestyle-, markers, markersize2, linewidth1) plt.plot(test_TCN_predict_rescaled, labelTCN Predict, colorblack, linestyle-, marker^, markersize2, linewidth1) plt.plot(test_TCN_LSTM_predict_rescaled, labelTCNLSTM Predict, colorgreen, linestyle-, marker*, markersize2, linewidth1) plt.ylim([Y_test_actual.min()-10 , Y_test_actual.max() 10]) plt.title(Price Prediction, fontsize16) plt.xlabel(Time, fontsize14) plt.ylabel(Power, fontsize14) plt.legend(fontsize12) plt.grid(True) plt.tight_layout() plt.grid(whichboth, linestyle--, linewidth0.5) plt.axhline(y0, colork, linewidth1) # plt.savefig(my_chart.png, dpi300) plt.show()