最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(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ù)測(cè),感興趣的可以學(xué)習(xí)一下

數(shù)據(jù)集

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

特征構(gòu)造

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

一維卷積

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

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

假設(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ù)測(cè),一維卷積則只是在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ù)測(cè)當(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用作測(cè)試集。

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ù)測(cè)的風(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ù)測(cè)及表現(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

測(cè)試:

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ù)測(cè)的文章就介紹到這了,更多相關(guān)PyTorch CNN風(fēng)速預(yù)測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

鲜城| 安丘市| 诸城市| 光山县| 克东县| 荃湾区| 榆中县| 涿州市| 漯河市| 万盛区| 固原市| 丰台区| 玛曲县| 花莲市| 买车| 楚雄市| 左权县| 循化| 视频| 县级市| 景宁| 临泽县| 汶川县| 确山县| 昔阳县| 包头市| 务川| 和平县| 西乌珠穆沁旗| 措美县| 屯昌县| 新巴尔虎左旗| 上犹县| 谷城县| 台北市| 奉化市| 客服| 霍邱县| 永昌县| 珲春市| 夹江县|