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

數(shù)據(jù)集為Barcelona某段時間內(nèi)的氣象數(shù)據(jù),其中包括溫度、濕度以及風(fēng)速等。本文將利用CNN來對風(fēng)速進(jìn)行預(yù)測。
特征構(gòu)造
對于風(fēng)速的預(yù)測,除了考慮歷史風(fēng)速數(shù)據(jù)外,還應(yīng)該充分考慮其余氣象因素的影響。因此,我們根據(jù)前24個時刻的風(fēng)速+下一時刻的其余氣象數(shù)據(jù)來預(yù)測下一時刻的風(fēng)速。
一維卷積
我們比較熟悉的是CNN處理圖像數(shù)據(jù)時的二維卷積,此時的卷積是一種局部操作,通過一定大小的卷積核作用于局部圖像區(qū)域獲取圖像的局部信息。圖像中不同數(shù)據(jù)窗口的數(shù)據(jù)和卷積核做inner product(內(nèi)積)的操作叫做卷積,其本質(zhì)是提純,即提取圖像不同頻段的特征。
上面這段話不是很好理解,我們舉一個簡單例子:

假設(shè)最左邊的是一個輸入圖片的某一個通道,為5 × 5 5 \times55×5,中間為一個卷積核的一層,3 × 3 3 \times33×3,我們讓卷積核的左上與輸入的左上對齊,然后整個卷積核可以往右或者往下移動,假設(shè)每次移動一個小方格,那么卷積核實(shí)際上走過了一個3 × 3 3 \times33×3的面積,那么具體怎么卷積?比如一開始位于左上角,輸入對應(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,這個0便是結(jié)果矩陣的左上角。當(dāng)卷積核掃過圖中陰影部分時,相應(yīng)的內(nèi)積為-1,如上圖所示。
因此,二維卷積是將一個特征圖在width和height兩個方向上進(jìn)行滑動窗口操作,對應(yīng)位置進(jìn)行相乘求和。
相比之下,一維卷積通常用于時序預(yù)測,一維卷積則只是在width或者h(yuǎn)eight方向上進(jìn)行滑動窗口并相乘求和。 如下圖所示:

原始時序數(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。即卷積核中的五個數(shù)先和原始數(shù)據(jù)中前五個數(shù)據(jù)做卷積,然后移動,和第二個到第六個數(shù)據(jù)做卷積,以此類推。
數(shù)據(jù)處理
1.數(shù)據(jù)預(yù)處理
數(shù)據(jù)預(yù)處理階段,主要將某些列上的文本數(shù)據(jù)轉(zhuǎn)為數(shù)值型數(shù)據(jù),同時對原始數(shù)據(jù)進(jìn)行歸一化處理。文本數(shù)據(jù)如下所示:

經(jīng)過轉(zhuǎn)換后,上述各個類別分別被賦予不同的數(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ù)據(jù)和前24個小時的風(fēng)速數(shù)據(jù)來預(yù)測當(dāng)前時刻的風(fēng)速:
def nn_seq():
"""
:param flag:
:param data: 待處理的數(shù)據(jù)
:return: X和Y兩個數(shù)據(jù)集,X=[當(dāng)前時刻的year,month, hour, day, lowtemp, hightemp, 前一天當(dāng)前時刻的負(fù)荷以及前23小時負(fù)荷]
Y=[當(dāng)前時刻負(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,表示每一個風(fēng)速數(shù)據(jù)的向量維度大小為1,輸出channel設(shè)置為64,卷積核大小為2。
原數(shù)數(shù)據(jù)的維度為38,即前24小時風(fēng)速+14種氣象數(shù)據(jù)。卷積核大小為2,根據(jù)前文公式,原始時序數(shù)據(jù)經(jīng)過卷積后維度為:
38 - 2 + 1 = 37
一維卷積后是一個ReLU激活函數(shù):
self.relu = nn.ReLU(inplace=True)
接下來是兩個全連接層:
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()
# 注意這里要對樣本進(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)如下表所示:
| MAE | RMSE |
|---|---|
| 1.08 | 1.51 |

到此這篇關(guān)于PyTorch搭建CNN實(shí)現(xiàn)風(fēng)速預(yù)測的文章就介紹到這了,更多相關(guān)PyTorch CNN風(fēng)速預(yù)測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python的flask接收前臺的ajax的post數(shù)據(jù)和get數(shù)據(jù)的方法
這篇文章主要介紹了Python的flask接收前臺的ajax的post數(shù)據(jù)和get數(shù)據(jù)的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
Python Pandas模塊實(shí)現(xiàn)數(shù)據(jù)的統(tǒng)計分析的方法
在上一篇講了幾個常用的“Pandas”函數(shù)之后,今天小編就為大家介紹一下在數(shù)據(jù)統(tǒng)計分析當(dāng)中經(jīng)常用到的“Pandas”函數(shù)方法,希望能對大家有所收獲,需要的朋友可以參考下2021-06-06
python實(shí)現(xiàn)beta分布概率密度函數(shù)的方法
今天小編就為大家分享一篇python實(shí)現(xiàn)beta分布概率密度函數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python關(guān)于__name__屬性的含義和作用詳解
在本篇文章里小編給大家分享的是關(guān)于Python關(guān)于__name__屬性的含義和作用知識點(diǎn),需要的朋友們可以參考下。2020-02-02
PyQt通過動畫實(shí)現(xiàn)平滑滾動的QScrollArea
這篇文章主要為大家詳細(xì)介紹了PyQt如何使用Qt的動畫框架 QPropertyAnimation來實(shí)現(xiàn)平滑滾動的QScrollArea,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的可以學(xué)習(xí)一下2023-01-01
Python實(shí)現(xiàn)杰卡德距離以及環(huán)比算法講解
這篇文章主要為大家介紹了Python實(shí)現(xiàn)杰卡德距離以及環(huán)比算法的示例講解,有需要的朋友可以借鑒參考下2022-02-02

