日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Pytorch實(shí)現(xiàn)LSTM案例總結(jié)學(xué)習(xí)_python

作者:ch206265 ? 更新時(shí)間: 2022-09-19 編程語(yǔ)言

前言

關(guān)鍵步驟主要分為數(shù)據(jù)準(zhǔn)備和模型構(gòu)建兩大部分,其中,

數(shù)據(jù)準(zhǔn)備主要工作:

  • 1、訓(xùn)練集和測(cè)試集的劃分
  • 2、訓(xùn)練數(shù)據(jù)的歸一化
  • 3、規(guī)范輸入數(shù)據(jù)的格式

模型構(gòu)建部分主要工作

1、構(gòu)建網(wǎng)絡(luò)層、前向傳播forward()

class LSTM(nn.Module):#注意Module首字母需要大寫
    def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
        super().__init__()
        self.hidden_layer_size = hidden_layer_size

        # 創(chuàng)建LSTM層和linear層,LSTM層提取特征,linear層用作最后的預(yù)測(cè)
        # LSTM算法接受三個(gè)輸入:先前的隱藏狀態(tài),先前的單元狀態(tài)和當(dāng)前輸入。
        self.lstm = nn.LSTM(input_size, hidden_layer_size)
        self.linear = nn.Linear(hidden_layer_size, output_size)

        #初始化隱含狀態(tài)及細(xì)胞狀態(tài)C,hidden_cell變量包含先前的隱藏狀態(tài)和單元狀態(tài)
        self.hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),
                            torch.zeros(1, 1, self.hidden_layer_size))
                            # 為什么的第二個(gè)參數(shù)也是1
                            # 第二個(gè)參數(shù)代表的應(yīng)該是batch_size吧
                            # 是因?yàn)橹皩?duì)數(shù)據(jù)已經(jīng)進(jìn)行過切分了嗎?????

    def forward(self, input_seq):
    	#lstm的輸出是當(dāng)前時(shí)間步的隱藏狀態(tài)ht和單元狀態(tài)ct以及輸出lstm_out
        lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq), 1, -1), self.hidden_cell)
        #按照l(shuí)stm的格式修改input_seq的形狀,作為linear層的輸入
        predictions = self.linear(lstm_out.view(len(input_seq), -1))
        #返回predictions的最后一個(gè)元素
        return predictions[-1]

定義好每層之后,最后還需要通過前向傳播的方式把這些串起來,這就涉及如何定義forward函數(shù)。

forward函數(shù)的任務(wù)需要把輸入層、網(wǎng)絡(luò)層、輸出層鏈接起來,實(shí)現(xiàn)信息的前向傳導(dǎo)。

forward該函數(shù)的參數(shù)一般為輸入數(shù)據(jù),返回值是輸出數(shù)據(jù)。

2、實(shí)例化網(wǎng)絡(luò),定義損失函數(shù)和優(yōu)化器

#創(chuàng)建LSTM()類的對(duì)象,定義損失函數(shù)和優(yōu)化器
model = LSTM()
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)#建立優(yōu)化器實(shí)例
print(model)

3、訓(xùn)練模型、反向傳播backward()

epochs = 150
for i in range(epochs):
    for seq, labels in train_inout_seq:
        #清除網(wǎng)絡(luò)先前的梯度值
        optimizer.zero_grad()
        #初始化隱藏層數(shù)據(jù)
        model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
                             torch.zeros(1, 1, model.hidden_layer_size))
        #實(shí)例化模型
        y_pred = model(seq)
        
        #計(jì)算損失,反向傳播梯度以及更新模型參數(shù)
        #訓(xùn)練過程中,正向傳播生成網(wǎng)絡(luò)的輸出,計(jì)算輸出和實(shí)際值之間的損失值
        single_loss = loss_function(y_pred, labels)
        single_loss.backward()#調(diào)用backward()自動(dòng)生成梯度
        optimizer.step()#使用optimizer.step()執(zhí)行優(yōu)化器,把梯度傳播回每個(gè)網(wǎng)絡(luò)

    # 查看模型訓(xùn)練的結(jié)果
    if i%25 == 1:
        print(f'epoch:{i:3} loss:{single_loss.item():10.8f}')
print(f'epoch:{i:3} loss:{single_loss.item():10.10f}')

訓(xùn)練模型時(shí)需要使模型處于訓(xùn)練模式,即調(diào)用model.train()。

缺省情況下梯度是累加的,需要手工把梯度初始化或者清零,調(diào)用optimizer.zero_grad()。

在訓(xùn)練過程中正向傳播生成網(wǎng)絡(luò)的輸出,計(jì)算輸出與實(shí)際值之間的損失值。調(diào)用loss.backward()自動(dòng)生成反向傳播梯度,然后使用optimizer.step()執(zhí)行優(yōu)化器,把梯度傳播回每個(gè)網(wǎng)絡(luò)。

實(shí)現(xiàn)梯度反向傳播的方法主要是復(fù)合函數(shù)的鏈?zhǔn)椒▌t。Pytorch提供了自動(dòng)反向傳播的功能,使用nn工具箱,無需自己編寫反向傳播,直接讓損失函數(shù)調(diào)用backward()即可。

反向傳播中,優(yōu)化器十分重要,這類優(yōu)化算法通過使用參數(shù)的梯度值更新參數(shù)。

4、測(cè)試模型

fut_pred = 12
test_inputs = train_data_normalized[-train_window:].tolist()#首先打印出數(shù)據(jù)列表的最后12個(gè)值
print(test_inputs)

#更改模型為測(cè)試或者驗(yàn)證模式
model.eval()#把training屬性設(shè)置為false,使模型處于測(cè)試或驗(yàn)證狀態(tài)
for i in range(fut_pred):
    seq = torch.FloatTensor(test_inputs[-train_window:])
    with torch.no_grad():
        model.hidden = (torch.zeros(1, 1, model.hidden_layer_size),
                        torch.zeros(1, 1, model.hidden_layer_size))
        test_inputs.append(model(seq).item())
#打印最后的12個(gè)預(yù)測(cè)值
print(test_inputs[fut_pred:])
#由于對(duì)訓(xùn)練集數(shù)據(jù)進(jìn)行了標(biāo)準(zhǔn)化,因此預(yù)測(cè)數(shù)據(jù)也是標(biāo)準(zhǔn)化了的
#需要將歸一化的預(yù)測(cè)值轉(zhuǎn)換為實(shí)際的預(yù)測(cè)值。通過inverse_transform實(shí)現(xiàn)
actual_predictions = scaler.inverse_transform(np.array(test_inputs[train_window:]).reshape(-1, 1))
print(actual_predictions)

全部代碼如下:

import torch
import torch.nn as nn
import torch.nn.functional	
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
"""
導(dǎo)入數(shù)據(jù)
"""
flight_data = sns.load_dataset("flights")
print(flight_data.head())
print(flight_data.shape)

#繪制每月乘客的出行頻率
fig_size = plt.rcParams['figure.figsize']
fig_size[0] = 15
fig_size[1] = 5
plt.rcParams['figure.figsize'] = fig_size
plt.title('Month vs Passenger')
plt.ylabel('Total Passengers')
plt.xlabel('Months')
plt.grid(True)
plt.autoscale(axis='x',tight=True)
plt.plot(flight_data['passengers'])
plt.show()

"""
數(shù)據(jù)預(yù)處理
"""
flight_data.columns#顯示數(shù)據(jù)集中 列的數(shù)據(jù)類型
all_data = flight_data['passengers'].values.astype(float)#將passengers列的數(shù)據(jù)類型改為float
#劃分測(cè)試集和訓(xùn)練集
test_data_size = 12
train_data = all_data[:-test_data_size]#除了最后12個(gè)數(shù)據(jù),其他全取
test_data = all_data[-test_data_size:]#取最后12個(gè)數(shù)據(jù)
print(len(train_data))
print(len(test_data))

#最大最小縮放器進(jìn)行歸一化,減小誤差,注意,數(shù)據(jù)標(biāo)準(zhǔn)化只應(yīng)用于訓(xùn)練數(shù)據(jù)而不應(yīng)用于測(cè)試數(shù)據(jù)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(-1, 1))
train_data_normalized = scaler.fit_transform(train_data.reshape(-1, 1))
#查看歸一化之后的前5條數(shù)據(jù)和后5條數(shù)據(jù)
print(train_data_normalized[:5])
print(train_data_normalized[-5:])
#將數(shù)據(jù)集轉(zhuǎn)換為tensor,因?yàn)镻yTorch模型是使用tensor進(jìn)行訓(xùn)練的,并將訓(xùn)練數(shù)據(jù)轉(zhuǎn)換為輸入序列和相應(yīng)的標(biāo)簽
train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1)
#view相當(dāng)于numpy中的resize,參數(shù)代表數(shù)組不同維的維度;
#參數(shù)為-1表示,這個(gè)維的維度由機(jī)器自行推斷,如果沒有-1,那么view中的所有參數(shù)就要和tensor中的元素總個(gè)數(shù)一致

#定義create_inout_sequences函數(shù),接收原始輸入數(shù)據(jù),并返回一個(gè)元組列表。
def create_inout_sequences(input_data, tw):
    inout_seq = []
    L = len(input_data)
    for i in range(L-tw):
        train_seq = input_data[i:i+tw]
        train_label = input_data[i+tw:i+tw+1]#預(yù)測(cè)time_step之后的第一個(gè)數(shù)值
        inout_seq.append((train_seq, train_label))#inout_seq內(nèi)的數(shù)據(jù)不斷更新,但是總量只有tw+1個(gè)
    return inout_seq
train_window = 12#設(shè)置訓(xùn)練輸入的序列長(zhǎng)度為12,類似于time_step = 12
train_inout_seq = create_inout_sequences(train_data_normalized, train_window)
print(train_inout_seq[:5])#產(chǎn)看數(shù)據(jù)集改造結(jié)果
"""
注意:
create_inout_sequences返回的元組列表由一個(gè)個(gè)序列組成,
每一個(gè)序列有13個(gè)數(shù)據(jù),分別是設(shè)置的12個(gè)數(shù)據(jù)(train_window)+ 第13個(gè)數(shù)據(jù)(label)
第一個(gè)序列由前12個(gè)數(shù)據(jù)組成,第13個(gè)數(shù)據(jù)是第一個(gè)序列的標(biāo)簽。
同樣,第二個(gè)序列從第二個(gè)數(shù)據(jù)開始,到第13個(gè)數(shù)據(jù)結(jié)束,而第14個(gè)數(shù)據(jù)是第二個(gè)序列的標(biāo)簽,依此類推。
"""

"""
創(chuàng)建LSTM模型
參數(shù)說明:
1、input_size:對(duì)應(yīng)的及特征數(shù)量,此案例中為1,即passengers
2、output_size:預(yù)測(cè)變量的個(gè)數(shù),及數(shù)據(jù)標(biāo)簽的個(gè)數(shù)
2、hidden_layer_size:隱藏層的特征數(shù),也就是隱藏層的神經(jīng)元個(gè)數(shù)
"""
class LSTM(nn.Module):#注意Module首字母需要大寫
    def __init__(self, input_size=1, hidden_layer_size=100, output_size=1):
        super().__init__()
        self.hidden_layer_size = hidden_layer_size

        # 創(chuàng)建LSTM層和linear層,LSTM層提取特征,linear層用作最后的預(yù)測(cè)
        ##LSTM算法接受三個(gè)輸入:先前的隱藏狀態(tài),先前的單元狀態(tài)和當(dāng)前輸入。
        self.lstm = nn.LSTM(input_size, hidden_layer_size)
        self.linear = nn.Linear(hidden_layer_size, output_size)

        #初始化隱含狀態(tài)及細(xì)胞狀態(tài)C,hidden_cell變量包含先前的隱藏狀態(tài)和單元狀態(tài)
        self.hidden_cell = (torch.zeros(1, 1, self.hidden_layer_size),
                            torch.zeros(1, 1, self.hidden_layer_size))
                            # 為什么的第二個(gè)參數(shù)也是1
                            # 第二個(gè)參數(shù)代表的應(yīng)該是batch_size吧
                            # 是因?yàn)橹皩?duì)數(shù)據(jù)已經(jīng)進(jìn)行過切分了嗎?????

    def forward(self, input_seq):
        lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq), 1, -1), self.hidden_cell)
        #lstm的輸出是當(dāng)前時(shí)間步的隱藏狀態(tài)ht和單元狀態(tài)ct以及輸出lstm_out
        #按照l(shuí)stm的格式修改input_seq的形狀,作為linear層的輸入
        predictions = self.linear(lstm_out.view(len(input_seq), -1))
        return predictions[-1]#返回predictions的最后一個(gè)元素
"""
forward方法:LSTM層的輸入與輸出:out, (ht,Ct)=lstm(input,(h0,C0)),其中
一、輸入格式:lstm(input,(h0, C0))
1、input為(seq_len,batch,input_size)格式的tensor,seq_len即為time_step
2、h0為(num_layers * num_directions, batch, hidden_size)格式的tensor,隱藏狀態(tài)的初始狀態(tài)
3、C0為(seq_len, batch, input_size)格式的tensor,細(xì)胞初始狀態(tài)
二、輸出格式:output,(ht,Ct)
1、output為(seq_len, batch, num_directions*hidden_size)格式的tensor,包含輸出特征h_t(源于LSTM每個(gè)t的最后一層)
2、ht為(num_layers * num_directions, batch, hidden_size)格式的tensor,
3、Ct為(num_layers * num_directions, batch, hidden_size)格式的tensor,
"""

#創(chuàng)建LSTM()類的對(duì)象,定義損失函數(shù)和優(yōu)化器
model = LSTM()
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)#建立優(yōu)化器實(shí)例
print(model)

"""
模型訓(xùn)練
batch-size是指1次迭代所使用的樣本量;
epoch是指把所有訓(xùn)練數(shù)據(jù)完整的過一遍;
由于默認(rèn)情況下權(quán)重是在PyTorch神經(jīng)網(wǎng)絡(luò)中隨機(jī)初始化的,因此可能會(huì)獲得不同的值。
"""
epochs = 150
for i in range(epochs):
    for seq, labels in train_inout_seq:
        #清除網(wǎng)絡(luò)先前的梯度值
        optimizer.zero_grad()#訓(xùn)練模型時(shí)需要使模型處于訓(xùn)練模式,即調(diào)用model.train()。缺省情況下梯度是累加的,需要手工把梯度初始化或者清零,調(diào)用optimizer.zero_grad()
        #初始化隱藏層數(shù)據(jù)
        model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size),
                             torch.zeros(1, 1, model.hidden_layer_size))
        #實(shí)例化模型
        y_pred = model(seq)
        #計(jì)算損失,反向傳播梯度以及更新模型參數(shù)
        single_loss = loss_function(y_pred, labels)#訓(xùn)練過程中,正向傳播生成網(wǎng)絡(luò)的輸出,計(jì)算輸出和實(shí)際值之間的損失值
        single_loss.backward()#調(diào)用loss.backward()自動(dòng)生成梯度,
        optimizer.step()#使用optimizer.step()執(zhí)行優(yōu)化器,把梯度傳播回每個(gè)網(wǎng)絡(luò)

    # 查看模型訓(xùn)練的結(jié)果
    if i%25 == 1:
        print(f'epoch:{i:3} loss:{single_loss.item():10.8f}')
print(f'epoch:{i:3} loss:{single_loss.item():10.10f}')

"""
預(yù)測(cè)
注意,test_input中包含12個(gè)數(shù)據(jù),
在for循環(huán)中,12個(gè)數(shù)據(jù)將用于對(duì)測(cè)試集的第一個(gè)數(shù)據(jù)進(jìn)行預(yù)測(cè),然后將預(yù)測(cè)值附加到test_inputs列表中。
在第二次迭代中,最后12個(gè)數(shù)據(jù)將再次用作輸入,并進(jìn)行新的預(yù)測(cè),然后 將第二次預(yù)測(cè)的新值再次添加到列表中。
由于測(cè)試集中有12個(gè)元素,因此該循環(huán)將執(zhí)行12次。
循環(huán)結(jié)束后,test_inputs列表將包含24個(gè)數(shù)據(jù),其中,最后12個(gè)數(shù)據(jù)將是測(cè)試集的預(yù)測(cè)值。
"""
fut_pred = 12
test_inputs = train_data_normalized[-train_window:].tolist()#首先打印出數(shù)據(jù)列表的最后12個(gè)值
print(test_inputs)

#更改模型為測(cè)試或者驗(yàn)證模式
model.eval()#把training屬性設(shè)置為false,使模型處于測(cè)試或驗(yàn)證狀態(tài)
for i in range(fut_pred):
    seq = torch.FloatTensor(test_inputs[-train_window:])
    with torch.no_grad():
        model.hidden = (torch.zeros(1, 1, model.hidden_layer_size),
                        torch.zeros(1, 1, model.hidden_layer_size))
        test_inputs.append(model(seq).item())
#打印最后的12個(gè)預(yù)測(cè)值
print(test_inputs[fut_pred:])
#由于對(duì)訓(xùn)練集數(shù)據(jù)進(jìn)行了標(biāo)準(zhǔn)化,因此預(yù)測(cè)數(shù)據(jù)也是標(biāo)準(zhǔn)化了的
#需要將歸一化的預(yù)測(cè)值轉(zhuǎn)換為實(shí)際的預(yù)測(cè)值。通過inverse_transform實(shí)現(xiàn)
actual_predictions = scaler.inverse_transform(np.array(test_inputs[train_window:]).reshape(-1, 1))
print(actual_predictions)

"""
根據(jù)實(shí)際值,繪制預(yù)測(cè)值
"""
x = np.arange(132, 132+fut_pred, 1)
plt.title('Month vs Passenger')
plt.ylabel('Total Passengers')
plt.xlabel('Months')
plt.grid(True)
plt.autoscale(axis='x', tight=True)
plt.plot(flight_data['passengers'])
plt.plot(x, actual_predictions)
plt.show()
#繪制最近12個(gè)月的實(shí)際和預(yù)測(cè)乘客數(shù)量,以更大的尺度觀測(cè)數(shù)據(jù)
plt.title('Month vs Passenger')
plt.ylabel('Total Passengers')
plt.xlabel('Months')
plt.grid(True)
plt.autoscale(axis='x', tight=True)
plt.plot(flight_data['passengers'][-train_window:])
plt.plot(x, actual_predictions)
plt.show()

原文鏈接:https://blog.csdn.net/ch206265/article/details/106962354

欄目分類
最近更新