前言
大家好,我是阿光。
本專欄整理了《PyTorch深度學(xué)習(xí)項(xiàng)目實(shí)戰(zhàn)100例》,內(nèi)包含了各種不同的深度學(xué)習(xí)項(xiàng)目,包含項(xiàng)目原理以及源碼,每一個(gè)項(xiàng)目實(shí)例都附帶有完整的代碼+數(shù)據(jù)集。
正在更新中~ ?
?? 我的項(xiàng)目環(huán)境:
- 平臺(tái):Windows10
- 語言環(huán)境:python3.7
- 編譯器:PyCharm
- PyTorch版本:1.8.1
?? 項(xiàng)目專欄:【PyTorch深度學(xué)習(xí)項(xiàng)目實(shí)戰(zhàn)100例】
一、GRU進(jìn)行天氣變化的時(shí)間序列預(yù)測(cè)
由于大氣運(yùn)動(dòng)極為復(fù)雜,影響天氣的因素較多,而人們認(rèn)識(shí)大氣本身運(yùn)動(dòng)的能力極為有限,因此天氣預(yù)報(bào)水平較低.預(yù)報(bào)員在預(yù)報(bào)實(shí)踐中,每次預(yù)報(bào)的過程都極為復(fù)雜,需要綜合分析,并預(yù)報(bào)各氣象要素,比如溫度、降水等.現(xiàn)階段,以往極少出現(xiàn)的極端天氣現(xiàn)象越來越多,這極大地增加了預(yù)報(bào)的難度。
本項(xiàng)目使用循環(huán)神經(jīng)網(wǎng)絡(luò)GRU訓(xùn)練一個(gè)網(wǎng)絡(luò)模型,來預(yù)測(cè)在給定天氣因素下,城市的溫度變化。

二、數(shù)據(jù)集介紹
一個(gè)天氣時(shí)間序列數(shù)據(jù)集,它由德國(guó)耶拿的馬克思 ? 普朗克生物地球化學(xué)研究所的氣象站記錄。在這個(gè)數(shù)據(jù)集中,每 10 分鐘記錄 14 個(gè)不同的量(比如氣溫、氣壓、濕度、風(fēng)向等),其中包含2009-2016多年的記錄。
數(shù)據(jù)集下載地址

三、定義網(wǎng)絡(luò)結(jié)構(gòu)
GRU(Gate Recurrent Unit)是循環(huán)神經(jīng)網(wǎng)絡(luò)(Recurrent Neural Network, RNN)的一種。和LSTM(Long-Short Term Memory)一樣,也是為了解決長(zhǎng)期記憶和反向傳播中的梯度等問題而提出來的。

- 更新門:定義了前面記憶保存到當(dāng)前時(shí)間步的量。如果我們將重置門設(shè)置為 1,更新門設(shè)置為 0
- 重置門:本質(zhì)上來說,重置門主要決定了到底有多少過去的信息需要遺忘
# 7.定義LSTM網(wǎng)絡(luò)
class GRU(nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
super(GRU, self).__init__()
self.hidden_dim = hidden_dim # 隱層大小
self.num_layers = num_layers # LSTM層數(shù)
# input_dim為特征維度,就是每個(gè)時(shí)間點(diǎn)對(duì)應(yīng)的特征數(shù)量,這里為14
self.gru = nn.GRU(input_dim, hidden_dim, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_dim, output_dim)
四、訓(xùn)練網(wǎng)絡(luò)

model = GRU(input_dim, hidden_dim, num_layers, output_dim) # 定義LSTM網(wǎng)絡(luò)
loss_function = nn.MSELoss() # 定義損失函數(shù)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01) # 定義優(yōu)化器
# 8.模型訓(xùn)練
for epoch in range(epochs):
model.train()
running_loss = 0
train_bar = tqdm(train_loader) # 形成進(jìn)度條
for data in train_bar:
x_train, y_train = data # 解包迭代器中的X和Y
optimizer.zero_grad()
y_train_pred = model(x_train)
loss = loss_function(y_train_pred, y_train.reshape(-1, 1))
loss.backward()
optimizer.step()
running_loss += loss.item()
train_bar.desc = "train epoch[{}/{}] loss:{:.3f}".format(epoch + 1,
epochs,
loss)
# 模型驗(yàn)證
model.eval()
test_loss = 0
with torch.no_grad():
test_bar = tqdm(test_loader)
for data in test_bar:
x_test, y_test = data
y_test_pred = model(x_test)
test_loss = loss_function(y_test_pred, y_test.reshape(-1, 1))
if test_loss < best_loss:
best_loss = test_loss
torch.save(model.state_dict(), save_path)
print('Finished Training')