PyTorch?之?強(qiáng)大的?hub?模塊和搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè)
本文參加新星計(jì)劃人工智能(Pytorch)賽道:https://bbs.csdn.net/topics/613989052

一、強(qiáng)大的 hub 模塊
- hub 模塊是調(diào)用別人訓(xùn)練好的網(wǎng)絡(luò)架構(gòu)以及訓(xùn)練好的權(quán)重參數(shù),使得自己的一行代碼就可以解決問(wèn)題,方便大家進(jìn)行調(diào)用。
- hub 模塊的 GITHUB 地址是 https://github.com/pytorch/hub。
- hub 模塊的模型 網(wǎng)址是 https://pytorch.org/hub/research-models。
1. hub 模塊的使用
首先,我們進(jìn)入網(wǎng)址。會(huì)出現(xiàn)如下的界面(這其中就是別人訓(xùn)練好的模型,我們通過(guò)一行代碼就可以實(shí)現(xiàn)調(diào)用)。

然后,我們隨便點(diǎn)開(kāi)一個(gè)模型,會(huì)出現(xiàn)如下界面。

其中,第一個(gè)按鈕是對(duì)應(yīng)的 GITHUB 代碼,第二個(gè)是使用谷歌配置好的實(shí)驗(yàn)環(huán)境,第三個(gè)進(jìn)行模型演示。
2. hub 模塊的代碼演示
首先,我們進(jìn)行基本的導(dǎo)入。
import torch
model = torch.hub.load('pytorch/vision:v0.4.2', 'deeplabv3_resnet101', pretrained=True)
model.eval()我們可以使用 hub.list() 查看對(duì)應(yīng) pytorch 版本的模型信息。
torch.hub.list('pytorch/vision:v0.4.2')
#Using cache found in C:\Users\Administrator/.cache\torch\hub\pytorch_vision_v0.4.2
#['alexnet',
# 'deeplabv3_resnet101',
# 'densenet121',
# 'densenet161',
# 'densenet169',
# 'densenet201',
# 'fcn_resnet101',
# 'googlenet',
# 'inception_v3',
# 'mobilenet_v2',
# 'resnet101',
# 'resnet152',
# 'resnet18',
# 'resnet34',
# 'resnet50',
# 'resnext101_32x8d',
# 'resnext50_32x4d',
# 'shufflenet_v2_x0_5',
# 'shufflenet_v2_x1_0',
# 'squeezenet1_0',
# 'squeezenet1_1',
# 'vgg11',
# 'vgg11_bn',
# 'vgg13',
# 'vgg13_bn',
# 'vgg16',
# 'vgg16_bn',
# 'vgg19',
# 'vgg19_bn',
# 'wide_resnet101_2',
# 'wide_resnet50_2']
我們可以從 pytorch 的網(wǎng)站上下載一個(gè)實(shí)例。
# Download an example image from the pytorch website
import urllib
url, filename = ("https://github.com/pytorch/hub/raw/master/dog.jpg", "dog.jpg")
try: urllib.URLopener().retrieve(url, filename)
except: urllib.request.urlretrieve(url, filename)我們執(zhí)行樣本,這里需要注意的是 torchvision。
# sample execution (requires torchvision)
from PIL import Image
from torchvision import transforms
input_image = Image.open(filename)
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
?
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
我們需要將輸入和模型移動(dòng)到GPU以獲得速度(如果可用)。
# move the input and model to GPU for speed if available
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
?
with torch.no_grad():
output = model(input_batch)['out'][0]
output_predictions = output.argmax(0)我們可以創(chuàng)建一個(gè)調(diào)色板,為每個(gè)類選擇一種顏色。
# create a color pallette, selecting a color for each class
palette = torch.tensor([2 ** 25 - 1, 2 ** 15 - 1, 2 ** 21 - 1])
colors = torch.as_tensor([i for i in range(21)])[:, None] * palette
colors = (colors % 255).numpy().astype("uint8")我們可以使用 hub 模塊中的模型繪制每種顏色 21 個(gè)類別的語(yǔ)義分割預(yù)測(cè)。?
# plot the semantic segmentation predictions of 21 classes in each color r = Image.fromarray(output_predictions.byte().cpu().numpy()).resize(input_image.size) r.putpalette(colors) ? import matplotlib.pyplot as plt plt.imshow(r) plt.show()

二、搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè)
1. 數(shù)據(jù)信息處理 在最開(kāi)始,我們需要導(dǎo)入必備的庫(kù)。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline我們需要觀察一下自己的數(shù)據(jù)都有哪些信息,在此之前,我們需要進(jìn)行數(shù)據(jù)的讀入,并打印數(shù)據(jù)的前五行進(jìn)行觀察。
features = pd.read_csv('temps.csv')
features.head()
#year month day week temp_2 temp_1 average actual friend
#0 2016 1 1 Fri 45 45 45.6 45 29
#1 2016 1 2 Sat 44 45 45.7 44 61
#2 2016 1 3 Sun 45 44 45.8 41 56
#3 2016 1 4 Mon 44 41 45.9 40 53
#4 2016 1 5 Tues 41 40 46.0 44 41- 在我們的數(shù)據(jù)表中,包含如下數(shù)據(jù)信息:
- (1) year 表示年數(shù)時(shí)間信息。
- (2) month 表示月數(shù)時(shí)間信息。
- (3) day 表示天數(shù)時(shí)間信息。
- (4) week 表示周數(shù)時(shí)間信息。
- (5) temp_2 表示前天的最高溫度值。
- (6) temp_1 表示昨天的最高溫度值。
- (7) average 表示在歷史中,每年這一天的平均最高溫度值。
- (8) actual 表示這就是我們的標(biāo)簽值了,當(dāng)天的真實(shí)最高溫度。
- (9) friend 表示這一列可能是湊熱鬧的,你的朋友猜測(cè)的可能值,咱們不管它就好了。
- 在獲悉每一個(gè)數(shù)據(jù)的信息之后,我們需要知道一共有多少個(gè)數(shù)據(jù)。
print('數(shù)據(jù)維度:', features.shape)
#數(shù)據(jù)維度: (348, 9)- (348, 9) 表示一共有 348 天,每一天有 9 個(gè)數(shù)據(jù)特征。
- 對(duì)于這么多的數(shù)據(jù),直接進(jìn)行行和列的操作可能會(huì)不太容易,因此,我們可以導(dǎo)入時(shí)間數(shù)據(jù)模塊,將其轉(zhuǎn)換為標(biāo)準(zhǔn)的時(shí)間信息。
# 處理時(shí)間數(shù)據(jù) import datetime ? # 分別得到年,月,日 years = features['year'] months = features['month'] days = features['day'] ? # datetime格式 dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)] dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
我們可以讀取新列 dates 中的部分?jǐn)?shù)據(jù)。
dates[:5] #[datetime.datetime(2016, 1, 1, 0, 0), # datetime.datetime(2016, 1, 2, 0, 0), # datetime.datetime(2016, 1, 3, 0, 0), # datetime.datetime(2016, 1, 4, 0, 0), # datetime.datetime(2016, 1, 5, 0, 0)]
2. 數(shù)據(jù)圖畫(huà)繪制
在基本數(shù)據(jù)處理完成后,我們就開(kāi)始圖畫(huà)的繪制,在最開(kāi)始,需要指定為默認(rèn)的風(fēng)格。
plt.style.use('fivethirtyeight')設(shè)置布局信息。
# 設(shè)置布局 fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize = (10,10)) fig.autofmt_xdate(rotation = 45)
設(shè)置標(biāo)簽值信息。
#標(biāo)簽值
ax1.plot(dates, features['actual'])
ax1.set_xlabel(''); ax1.set_ylabel('Temperature'); ax1.set_title('Max Temp')
繪制昨天也就是 temp_1 的數(shù)據(jù)圖畫(huà)。?
# 昨天
ax2.plot(dates, features['temp_1'])
ax2.set_xlabel(''); ax2.set_ylabel('Temperature'); ax2.set_title('Previous Max Temp')繪制前天也就是 temp_2 的數(shù)據(jù)圖畫(huà)。?
# 前天
ax3.plot(dates, features['temp_2'])
ax3.set_xlabel('Date'); ax3.set_ylabel('Temperature'); ax3.set_title('Two Days Prior Max Temp')繪制朋友也就是 friend 的數(shù)據(jù)圖畫(huà)。
# 我的逗逼朋友
ax4.plot(dates, features['friend'])
ax4.set_xlabel('Date'); ax4.set_ylabel('Temperature'); ax4.set_title('Friend Estimate')在上述信息設(shè)置完成后,開(kāi)始圖畫(huà)的繪制。
plt.tight_layout(pad=2)

對(duì)原始數(shù)據(jù)中的信息進(jìn)行編碼,這里主要是指周數(shù)信息。
# 獨(dú)熱編碼 features = pd.get_dummies(features) features.head(5) #year month day temp_2 temp_1 average actual friend week_Fri week_Mon week_Sat week_Sun week_Thurs week_Tues week_Wed #0 2016 1 1 45 45 45.6 45 29 1 0 0 0 0 0 0 #1 2016 1 2 44 45 45.7 44 61 0 0 1 0 0 0 0 #2 2016 1 3 45 44 45.8 41 56 0 0 0 1 0 0 0 #3 2016 1 4 44 41 45.9 40 53 0 1 0 0 0 0 0 #4 2016 1 5 41 40 46.0 44 41 0 0 0 0 0 1 0
在周數(shù)信息編碼完成后,我們將準(zhǔn)確值進(jìn)行標(biāo)簽操作,在特征數(shù)據(jù)中去掉標(biāo)簽數(shù)據(jù),并將此時(shí)數(shù)據(jù)特征中的標(biāo)簽信息保存一下,并將其轉(zhuǎn)換成合適的格式。
# 標(biāo)簽
labels = np.array(features['actual'])
?
# 在特征中去掉標(biāo)簽
features= features.drop('actual', axis = 1)
?
# 名字單獨(dú)保存一下,以備后患
feature_list = list(features.columns)
?
# 轉(zhuǎn)換成合適的格式
features = np.array(features)我們可以查看此時(shí)特征數(shù)據(jù)的具體數(shù)量。
features.shape #(348, 14)
- (348, 14) 表示我們的特征數(shù)據(jù)當(dāng)中一共有 348 個(gè),每一個(gè)有 14 個(gè)特征。
- 我們可以查看第一個(gè)的具體數(shù)據(jù)。
from sklearn import preprocessing input_features = preprocessing.StandardScaler().fit_transform(features) input_features[0] #array([ 0. , -1.5678393 , -1.65682171, -1.48452388, -1.49443549, # -1.3470703 , -1.98891668, 2.44131112, -0.40482045, -0.40961596, # -0.40482045, -0.40482045, -0.41913682, -0.40482045])
3. 構(gòu)建網(wǎng)絡(luò)模型
x = torch.tensor(input_features, dtype = float)
?
y = torch.tensor(labels, dtype = float)
?
# 權(quán)重參數(shù)初始化
weights = torch.randn((14, 128), dtype = float, requires_grad = True)
biases = torch.randn(128, dtype = float, requires_grad = True)
weights2 = torch.randn((128, 1), dtype = float, requires_grad = True)
biases2 = torch.randn(1, dtype = float, requires_grad = True)
?
learning_rate = 0.001
losses = []
?
for i in range(1000):
# 計(jì)算隱層
hidden = x.mm(weights) + biases
# 加入激活函數(shù)
hidden = torch.relu(hidden)
# 預(yù)測(cè)結(jié)果
predictions = hidden.mm(weights2) + biases2
# 通計(jì)算損失
loss = torch.mean((predictions - y) ** 2)
losses.append(loss.data.numpy())
# 打印損失值
if i % 100 == 0:
print('loss:', loss)
#返向傳播計(jì)算
loss.backward()
#更新參數(shù)
weights.data.add_(- learning_rate * weights.grad.data)
biases.data.add_(- learning_rate * biases.grad.data)
weights2.data.add_(- learning_rate * weights2.grad.data)
biases2.data.add_(- learning_rate * biases2.grad.data)
# 每次迭代都得記得清空
weights.grad.data.zero_()
biases.grad.data.zero_()
weights2.grad.data.zero_()
biases2.grad.data.zero_()
?#loss: tensor(8347.9924, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(152.3170, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(145.9625, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(143.9453, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(142.8161, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(142.0664, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(141.5386, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(141.1528, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(140.8618, dtype=torch.float64, grad_fn=<MeanBackward0>)
#loss: tensor(140.6318, dtype=torch.float64, grad_fn=<MeanBackward0>)
我們查看預(yù)測(cè)數(shù)據(jù)的具體數(shù)量,應(yīng)該是一共有 348 個(gè),每個(gè)只有一個(gè)值,也就是 (348,1)。
predictions.shape #torch.Size([348, 1])
4. 更簡(jiǎn)單的構(gòu)建網(wǎng)絡(luò)模型
input_size = input_features.shape[1]
hidden_size = 128
output_size = 1
batch_size = 16
my_nn = torch.nn.Sequential(
torch.nn.Linear(input_size, hidden_size),
torch.nn.Sigmoid(),
torch.nn.Linear(hidden_size, output_size),
)
cost = torch.nn.MSELoss(reduction='mean')
optimizer = torch.optim.Adam(my_nn.parameters(), lr = 0.001)
# 訓(xùn)練網(wǎng)絡(luò)
losses = []
for i in range(1000):
batch_loss = []
# MINI-Batch方法來(lái)進(jìn)行訓(xùn)練
for start in range(0, len(input_features), batch_size):
end = start + batch_size if start + batch_size < len(input_features) else len(input_features)
xx = torch.tensor(input_features[start:end], dtype = torch.float, requires_grad = True)
yy = torch.tensor(labels[start:end], dtype = torch.float, requires_grad = True)
prediction = my_nn(xx)
loss = cost(prediction, yy)
optimizer.zero_grad()
loss.backward(retain_graph=True)
optimizer.step()
batch_loss.append(loss.data.numpy())
# 打印損失
if i % 100==0:
losses.append(np.mean(batch_loss))
print(i, np.mean(batch_loss))
#0 3950.7627
#100 37.9201
#200 35.654438
#300 35.278366
#400 35.116814
#500 34.986076
#600 34.868954
#700 34.75414
#800 34.637356
#900 34.516705
我們可以得到如下的預(yù)測(cè)訓(xùn)練結(jié)果,將其用圖畫(huà)的形式展現(xiàn)出來(lái)。
x = torch.tensor(input_features, dtype = torch.float)
predict = my_nn(x).data.numpy()
# 轉(zhuǎn)換日期格式
dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in dates]
?
# 創(chuàng)建一個(gè)表格來(lái)存日期和其對(duì)應(yīng)的標(biāo)簽數(shù)值
true_data = pd.DataFrame(data = {'date': dates, 'actual': labels})
?
# 同理,再創(chuàng)建一個(gè)來(lái)存日期和其對(duì)應(yīng)的模型預(yù)測(cè)值
months = features[:, feature_list.index('month')]
days = features[:, feature_list.index('day')]
years = features[:, feature_list.index('year')]
?
test_dates = [str(int(year)) + '-' + str(int(month)) + '-' + str(int(day)) for year, month, day in zip(years, months, days)]
?
test_dates = [datetime.datetime.strptime(date, '%Y-%m-%d') for date in test_dates]
?
predictions_data = pd.DataFrame(data = {'date': test_dates, 'prediction': predict.reshape(-1)})
# 真實(shí)值
plt.plot(true_data['date'], true_data['actual'], 'b-', label = 'actual')
?
# 預(yù)測(cè)值
plt.plot(predictions_data['date'], predictions_data['prediction'], 'ro', label = 'prediction')
plt.xticks(rotation = '60');
plt.legend()
?
# 圖名
plt.xlabel('Date'); plt.ylabel('Maximum Temperature (F)'); plt.title('Actual and Predicted Values');
到此這篇關(guān)于PyTorch 之 強(qiáng)大的 hub 模塊和搭建神經(jīng)網(wǎng)絡(luò)進(jìn)行氣溫預(yù)測(cè)的文章就介紹到這了,更多相關(guān)PyTorch hub神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyCharm代碼整體縮進(jìn),反向縮進(jìn)的方法
今天小編就為大家分享一篇PyCharm代碼整體縮進(jìn),反向縮進(jìn)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
Python?獲取指定開(kāi)頭指定結(jié)尾所夾中間內(nèi)容(推薦)
獲取文章中指定開(kāi)頭、指定結(jié)尾中所夾的內(nèi)容。其中,開(kāi)頭和結(jié)尾均有多種,但最多也就十幾種,所以代碼還是具有可行性的,今天小編給大家介紹通過(guò)Python?獲取指定開(kāi)頭指定結(jié)尾所夾中間內(nèi)容,感興趣的朋友一起看看吧2023-02-02
Python中的CSV文件使用"with"語(yǔ)句的方式詳解
with語(yǔ)句的主要用法是對(duì)語(yǔ)句中使用的對(duì)象進(jìn)行異常安全的清除.確保文件已關(guān)閉,鎖定已釋放,上下文恢復(fù)等.本文通過(guò)實(shí)例代碼給大家介紹Python中的CSV文件使用"with"語(yǔ)句的相關(guān)知識(shí),感興趣的朋友一起看看吧2018-10-10
python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型
這篇文章主要介紹了python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python開(kāi)發(fā)游戲自動(dòng)化后臺(tái)腳本的實(shí)現(xiàn)
本文主要介紹了Python開(kāi)發(fā)游戲自動(dòng)化后臺(tái)腳本的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
一文教你如何創(chuàng)建Python虛擬環(huán)境venv
創(chuàng)建?Python?虛擬環(huán)境是一個(gè)很好的實(shí)踐,可以幫助我們管理項(xiàng)目的依賴項(xiàng),避免不同項(xiàng)目之間的沖突,下面就跟隨小編一起學(xué)習(xí)一下如何創(chuàng)建Python虛擬環(huán)境venv吧2024-12-12

