1.引言?
???????在之前使用長(zhǎng)短期記憶網(wǎng)絡(luò)構(gòu)建電力負(fù)荷預(yù)測(cè)模型的基礎(chǔ)上,將自注意力機(jī)制 (Self-Attention)融入到負(fù)荷預(yù)測(cè)模型中。具體內(nèi)容是是在LSTM層后面接Self-Attention層,在加入Self-Attention后,可以將負(fù)荷數(shù)據(jù)通過(guò)加權(quán)求和的方式進(jìn)行處理,對(duì)負(fù)荷特征添加注意力權(quán)重,來(lái)突出負(fù)荷的影響因數(shù)。結(jié)果表明,通過(guò)自注意力機(jī)制,可以更好的挖掘電力負(fù)荷數(shù)據(jù)的特征以及變化規(guī)律信息,提高預(yù)測(cè)模型的性能。
? ? ? ? 環(huán)境:python3.8,tensorflow2.5.
2.原理
2.1.自注意力機(jī)制
? ? ? ? 自注意力機(jī)制網(wǎng)上很多推導(dǎo),這里就不再贅述,需要的可以看博客,這個(gè)博客講的很好。
2.2 模型結(jié)構(gòu)
主要包含輸入層,LSTM層,位置編碼層,自注意力機(jī)制層,以及輸出層。
3. 實(shí)戰(zhàn)
3.1 數(shù)據(jù)結(jié)構(gòu)
????????采用2016電工杯負(fù)荷預(yù)測(cè)數(shù)據(jù),每15分鐘采樣一次,一天共96個(gè)負(fù)荷值與5個(gè)氣象數(shù)據(jù)(溫度濕度降雨量啥的)。我們采用滾動(dòng)建模預(yù)測(cè),就是利用1到n天的所有值為輸入,第n+1天的96個(gè)負(fù)荷值為輸出;然后2到n+1天的所有值為輸入,第n+2天的96個(gè)負(fù)荷值為輸出,這樣進(jìn)行滾動(dòng)序列建模。這個(gè)n就是時(shí)間步,程序里面設(shè)置的是20,所以上面的輸入層你看到是Nonex20x101,輸出是Nonex96。
3.2 建模預(yù)測(cè)
# coding: utf-8
from sklearn.preprocessing import StandardScaler,MinMaxScaler
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input,Dense,LSTM
import tensorflow as tf
from Layers import SelfAttention,AddSinusoidalPositionalEncodings
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
from tensorflow.keras.utils import plot_model
# In[]定義一些需要的函數(shù)
def build_model(seq,fea,out):
input_ = Input(shape=(seq,fea))
x=LSTM(20, return_sequences=True)(input_)
pos = AddSinusoidalPositionalEncodings()(x)
att = SelfAttention(100,100,return_sequence=False, dropout=.0)(pos)
out = Dense(out, activation=None)(att)
model = Model(inputs=input_, outputs=out)
return model
def split_data(data, n):
in_ = []
out_ = []
N = data.shape[0] - n
for i in range(N):
in_.append(data[i:i + n,:])
out_.append(data[i + n,:96])
in_ = np.array(in_).reshape(len(in_), -1)
out_ = np.array(out_).reshape(len(out_), -1)
return in_, out_
def result(real,pred,name):
# ss_X = MinMaxScaler(feature_range=(-1, 1))
# real = ss_X.fit_transform(real).reshape(-1,)
# pred = ss_X.transform(pred).reshape(-1,)
real=real.reshape(-1,)
pred=pred.reshape(-1,)
# mape
test_mape = np.mean(np.abs((pred - real) / real))
# rmse
test_rmse = np.sqrt(np.mean(np.square(pred - real)))
# mae
test_mae = np.mean(np.abs(pred - real))
# R2
test_r2 = r2_score(real, pred)
print(name,'的mape:%.4f,rmse:%.4f,mae:%.4f,R2:%.4f'%(test_mape ,test_rmse, test_mae, test_r2))
# In[]
df=pd.read_csv('數(shù)據(jù)集/data196.csv').fillna(0).iloc[:,1:]
data=df.values
time_steps=20
in_,out_=split_data(data,time_steps)
n=range(in_.shape[0])
#m=int(0.8*in_.shape[0])#前80%訓(xùn)練 后20%測(cè)試
m=-2#最后兩天測(cè)試
train_data = in_[n[0:m],]
test_data = in_[n[m:],]
train_label = out_[n[0:m],]
test_label = out_[n[m:],]
# 歸一化
ss_X = StandardScaler().fit(train_data)
ss_Y = StandardScaler().fit(train_label)
# ss_X = MinMaxScaler(feature_range=(0, 1)).fit(train_data)
# ss_Y = MinMaxScaler(feature_range=(0, 1)).fit(train_label)
train_data = ss_X.transform(train_data).reshape(train_data.shape[0], time_steps, -1)
train_label = ss_Y.transform(train_label)
test_data = ss_X.transform(test_data).reshape(test_data.shape[0], time_steps, -1)
test_label = ss_Y.transform(test_label)
# In[]
model=build_model(train_data.shape[-2],train_data.shape[-1],train_label.shape[-1])
#查看網(wǎng)絡(luò)結(jié)構(gòu)
model.summary()
plot_model(model, show_shapes=True, to_file='result/lstmsa_model.jpg')
train_again=True #為 False 的時(shí)候就直接加載訓(xùn)練好的模型進(jìn)行測(cè)試
#訓(xùn)練模型
if train_again:
#編譯模型
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mse')
#訓(xùn)練模型
history=model.fit(train_data,train_label,batch_size=64,epochs=100,
verbose=1,validation_data=(test_data,test_label))
# In[8]
model.save_weights('result/lstmsa_model.h5')
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.plot( loss, label='Train Loss')
plt.plot( val_loss, label='Test Loss')
plt.title('Train and Val Loss')
plt.legend()
plt.savefig('result/lstmsa_model_loss.jpg')
plt.show()
else:#加載模型
model.load_weights('result/lstmsa_model.h5')
# In[]
test_pred = model.predict(test_data)
# 對(duì)測(cè)試集的預(yù)測(cè)結(jié)果進(jìn)行反歸一化
test_label1 = ss_Y.inverse_transform(test_label)
test_pred1 = ss_Y.inverse_transform(test_pred)
# In[]計(jì)算各種指標(biāo)
result(test_label1,test_pred1,'LSTM-SA')
np.savez('result/lstmsa1.npz',real=test_label1,pred=test_pred1)
test_label=test_label1.reshape(-1,)
test_pred=test_pred1.reshape(-1,)
# plot test_set result
plt.figure()
plt.plot(test_label, c='r', label='real')
plt.plot(test_pred, c='b', label='pred')
plt.legend()
plt.xlabel('樣本點(diǎn)')
plt.ylabel('功率')
plt.title('測(cè)試集')
plt.show()
?3.2 結(jié)果對(duì)比
? ? ? ? 將其與RNN、LSTM進(jìn)行對(duì)比,結(jié)果如下
測(cè)試集取的是最后兩天的,從結(jié)果上看,顯然提出的方法效果最好?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-616553.html
4.代碼
? ? ? ? 詳細(xì)代碼見(jiàn)評(píng)論區(qū)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-616553.html
到了這里,關(guān)于基于自注意力機(jī)制的LSTM多變量負(fù)荷預(yù)測(cè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!