深度學(xué)習(xí)之Pytorch基礎(chǔ)教程!
每日干貨?&?每月組隊學(xué)習(xí),不錯過
作者:李祖賢,Datawhale高校群成員,深圳大學(xué)


一、數(shù)據(jù)操作
import torch# 創(chuàng)建未初始化的Tensorx = torch.empty(5,3)print(x)

# 創(chuàng)建隨機初始化的Tensorx = torch.rand(5,3)print(x)

# 創(chuàng)建全為0的Tensorx = torch.zeros(5,3,dtype=torch.long)print(x)

# 根據(jù)數(shù)據(jù)創(chuàng)建Tensorx = torch.tensor([5.5,3])print(x)

# 修改原Tensor為全1的Tensorx = x.new_ones(5,3,dtype=torch.float64)print(x)# 修改數(shù)據(jù)類型x = torch.rand_like(x,dtype=torch.float64)print(x)

# 獲取Tensor的形狀print(x.size())print(x.shape)# 注意:返回的torch.Size其實就是?一個tuple, ?支持所有tuple的操作。


這些創(chuàng)建方法都可以在創(chuàng)建的時候指定數(shù)據(jù)類型dtype和存放device(cpu/gpu)。
1.2.1 算術(shù)操作
在PyTorch中,同?種操作可能有很多種形式,下?面?用加法作為例子。
# 形式1:y = torch.rand(5,3)print(x+y)

# 形式2print(torch.add(x,y))# 還可以指定輸出result = torch.empty(5, 3)torch.add(x, y, out=result)print(result)

# 形式3y.add_(x)print(y)

我們還可以使?類似NumPy的索引操作來訪問 Tensor 的一部分,需要注意的是:索引出來的結(jié)果與原數(shù)據(jù)共享內(nèi)存,也即修改?個,另?個會跟著修改。
y = x[0,:]y += 1print(y)print(x[0,:]) # 觀察x是否改變了

1.2.3 改變形狀
注意 view() 返回的新tensor與源tensor共享內(nèi)存(其實是同?個tensor),也即更改其中的?個,另 外?個也會跟著改變。(顧名思義,view僅是改變了對這個張量的觀察角度)
y = x.view(15)z = x.view(-1,5) # -1所指的維度可以根據(jù)其他維度的值推出來print(x.size(),y.size(),z.size())

x += 1print(x)print(y)

所以如果我們想返回?個真正新的副本(即不共享內(nèi)存)該怎么辦呢?Pytorch還提供了? 個 reshape() 可以改變形狀,但是此函數(shù)并不能保證返回的是其拷貝,所以不推薦使用。推薦先 ? clone 創(chuàng)造一個副本然后再使? view 。
x_cp = x.clone().view(15)x -= 1print(x)print(x_cp)

另外?個常用的函數(shù)就是 item() , 它可以將?個標(biāo)量 Tensor 轉(zhuǎn)換成?個Python
number:x = torch.randn(1)print(x)print(x.item())


1.2.4 線性代數(shù)
1.3 廣播機制
前?我們看到如何對兩個形狀相同的 Tensor 做按元素運算。當(dāng)對兩個形狀不同的 Tensor 按元素運算時,可能會觸發(fā)廣播(broadcasting)機制:先適當(dāng)復(fù)制元素使這兩個 Tensor 形狀相同后再按元素運算。例如:
x = torch.arange(1,3).view(1,2)print(x)y = torch.arange(1,4).view(3,1)print(y)print(x+y)

1.4 Tensor和Numpy相互轉(zhuǎn)化
我們很容易? numpy() 和 from_numpy() 將 Tensor 和NumPy中的數(shù)組相互轉(zhuǎn)換。但是需要注意的?點是:這兩個函數(shù)所產(chǎn)生的的 Tensor 和NumPy中的數(shù)組共享相同的內(nèi)存(所以他們之間的轉(zhuǎn)換很快),改變其中?個時另?個也會改變?。?!
a = torch.ones(5)b = a.numpy()print(a,b)

a += 1print(a,b)

b += 1print(a,b)

使? from_numpy() 將NumPy數(shù)組轉(zhuǎn)換成 Tensor :
import numpy as npa = np.ones(5)b = torch.from_numpy(a)print(a,b)

a += 1print(a,b)b += 1print(a,b)

1.5 GPU運算
# let us run this cell only if CUDA is available# We will use ``torch.device`` objects to move tensors in and out of GPUif torch.cuda.is_available():device = torch.device("cuda") # a CUDA device objecty = torch.ones_like(x, device=device) # directly create a tensor on GPUx = x.to(device) # or just use strings ``.to("cuda")``z = x + yprint(z)print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!

二、自動求梯度(非常重要)
?
?
?處的導(dǎo)數(shù)。我們的做法是利用鏈?zhǔn)椒▌t分解為一系列的操作:


2.1 張量及張量的求導(dǎo)(Tensor)
# 加入requires_grad=True參數(shù)可追蹤函數(shù)求導(dǎo)x = torch.ones(2,2,requires_grad=True)print(x)print(x.grad_fn)

# 進行運算y = x + 2print(y)print(y.grad_fn) # 創(chuàng)建了一個加法操作

像x這種直接創(chuàng)建的稱為葉子節(jié)點,葉子節(jié)點對應(yīng)的 grad_fn 是 None 。
print(x.is_leaf,y.is_leaf)
# 整點復(fù)雜的操作z = y * y * 3out = z.mean()print(z,out)

a = torch.randn(2,2) # 缺失情況下默認(rèn) requires_grad = Falsea = ((a*3)/(a-1))print(a.requires_grad) # Falsea.requires_grad_(True)print(a.requires_grad)b = (a*a).sum()print(b.grad_fn)

現(xiàn)在讓我們反向傳播:因為out包含單個標(biāo)量,out.backward()所以等效于out.backward(torch.tensor(1.))。
out.backward()print(x.grad)

# 再來反向傳播?次,注意grad是累加的out2 = x.sum()out2.backward()print(x.grad)out3 = x.sum()x.grad.data.zero_()out3.backward()print(x.grad)

定義具有一些可學(xué)習(xí)參數(shù)(或權(quán)重)的神經(jīng)網(wǎng)絡(luò)
遍歷輸入數(shù)據(jù)集
通過網(wǎng)絡(luò)處理輸入
計算損失(輸出正確的距離有多遠)
將梯度傳播回網(wǎng)絡(luò)參數(shù)
通常使用簡單的更新規(guī)則來更新網(wǎng)絡(luò)的權(quán)重:weight = weight - learning_rate * gradient

import torchimport torch.nn as nnimport?torch.nn.functional?as?Fclass Net(nn.Module):def __init__(self):super(Net,self).__init__()# 1 input image channel, 6 output channels, 3x3 square convolution# kernelself.conv1 = nn.Conv2d(1,6,3)self.conv2 = nn.Conv2d(6,16,3)# an affine operation: y = Wx + bself.fc1 = nn.Linear(16*6*6,120) # 6*6 from image dimensionself.fc2 = nn.Linear(120,84)self.fc3 = nn.Linear(84,10)def forward(self,x):# Max pooling over a (2, 2) windowx = F.max_pool2d(F.relu(self.conv1(x)),(2,2)) # CLASStorch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)x = F.max_pool2d(F.relu(self.conv2(x)),2)x = x.view(-1,self.num_flat_features(x))x = F.relu(self.fc1(x))x = F.relu(self.fc2(x))x = self.fc3(x)return xdef num_flat_features(self,x):size = x.size()[1:] # all dimensions except the batch dimensionnum_features = 1for s in size:num_features *= sprint(num_features)return num_featuresnet = Net()print(net)

# 模型的可學(xué)習(xí)參數(shù)由返回 net.parameters()params = list(net.parameters())print(len(params))print(params[0].size()) # conv1's .weight

# 嘗試一個32x32隨機輸入input = torch.randn(1,1,32,32)out = net(input)print(out)

# 用隨機梯度將所有參數(shù)和反向傳播器的梯度緩沖區(qū)歸零:net.zero_grad()out.backward(torch.randn(1,10))
output = net(input)target = torch.randn(10) # a dummy target, for exampletarget = target.view(-1,1) # # make it the same shape as outputcriterion = nn.MSELoss()loss = criterion(output,target)print(loss)


# 如果loss使用.grad_fn屬性的屬性向后移動,可查看網(wǎng)絡(luò)結(jié)構(gòu)print(loss.grad_fn) # MSELossprint(loss.grad_fn.next_functions[0][0]) # Linearprint(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU

weight = weight - learning_rate * gradient
import torch.optim as optim# create your optimizeroptimizer = optim.SGD(net.parameters(),lr = 0.01)# in your training loop:optimizer.zero_grad() # zero the gradient buffersoutput = net(input)loss = criterion(output,target)loss.backward()optimizer.step()
576
四、寫到最后
關(guān)于Pytorch的項目實踐,阿里天池「零基礎(chǔ)入門NLP」學(xué)習(xí)賽中提供了Pytorch版實踐教程,供學(xué)習(xí)參考(閱讀原文直接跳轉(zhuǎn)):
“整理不易,點贊三連↓
