重磅乾貨,第一時間送達
本文經作者授權轉載,禁二次轉載
作者 | 王大毛,和鯨社區
地址 | https://www.kesci.com/home/project/5e0038642823a10036ae9ebf
大家好,又是我,我又來給大家碼x題系列了,這次比較高端,是PyTorchPyTorch是一個基於Python的庫,提供了一個具有靈活易用的深度學習框架,是近年來最受歡迎的深度學習框架之一。
點擊此處查看線上運行效果👇
https://www.kesci.com/home/project/5e0038642823a10036ae9ebf
如果你是新新新手,可以先學習以下教程:
https://www.kesci.com/home/project/5e0036722823a10036ae9d1d
https://pytorch-cn.readthedocs.io/zh/latest/
改編自:
https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html#deep-learning-with-pytorch-a-60-minute-blitz
1.導入pytorch包
import torch
2.創建一個空的5x3張量
x = torch.empty(5, 3)
print(x)
3.創建一個隨機初始化的5x3張量
x = torch.rand(5, 3)
print(x)
4.創建一個5x3的0張量,類型為long
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
5.直接從數組創建張量
x = torch.tensor([5.5, 3])
print(x)
6.創建一個5x3的單位張量,類型為double
x = torch.ones(5, 3, dtype=torch.double)
print(x)
7.從已有的張量創建相同維度的新張量,並且重新定義類型為float
x = torch.randn_like(x, dtype=torch.float)
print(x)
8.列印一個張量的維度
print(x.size())
9.將兩個張量相加
y = torch.rand(5, 3)
print(x + y)
# 方法二
# print(torch.add(x, y))
# 方法三
# result = torch.empty(5, 3)
# torch.add(x, y, out=result)
# print(result)
# 方法四
# y.add_(x)
# print(y)
10.取張量的第一列
print(x[:, 1])
11.將一個4x4的張量resize成一個一維張量
x = torch.randn(4, 4)
y = x.view(16)
print(x.size(),y.size())
12.將一個4x4的張量,resize成一個2x8的張量
y = x.view(2, 8)
print(x.size(),y.size())
# 方法二
z = x.view(-1, 8) # 確定一個維度,-1的維度會被自動計算
print(x.size(),z.size())
13.從張量中取出數字
x = torch.randn(1)
print(x)
print(x.item())
14.將張量裝換成numpy數組
a = torch.ones(5)
print(a)
b = a.numpy()
print(b)
15.將張量+1,並觀察上題中numpy數組的變化
a.add_(1)
print(a)
print(b)
16.從numpy數組創建張量
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a)
print(b)
17.將numpy數組+1並觀察上題中張量的變化
np.add(a, 1, out=a)
print(a)
print(b)
18.新建一個張量,並設置requires_grad=True
x = torch.ones(2, 2, requires_grad=True)
print(x)
19.對張量進行任意操作(y = x + 2)
y = x + 2
print(y)
print(y.grad_fn) # y就多了一個AddBackward
20.再對y進行任意操作
z = y * y * 3
out = z.mean()
print(z) # z多了MulBackward
print(out) # out多了MeanBackward
21.對out進行反向傳播
out.backward()
22.列印梯度d(out)/dx
print(x.grad) #out=0.25*Σ3(x+2)^2
23.創建一個結果為矢量的計算過程(y=x*2^n)
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
print(y)
24.計算v = [0.1, 1.0, 0.0001]處的梯度
v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)
y.backward(v)
print(x.grad)
25.關閉梯度的功能
print(x.requires_grad)
print((x ** 2).requires_grad)
with torch.no_grad():
print((x ** 2).requires_grad)
# 方法二
# print(x.requires_grad)
# y = x.detach()
# print(y.requires_grad)
# print(x.eq(y).all())
這部分會實現LeNet5,結構如下所示
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 26.定義①的卷積層,輸入為32x32的圖像,卷積核大小5x5卷積核種類6
self.conv1 = nn.Conv2d(3, 6, 5)
# 27.定義③的卷積層,輸入為前一層6個特徵,卷積核大小5x5,卷積核種類16
self.conv2 = nn.Conv2d(6, 16, 5)
# 28.定義⑤的全連結層,輸入為16*5*5,輸出為120
self.fc1 = nn.Linear(16 * 5 * 5, 120) # 6*6 from image dimension
# 29.定義⑥的全連接層,輸入為120,輸出為84
self.fc2 = nn.Linear(120, 84)
# 30.定義⑥的全連接層,輸入為84,輸出為10
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# 31.完成input-S2,先卷積+relu,再2x2下採樣
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# 32.完成S2-S4,先卷積+relu,再2x2下採樣
x = F.max_pool2d(F.relu(self.conv2(x)), 2) #卷積核方形時,可以只寫一個維度
# 33.將特徵向量扁平成列向量
x = x.view(-1, 16 * 5 * 5)
# 34.使用fc1+relu
x = F.relu(self.fc1(x))
# 35.使用fc2+relu
x = F.relu(self.fc2(x))
# 36.使用fc3
x = self.fc3(x)
return x
net = Net()
print(net)
37.列印網絡的參數
params = list(net.parameters())
# print(params)
print(len(params))
38.列印某一層參數的形狀
print(params[0].size())
39.隨機輸入一個向量,查看前向傳播輸出
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
40.將梯度初始化
net.zero_grad()
41.隨機一個梯度進行反向傳播
out.backward(torch.randn(1, 10))
42.用自帶的MSELoss()定義損失函數
criterion = nn.MSELoss()
43.隨機一個真值,並用隨機的輸入計算損失
target = torch.randn(10) # 隨機真值
target = target.view(1, -1) # 變成列向量
output = net(input) # 用隨機輸入計算輸出
loss = criterion(output, target) # 計算損失
print(loss)
44.將梯度初始化,計算上一步中loss的反向傳播
net.zero_grad()
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
45.計算43中loss的反向傳播
loss.backward()
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
46.定義SGD優化器算法,學習率設置為0.01
import torch.optim as optim
optimizer = optim.SGD(net.parameters(), lr=0.01)
47.使用優化器更新權重
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
loss.backward()
# 更新權重
optimizer.step()
48.構造一個transform,將三通道(0,1)區間的數據轉換成(-1,1)的數據
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
讀取數據集
trainset = cifar(root = './input/cifar10', segmentation='train', transforms=transform)
testset = cifar(root = './input/cifar10', segmentation='test', transforms=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,shuffle=True, num_workers=2)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
這部分沿用前面的網絡
net2 = Net()
49.定義交叉熵損失函數
criterion2 = nn.CrossEntropyLoss()
50.定義SGD優化器算法,學習率設置為0.001,momentum=0.9
optimizer2 = optim.SGD(net2.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 獲取X,y對
inputs, labels = data
# 51.初始化梯度
optimizer2.zero_grad()
# 52.前饋
outputs = net2(inputs)
# 53.計算損失
loss = criterion2(outputs, labels)
# 54.計算梯度
loss.backward()
# 55.更新權值
optimizer2.step()
# 每2000個數據列印平均代價函數值
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
取一些數據
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
56.使用模型預測
outputs = net2(images)
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
57.在測試集上進行打分
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net2(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
58.保存訓練好的模型
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
59.讀取保存的模型
pretrained_net = torch.load(PATH)
60.加載模型
net3 = Net()
net3.load_state_dict(pretrained_net)
點擊此處查看線上運行效果👇
https://www.kesci.com/home/project/5e0038642823a10036ae9ebf
重磅!
林軒田機器學習完整視頻和博主筆記來啦!
掃描下方二維碼,添加 AI有道小助手微信,可申請入群,並獲得林軒田機器學習完整視頻 + 博主紅色石頭的精煉筆記(一定要備註:入群 + 地點 + 學校/公司。例如:入群+上海+復旦。
長按掃碼,申請入群
(添加人數較多,請耐心等待)
最新 AI 乾貨,我在看