版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
第PyTorch搭建LSTM實現(xiàn)時間序列負荷預(yù)測目錄I.前言II.數(shù)據(jù)處理III.LSTM模型IV.訓(xùn)練V.測試VI.源碼及數(shù)據(jù)
I.前言
在上一篇文章深入理解PyTorch中LSTM的輸入和輸出(從input輸入到Linear輸出)中,我詳細地解釋了如何利用PyTorch來搭建一個LSTM模型,本篇文章的主要目的是搭建一個LSTM模型用于時間序列預(yù)測。
系列文章:
PyTorch搭建LSTM實現(xiàn)多變量多步長時序負荷預(yù)測
PyTorch搭建LSTM實現(xiàn)多變量時序負荷預(yù)測
PyTorch深度學(xué)習(xí)LSTM從input輸入到Linear輸出
PyTorch搭建雙向LSTM實現(xiàn)時間序列負荷預(yù)測
II.數(shù)據(jù)處理
數(shù)據(jù)集為某個地區(qū)某段時間內(nèi)的電力負荷數(shù)據(jù),除了負荷以外,還包括溫度、濕度等信息。
本篇文章暫時不考慮其它變量,只考慮用歷史負荷來預(yù)測未來負荷。
本文中,我們根據(jù)前24個時刻的負荷下一時刻的負荷。有關(guān)多變量預(yù)測請參考:PyTorch搭建LSTM實現(xiàn)多變量時間序列預(yù)測(負荷預(yù)測)。
defload_data(file_name):
globalMAX,MIN
df=pd.read_csv('data/new_data/'+file_name,encoding='gbk')
columns=df.columns
df.fillna(df.mean(),inplace=True)
MAX=np.max(df[columns[1]])
MIN=np.min(df[columns[1]])
df[columns[1]]=(df[columns[1]]-MIN)/(MAX-MIN)
returndf
classMyDataset(Dataset):
def__init__(self,data):
self.data=data
def__getitem__(self,item):
returnself.data[item]
def__len__(self):
returnlen(self.data)
defnn_seq(file_name,B):
print('處理數(shù)據(jù):')
data=load_data(file_name)
load=data[data.columns[1]]
load=load.tolist()
load=torch.FloatTensor(load).view(-1)
data=data.values.tolist()
seq=[]
foriinrange(len(data)-24):
train_seq=[]
train_label=[]
forjinrange(i,i+24):
train_seq.append(load[j])
train_label.append(load[i+24])
train_seq=torch.FloatTensor(train_seq).view(-1)
train_label=torch.FloatTensor(train_label).view(-1)
seq.append((train_seq,train_label))
#print(seq[:5])
Dtr=seq[0:int(len(seq)*0.7)]
Dte=seq[int(len(seq)*0.7):len(seq)]
train_len=int(len(Dtr)/B)*B
test_len=int(len(Dte)/B)*B
Dtr,Dte=Dtr[:train_len],Dte[:test_len]
train=MyDataset(Dtr)
test=MyDataset(Dte)
Dtr=DataLoader(dataset=train,batch_size=B,shuffle=False,num_workers=0)
Dte=DataLoader(dataset=test,batch_size=B,shuffle=False,num_workers=0)
returnDtr,Dte
上面代碼用了DataLoader來對原始數(shù)據(jù)進行處理,最終得到了batch_size=B的數(shù)據(jù)集Dtr和Dte,Dtr為訓(xùn)練集,Dte為測試集。
III.LSTM模型
這里采用了深入理解PyTorch中LSTM的輸入和輸出(從input輸入到Linear輸出)中的模型:
classLSTM(nn.Module):
def__init__(self,input_size,hidden_size,num_layers,output_size,batch_size):
super().__init__()
self.input_size=input_size
self.hidden_size=hidden_size
self.num_layers=num_layers
self.output_size=output_size
self.num_directions=1#單向LSTM
self.batch_size=batch_size
self.lstm=nn.LSTM(self.input_size,self.hidden_size,self.num_layers,batch_first=True)
self.linear=nn.Linear(self.hidden_size,self.output_size)
defforward(self,input_seq):
h_0=torch.randn(self.num_directions*self.num_layers,self.batch_size,self.hidden_size).to(device)
c_0=torch.randn(self.num_directions*self.num_layers,self.batch_size,self.hidden_size).to(device)
seq_len=input_seq.shape[1]#(5,24)
#input(batch_size,seq_len,input_size)
input_seq=input_seq.view(self.batch_size,seq_len,1)#(5,24,1)
#output(batch_size,seq_len,num_directions*hidden_size)
output,_=self.lstm(input_seq,(h_0,c_0))#output(5,24,64)
output=output.contiguous().view(self.batch_size*seq_len,self.hidden_size)#(5*24,64)
pred=self.linear(output)#pred(150,1)
pred=pred.view(self.batch_size,seq_len,-1)#(5,24,1)
pred=pred[:,-1,:]#(5,1)
returnpred
IV.訓(xùn)練
defLSTM_train(name,b):
Dtr,Dte=nn_seq(file_name=name,B=b)
input_size,hidden_size,num_layers,output_size=1,64,5,1
model=LSTM(input_size,hidden_size,num_layers,output_size,batch_size=b).to(device)
loss_function=nn.MSELoss().to(device)
optimizer=torch.optim.Adam(model.parameters(),lr=0.001)
#訓(xùn)練
epochs=15
cnt=0
foriinrange(epochs):
cnt=0
print('當(dāng)前',i)
for(seq,label)inDtr:
cnt+=1
seq=seq.to(device)
label=label.to(device)
y_pred=model(seq)
loss=loss_function(y_pred,label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
ifcnt%100==0:
print('epoch',i,':',cnt-100,'~',cnt,loss.item())
state={'model':model.state_dict(),'optimizer':optimizer.state_dict()}
torch.save(state,LSTM_PATH)
一共訓(xùn)練了15輪:
V.測試
deftest(name,b):
globalMAX,MIN
Dtr,Dte=nn_seq(file_name=name,B=b)
pred=[]
y=[]
print('loadingmodel...')
input_size,hidden_size,num_layers,output_size=1,64,5,1
model=LSTM(input_size,hidden_size,num_layers,output_size,batch_size=b).to(device)
model.load_state_dict(torch.load(LSTM_PATH)['model'])
model.eval()
print('predicting...')
for(seq,target)inDte:
target=list(chain.from_iterable(target.data.tolist()))
y.extend(target)
seq=seq.to(device)
seq_len=seq.shape[1]
seq=seq.view(model.batch_size,seq_len,1)#(5,24,1)
withtorch.no_grad():
y_pred=model(seq)
y_pred=list(chain.from_iterable(y_pred.data.tolist()))
pred.extend(y_pred)
y,pred=np.array(y),np.array(pred)
y=(MAX-MIN)*y+MIN
pred=(MAX-MIN)*pred+MIN
print('accuracy:',get_mape(y,pred))
#plot
x=[iforiinrange(1,151)]
x_smooth=np.linspace(np.min(x),np.max(x),600)
y_smooth=make_interp_spline(x,y[0:150])(x_smooth)
plt.plot(x_smooth,y_smooth,c='green',marker='*',ms=1,alpha=0.75,label='true')
y_smooth=make_interp_spline(x,pred[0:150])(x_smooth)
plt.plo
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 辦公場地租賃押金管理細則協(xié)議2025年
- 2024年中考道德與法治(上海)第二次模擬考試(含答案)
- 2025年海南省公需課學(xué)習(xí)-重點排污單位自動監(jiān)測數(shù)據(jù)標(biāo)記規(guī)則第344期
- 冰點文庫撈鐵牛課件
- 2025年中考沈陽歷史試卷及答案
- 2025年共同條例考核試卷及答案
- 景區(qū)輪船維修合同范本
- 2025年高熱度智商測試題及答案
- 2025年行政管理常識題庫及答案
- 礦山承包協(xié)議合同范本
- 基于地理信息系統(tǒng)的位置分析與環(huán)境影響評價-洞察及研究
- 藥物警戒培訓(xùn)課件
- 【2025秋新版】三年級上冊語文期末復(fù)習(xí)1- 8單元日積月累
- 競爭性談判會議記錄
- GB/T 30658-2025假肢和矯形器開具下肢假肢處方考慮的因素
- 安全標(biāo)志現(xiàn)場評審規(guī)范
- 食品添加劑檢驗員崗位面試問題及答案
- 電商公司選品管理制度
- 鋁合金鑄造項目可行性研究報告
- 第19課《只有一個地球》第二課時 課件
- 噴涂角度對鋁-銅接觸件冷噴涂銅防護涂層結(jié)構(gòu)形成及耐蝕性能的影響
評論
0/150
提交評論