欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PyTorch搭建CNN實(shí)現(xiàn)風(fēng)速預(yù)測

 更新時(shí)間:2021年12月31日 16:08:15   作者:KI-711  
PyTorch是一個(gè)開源的Python機(jī)器學(xué)習(xí)庫,基于Torch,用于自然語言處理等應(yīng)用程序。它不僅能夠?qū)崿F(xiàn)強(qiáng)大的GPU加速,同時(shí)還支持動(dòng)態(tài)神經(jīng)網(wǎng)絡(luò)。本文將介紹PyTorch搭建CNN如何實(shí)現(xiàn)風(fēng)速預(yù)測,感興趣的可以學(xué)習(xí)一下

數(shù)據(jù)集

數(shù)據(jù)集為Barcelona某段時(shí)間內(nèi)的氣象數(shù)據(jù),其中包括溫度、濕度以及風(fēng)速等。本文將利用CNN來對(duì)風(fēng)速進(jìn)行預(yù)測。

特征構(gòu)造

對(duì)于風(fēng)速的預(yù)測,除了考慮歷史風(fēng)速數(shù)據(jù)外,還應(yīng)該充分考慮其余氣象因素的影響。因此,我們根據(jù)前24個(gè)時(shí)刻的風(fēng)速+下一時(shí)刻的其余氣象數(shù)據(jù)來預(yù)測下一時(shí)刻的風(fēng)速。

一維卷積

我們比較熟悉的是CNN處理圖像數(shù)據(jù)時(shí)的二維卷積,此時(shí)的卷積是一種局部操作,通過一定大小的卷積核作用于局部圖像區(qū)域獲取圖像的局部信息。圖像中不同數(shù)據(jù)窗口的數(shù)據(jù)和卷積核做inner product(內(nèi)積)的操作叫做卷積,其本質(zhì)是提純,即提取圖像不同頻段的特征。

上面這段話不是很好理解,我們舉一個(gè)簡單例子:

假設(shè)最左邊的是一個(gè)輸入圖片的某一個(gè)通道,為5 × 5 5 \times55×5,中間為一個(gè)卷積核的一層,3 × 3 3 \times33×3,我們讓卷積核的左上與輸入的左上對(duì)齊,然后整個(gè)卷積核可以往右或者往下移動(dòng),假設(shè)每次移動(dòng)一個(gè)小方格,那么卷積核實(shí)際上走過了一個(gè)3 × 3 3 \times33×3的面積,那么具體怎么卷積?比如一開始位于左上角,輸入對(duì)應(yīng)為(1, 1, 1;-1, 0, -3;2, 1, 1),而卷積層一直為(1, 0, 0;0, 0, 0;0, 0, -1),讓二者做內(nèi)積運(yùn)算,即1 * 1+(-1 * 1)= 0,這個(gè)0便是結(jié)果矩陣的左上角。當(dāng)卷積核掃過圖中陰影部分時(shí),相應(yīng)的內(nèi)積為-1,如上圖所示。

因此,二維卷積是將一個(gè)特征圖在width和height兩個(gè)方向上進(jìn)行滑動(dòng)窗口操作,對(duì)應(yīng)位置進(jìn)行相乘求和。

相比之下,一維卷積通常用于時(shí)序預(yù)測,一維卷積則只是在width或者h(yuǎn)eight方向上進(jìn)行滑動(dòng)窗口并相乘求和。 如下圖所示:

原始時(shí)序數(shù)為:(1, 20, 15, 3, 18, 12. 4, 17),維度為8。卷積核的維度為5,卷積核為:(1, 3, 10, 3, 1)。那么將卷積核作用與上述原始數(shù)據(jù)后,數(shù)據(jù)的維度將變?yōu)椋?-5+1=4。即卷積核中的五個(gè)數(shù)先和原始數(shù)據(jù)中前五個(gè)數(shù)據(jù)做卷積,然后移動(dòng),和第二個(gè)到第六個(gè)數(shù)據(jù)做卷積,以此類推。

數(shù)據(jù)處理

1.數(shù)據(jù)預(yù)處理

數(shù)據(jù)預(yù)處理階段,主要將某些列上的文本數(shù)據(jù)轉(zhuǎn)為數(shù)值型數(shù)據(jù),同時(shí)對(duì)原始數(shù)據(jù)進(jìn)行歸一化處理。文本數(shù)據(jù)如下所示:

經(jīng)過轉(zhuǎn)換后,上述各個(gè)類別分別被賦予不同的數(shù)值,比如"sky is clear"為0,"few clouds"為1。

def load_data():
    global Max, Min
    df = pd.read_csv('Barcelona/Barcelona.csv')
    df.drop_duplicates(subset=[df.columns[0]], inplace=True)
    # weather_main
    listType = df['weather_main'].unique()
    df.fillna(method='ffill', inplace=True)
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_main'] = df['weather_main'].map(dic)
    # weather_description
    listType = df['weather_description'].unique()
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_description'] = df['weather_description'].map(dic)
    # weather_icon
    listType = df['weather_icon'].unique()
    dic = dict.fromkeys(listType)
    for i in range(len(listType)):
        dic[listType[i]] = i
    df['weather_icon'] = df['weather_icon'].map(dic)
    # print(df)

    columns = df.columns
    Max = np.max(df['wind_speed'])  # 歸一化
    Min = np.min(df['wind_speed'])

    for i in range(2, 17):
        column = columns[i]
        if column == 'wind_speed':
            continue
        df[column] = df[column].astype('float64')
        if len(df[df[column] == 0]) == len(df):  # 全0
            continue
        mx = np.max(df[column])
        mn = np.min(df[column])
        df[column] = (df[column] - mn) / (mx - mn)
    # print(df.isna().sum())
    return df

2.數(shù)據(jù)集構(gòu)造

利用當(dāng)前時(shí)刻的氣象數(shù)據(jù)和前24個(gè)小時(shí)的風(fēng)速數(shù)據(jù)來預(yù)測當(dāng)前時(shí)刻的風(fēng)速:

def nn_seq():
    """
    :param flag:
    :param data: 待處理的數(shù)據(jù)
    :return: X和Y兩個(gè)數(shù)據(jù)集,X=[當(dāng)前時(shí)刻的year,month, hour, day, lowtemp, hightemp, 前一天當(dāng)前時(shí)刻的負(fù)荷以及前23小時(shí)負(fù)荷]
                              Y=[當(dāng)前時(shí)刻負(fù)荷]
    """
    print('處理數(shù)據(jù):')
    data = load_data()
    speed = data['wind_speed']
    speed = speed.tolist()
    speed = torch.FloatTensor(speed).view(-1)
    data = data.values.tolist()
    seq = []
    for i in range(len(data) - 30):
        train_seq = []
        train_label = []
        for j in range(i, i + 24):
            train_seq.append(speed[j])
        # 添加溫度、濕度、氣壓等信息
        for c in range(2, 7):
            train_seq.append(data[i + 24][c])
        for c in range(8, 17):
            train_seq.append(data[i + 24][c])
        train_label.append(speed[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.5)]
    Den = seq[int(len(seq) * 0.50):int(len(seq) * 0.75)]
    Dte = seq[int(len(seq) * 0.75):len(seq)]

    return Dtr, Den, Dte

任意輸出其中一條數(shù)據(jù):

(tensor([1.0000e+00, 1.0000e+00, 2.0000e+00, 1.0000e+00, 1.0000e+00, 1.0000e+00,
        1.0000e+00, 1.0000e+00, 0.0000e+00, 1.0000e+00, 5.0000e+00, 0.0000e+00,
        2.0000e+00, 0.0000e+00, 0.0000e+00, 5.0000e+00, 0.0000e+00, 2.0000e+00,
        2.0000e+00, 5.0000e+00, 6.0000e+00, 5.0000e+00, 5.0000e+00, 5.0000e+00,
        5.3102e-01, 5.5466e-01, 4.6885e-01, 1.0066e-03, 5.8000e-01, 6.6667e-01,
        0.0000e+00, 0.0000e+00, 0.0000e+00, 0.0000e+00, 9.9338e-01, 0.0000e+00,
        0.0000e+00, 0.0000e+00]), tensor([5.]))

數(shù)據(jù)被劃分為三部分:Dtr、Den以及Dte,Dtr用作訓(xùn)練集,Dte用作測試集。

CNN模型

1.模型搭建

CNN模型搭建如下:

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1d = nn.Conv1d(1, 64, kernel_size=2)
        self.relu = nn.ReLU(inplace=True)
        self.Linear1 = nn.Linear(64 * 37, 50)
        self.Linear2 = nn.Linear(50, 1) 
        def forward(self, x):
        x = self.conv1d(x)
        x = self.relu(x)
        x = x.view(-1)
        x = self.Linear1(x)
        x = self.relu(x)
        x = self.Linear2(x)
        return x

卷積層定義如下:

self.conv1d = nn.Conv1d(1, 64, kernel_size=2)

一維卷積的原始定義為:

nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

這里channel的概念相當(dāng)于自然語言處理中的embedding,這里輸入通道數(shù)為1,表示每一個(gè)風(fēng)速數(shù)據(jù)的向量維度大小為1,輸出channel設(shè)置為64,卷積核大小為2。

原數(shù)數(shù)據(jù)的維度為38,即前24小時(shí)風(fēng)速+14種氣象數(shù)據(jù)。卷積核大小為2,根據(jù)前文公式,原始時(shí)序數(shù)據(jù)經(jīng)過卷積后維度為:

38 - 2 + 1 = 37

一維卷積后是一個(gè)ReLU激活函數(shù):

self.relu = nn.ReLU(inplace=True)

接下來是兩個(gè)全連接層:

self.Linear1 = nn.Linear(64 * 37, 50)
self.Linear2 = nn.Linear(50, 1)

最后輸出維度為1,即我們需要預(yù)測的風(fēng)速。

2.模型訓(xùn)練

def CNN_train():
    Dtr, Den, Dte = nn_seq()
    print(Dte[0])
    epochs = 100
    model = CNN().to(device)
    loss_function = nn.MSELoss().to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
    # 訓(xùn)練
    print(len(Dtr))
    Dtr = Dtr[0:5000]
    for epoch in range(epochs):
        cnt = 0
        for seq, y_train in Dtr:
            cnt = cnt + 1
            seq, y_train = seq.to(device), y_train.to(device)
            # print(seq.size())
            # print(y_train.size())
            # 每次更新參數(shù)前都梯度歸零和初始化
            optimizer.zero_grad()
            # 注意這里要對(duì)樣本進(jìn)行reshape,
            # 轉(zhuǎn)換成conv1d的input size(batch size, channel, series length)
            y_pred = model(seq.reshape(1, 1, -1))
            loss = loss_function(y_pred, y_train)
            loss.backward()
            optimizer.step()
            if cnt % 500 == 0:
                print(f'epoch: {epoch:3} loss: {loss.item():10.8f}')
        print(f'epoch: {epoch:3} loss: {loss.item():10.10f}')

        state = {'model': model.state_dict(), 'optimizer': optimizer.state_dict()}
        torch.save(state, 'Barcelona' + CNN_PATH)

一共訓(xùn)練100輪:

3.模型預(yù)測及表現(xiàn)

def CNN_predict(cnn, test_seq):
    pred = []
    for seq, labels in test_seq:
        seq = seq.to(device)
        with torch.no_grad():
            pred.append(cnn(seq.reshape(1, 1, -1)).item())
    pred = np.array([pred])
    return pred

測試:

def test():
    Dtr, Den, Dte = nn_seq()
    cnn = CNN().to(device)
    cnn.load_state_dict(torch.load('Barcelona' + CNN_PATH)['model'])
    cnn.eval()
    pred = CNN_predict(cnn, Dte)
    print(mean_absolute_error(te_y, pred2.T), np.sqrt(mean_squared_error(te_y, pred2.T)))

CNN在Dte上的表現(xiàn)如下表所示:

MAERMSE
1.081.51

到此這篇關(guān)于PyTorch搭建CNN實(shí)現(xiàn)風(fēng)速預(yù)測的文章就介紹到這了,更多相關(guān)PyTorch CNN風(fēng)速預(yù)測內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 在?Python?中如何為對(duì)象添加屬性

    在?Python?中如何為對(duì)象添加屬性

    在本文中我們將介紹如何在Python中為對(duì)象添加屬性,我們還將通過示例介紹如何在Python中更改對(duì)象的屬性,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2023-06-06
  • 《Python學(xué)習(xí)手冊(cè)》學(xué)習(xí)總結(jié)

    《Python學(xué)習(xí)手冊(cè)》學(xué)習(xí)總結(jié)

    本篇文章是讀者朋友在學(xué)習(xí)了《Python學(xué)習(xí)手冊(cè)》這本書以后,總結(jié)出的學(xué)習(xí)心得,值得大家參考學(xué)習(xí)。
    2018-01-01
  • pymilvus?offset參數(shù)不生效解決示例

    pymilvus?offset參數(shù)不生效解決示例

    這篇文章主要為大家介紹了pymilvus?offset參數(shù)不生效解決示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • 基于Python-turtle庫繪制路飛的草帽骷髏旗、美國隊(duì)長的盾牌、高達(dá)的源碼

    基于Python-turtle庫繪制路飛的草帽骷髏旗、美國隊(duì)長的盾牌、高達(dá)的源碼

    這篇文章主要介紹了基于Python-turtle庫繪制路飛的草帽骷髏旗、美國隊(duì)長的盾牌、高達(dá)的源碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • 在python Numpy中求向量和矩陣的范數(shù)實(shí)例

    在python Numpy中求向量和矩陣的范數(shù)實(shí)例

    今天小編就為大家分享一篇在python Numpy中求向量和矩陣的范數(shù)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • python處理csv數(shù)據(jù)的方法

    python處理csv數(shù)據(jù)的方法

    這篇文章主要介紹了python處理csv數(shù)據(jù)的方法,實(shí)例分析了Python處理csv數(shù)據(jù)的技巧,需要的朋友可以參考下
    2015-03-03
  • 一文詳解Python中subprocess模塊的用法

    一文詳解Python中subprocess模塊的用法

    Python的subprocess模塊是一個(gè)非常強(qiáng)大的工具,用于啟動(dòng)和與外部進(jìn)程進(jìn)行交互,本文將為大家詳細(xì)介紹?subprocess模塊的各個(gè)方面,希望對(duì)大家有所幫助
    2023-11-11
  • 一文教你利用Python租到最合適的房子

    一文教你利用Python租到最合適的房子

    這篇文章主要為大家詳細(xì)介紹了如何利用Python語言在爬取到房源數(shù)據(jù)后,挑選出符合自己要求的房子呢?感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-09-09
  • python創(chuàng)建臨時(shí)文件夾的方法

    python創(chuàng)建臨時(shí)文件夾的方法

    這篇文章主要介紹了python創(chuàng)建臨時(shí)文件夾的方法,涉及Python基于tempfile模塊創(chuàng)建臨時(shí)文件夾的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2015-07-07
  • Python變量及數(shù)據(jù)類型用法原理匯總

    Python變量及數(shù)據(jù)類型用法原理匯總

    這篇文章主要介紹了Python變量及數(shù)據(jù)類型用法原理匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08

最新評(píng)論