基于SARIMA、XGBoost和CNN-LSTM的時(shí)間序列預(yù)測(cè)對(duì)比(3)
XGBoost
XGBoost (eXtreme Gradient Boosting)是一種梯度增強(qiáng)決策樹算法。它使用集成方法,其中添加新的決策樹模型來(lái)修改現(xiàn)有的決策樹分?jǐn)?shù)。與SARIMA不同的是,XGBoost是一種多元機(jī)器學(xué)習(xí)算法,這意味著該模型可以采用多特征來(lái)提高模型性能。
我們采用特征工程提高模型精度。還創(chuàng)建了3個(gè)附加特性,其中包括AC和DC功率的滯后版本,分別為S1_AC_POWER和S1_DC_POWER,以及通過交流功率除以直流功率的總體效率EFF。并將AC_POWER和MODULE_TEMPERATURE從數(shù)據(jù)中刪除。圖14通過增益(使用一個(gè)特征的分割的平均增益)和權(quán)重(一個(gè)特征在樹中出現(xiàn)的次數(shù))顯示了特征的重要性級(jí)別。
通過網(wǎng)格搜索確定建模使用的超參數(shù),結(jié)果為:*learning rate = 0.01, number of estimators = 1200, subsample = 0.8, colsample by tree = 1, colsample by level = 1, min child weight = 20 and max depth = 10
我們使用MinMaxScaler將訓(xùn)練數(shù)據(jù)縮放到0到1之間(也可以試驗(yàn)其他縮放器,如log-transform和standard-scaler,這取決于數(shù)據(jù)的分布)。通過將所有自變量向后移動(dòng)一段時(shí)間,將數(shù)據(jù)轉(zhuǎn)換為監(jiān)督學(xué)習(xí)數(shù)據(jù)集。
import numpy as np import pandas as pd import xgboost as xgb from sklearn.preprocessing import MinMaxScaler from time import time
def train_test_split(df, test_len=48): """ split data into training and testing. """ train, test = df[:-test_len], df[-test_len:] return train, test
def data_to_supervised(df, shift_by=1, target_var='DC_POWER'): """ Convert data into a supervised learning problem. """ target = df[target_var][shift_by:].values dep = df.drop(target_var, axis=1).shift(-shift_by).dropna().values data = np.column_stack((dep, target)) return data
def xgb_forecast(train, x_test): """ XGBOOST model which outputs prediction and model. """ x_train, y_train = train[:,:-1], train[:,-1] xgb_model = xgb.XGBRegressor(learning_rate=0.01, n_estimators=1500, subsample=0.8, colsample_bytree=1, colsample_bylevel=1, min_child_weight=20, max_depth=14, objective='reg:squarederror') xgb_model.fit(x_train, y_train) yhat = xgb_model.predict([x_test]) return yhat[0], xgb_model
def walk_forward_validation(df): """ A walk forward validation approach by scaling the data and changing into a supervised learning problem. """ preds = [] train, test = train_test_split(df)
scaler = MinMaxScaler(feature_range=(0,1)) train_scaled = scaler.fit_transform(train) test_scaled = scaler.transform(test)
train_scaled_df = pd.DataFrame(train_scaled, columns = train.columns, index=train.index) test_scaled_df = pd.DataFrame(test_scaled, columns = test.columns, index=test.index)
train_scaled_sup, test_scaled_sup = data_to_supervised(train_scaled_df), data_to_supervised(test_scaled_df) history = np.array([x for x in train_scaled_sup])
for i in range(len(test_scaled_sup)): test_x, test_y = test_scaled_sup[i][:-1], test_scaled_sup[i][-1] yhat, xgb_model = xgb_forecast(history, test_x) preds.append(yhat) np.append(history,[test_scaled_sup[i]], axis=0)
pred_array = test_scaled_df.drop("DC_POWER", axis=1).to_numpy() pred_num = np.array([pred]) pred_array = np.concatenate((pred_array, pred_num.T), axis=1) result = scaler.inverse_transform(pred_array)
return result, test, xgb_model
if __name__ == '__main__': start_time = time() xgb_pred, actual, xgb_model = walk_forward_validation(dropped_df_cat) time_len = time() - start_time
print(f'XGBOOST runtime: {round(time_len/60,2)} mins')
圖15顯示了XGBoost模型的預(yù)測(cè)值與SP2 2天內(nèi)記錄的直流功率的比較。
CNN-LSTM
CNN-LSTM (convolutional Neural Network Long - Short-Term Memory)是兩種神經(jīng)網(wǎng)絡(luò)模型的混合模型。CNN是一種前饋神經(jīng)網(wǎng)絡(luò),在圖像處理和自然語(yǔ)言處理方面表現(xiàn)出了良好的性能。它還可以有效地應(yīng)用于時(shí)間序列數(shù)據(jù)的預(yù)測(cè)。LSTM是一種序列到序列的神經(jīng)網(wǎng)絡(luò)模型,旨在解決長(zhǎng)期存在的梯度爆炸/消失問題,使用內(nèi)部存儲(chǔ)系統(tǒng),允許它在輸入序列上積累狀態(tài)。
在本例中,使用CNN-LSTM作為編碼器-****體系結(jié)構(gòu)。由于CNN不直接支持序列輸入,所以我們通過1D CNN讀取序列輸入并自動(dòng)學(xué)習(xí)重要特征。然后LSTM進(jìn)行解碼。與XGBoost模型類似,使用scikitlearn的MinMaxScaler使用相同的數(shù)據(jù)并進(jìn)行縮放,但范圍在-1到1之間。對(duì)于CNN-LSTM,需要將數(shù)據(jù)重新整理為所需的結(jié)構(gòu):[samples, subsequences, timesteps, features],以便可以將其作為輸入傳遞給模型。
由于我們希望為每個(gè)子序列重用相同的CNN模型,因此使用timedidistributedwrapper對(duì)每個(gè)輸入子序列應(yīng)用一次整個(gè)模型。在下面的圖16中可以看到最終模型中使用的不同層的模型摘要。
在將數(shù)據(jù)分解為訓(xùn)練數(shù)據(jù)和測(cè)試數(shù)據(jù)之后,將訓(xùn)練數(shù)據(jù)分解為訓(xùn)練數(shù)據(jù)和驗(yàn)證數(shù)據(jù)集。在所有訓(xùn)練數(shù)據(jù)(包括驗(yàn)證數(shù)據(jù))的每次迭代之后,模型可以進(jìn)一步使用這一點(diǎn)來(lái)評(píng)估模型的性能。
學(xué)習(xí)曲線是深度學(xué)習(xí)中使用的一個(gè)很好的診斷工具,它顯示了模型在每個(gè)階段之后的表現(xiàn)。下面的圖17顯示了模型如何從數(shù)據(jù)中學(xué)習(xí),并顯示了驗(yàn)證數(shù)據(jù)與訓(xùn)練數(shù)據(jù)的收斂。這是良好模特訓(xùn)練的標(biāo)志。
import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler import keras from keras.models import Sequential from keras.layers.convolutional import Conv1D, MaxPooling1D from keras.layers import LSTM, TimeDistributed, RepeatVector, Dense, Flatten from keras.optimizers import Adam
n_steps = 1 subseq = 1
def train_test_split(df, test_len=48): """ Split data in training and testing. Use 48 hours as testing. """ train, test = df[:-test_len], df[-test_len:] return train, test
def split_data(sequences, n_steps): """ Preprocess data returning two arrays. """ x, y = [], [] for i in range(len(sequences)): end_x = i + n_steps
if end_x > len(sequences): break x.append(sequences[i:end_x, :-1]) y.append(sequences[end_x-1, -1])
return np.array(x), np.array(y)
def CNN_LSTM(x, y, x_val, y_val): """ CNN-LSTM model. """ model = Sequential() model.add(TimeDistributed(Conv1D(filters=14, kernel_size=1, activation="sigmoid", input_shape=(None, x.shape[2], x.shape[3])))) model.add(TimeDistributed(MaxPooling1D(pool_size=1))) model.add(TimeDistributed(Flatten())) model.add(LSTM(21, activation="tanh", return_sequences=True)) model.add(LSTM(14, activation="tanh", return_sequences=True)) model.add(LSTM(7, activation="tanh")) model.add(Dense(3, activation="sigmoid")) model.add(Dense(1))
model.compile(optimizer=Adam(learning_rate=0.001), loss="mse", metrics=['mse']) history = model.fit(x, y, epochs=250, batch_size=36, verbose=0, validation_data=(x_val, y_val))
return model, history
# split and resahpe data train, test = train_test_split(dropped_df_cat)
train_x = train.drop(columns="DC_POWER", axis=1).to_numpy() train_y = train["DC_POWER"].to_numpy().reshape(len(train), 1)
test_x = test.drop(columns="DC_POWER", axis=1).to_numpy() test_y = test["DC_POWER"].to_numpy().reshape(len(test), 1)
#scale data scaler_x = MinMaxScaler(feature_range=(-1,1)) scaler_y = MinMaxScaler(feature_range=(-1,1))
train_x = scaler_x.fit_transform(train_x) train_y = scaler_y.fit_transform(train_y)
test_x = scaler_x.transform(test_x) test_y = scaler_y.transform(test_y)
# shape data into CNN-LSTM format [samples, subsequences, timesteps, features] ORIGINAL train_data_np = np.hstack((train_x, train_y)) x, y = split_data(train_data_np, n_steps) x_subseq = x.reshape(x.shape[0], subseq, x.shape[1], x.shape[2])
# create validation set x_val, y_val = x_subseq[-24:], y[-24:] x_train, y_train = x_subseq[:-24], y[:-24]
n_features = x.shape[2] actual = scaler_y.inverse_transform(test_y)
# run CNN-LSTM model if __name__ == '__main__': start_time = time()
model, history = CNN_LSTM(x_train, y_train, x_val, y_val) prediction = []
for i in range(len(test_x)): test_input = test_x[i].reshape(1, subseq, n_steps, n_features) yhat = model.predict(test_input, verbose=0) yhat_IT = scaler_y.inverse_transform(yhat) prediction.append(yhat_IT[0][0])
time_len = time() - start_time mse = mean_squared_error(actual.flatten(), prediction)
print(f'CNN-LSTM runtime: {round(time_len/60,2)} mins') print(f"CNN-LSTM MSE: {round(mse,2)}")
圖18顯示了CNN-LSTM模型的預(yù)測(cè)值與SP2 2天內(nèi)記錄的直流功率的對(duì)比。
由于CNN-LSTM的隨機(jī)性,該模型運(yùn)行10次,并記錄一個(gè)平均MSE值作為最終值,以判斷模型的性能。圖19顯示了為所有模型運(yùn)行記錄的mse的范圍。
結(jié)果對(duì)比下表顯示了每個(gè)模型的MSE (CNN-LSTM的平均MSE)和每個(gè)模型的運(yùn)行時(shí)間(以分鐘為單位)。
從表中可以看出,XGBoost的MSE最低、運(yùn)行時(shí)第二快,并且與所有其他模型相比具有最佳性能。由于該模型顯示了一個(gè)可以接受的每小時(shí)預(yù)測(cè)的運(yùn)行時(shí),它可以成為幫助運(yùn)營(yíng)經(jīng)理決策過程的強(qiáng)大工具。
總結(jié)在本文中我們分析了SP1和SP2,確定SP1性能較低。所以對(duì)SP2的進(jìn)一步調(diào)查顯示,并且查看了SP2中那些模塊性能可能有問題,并使用假設(shè)檢驗(yàn)來(lái)計(jì)算每個(gè)模塊在統(tǒng)計(jì)上明顯表現(xiàn)不佳的次數(shù),' Quc1TzYxW2pYoWX '模塊顯示了約850次低性能計(jì)數(shù)。
我們使用數(shù)據(jù)訓(xùn)練三個(gè)模型:SARIMA、XGBoost和CNN-LSTM。SARIMA表現(xiàn)最差,XGBOOST表現(xiàn)最好,MSE為16.9,運(yùn)行時(shí)間為1.43 min。所以可以說XGBoost在表格數(shù)據(jù)中還是最優(yōu)先得選擇。
本文代碼:https://github.com/Amitdb123/Solar_Power_Analysis-Prediction
數(shù)據(jù)集:https://www.kaggle.com/datasets/ef9660b4985471a8797501c8970009f36c5b3515213e2676cf40f540f0100e54
作者:Amit Bharadwa
*博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。