# 創建未初始化的Tensorx = torch.empty(5,3)print(x)x = torch.rand(5,3)print(x)x = torch.zeros(5,3,dtype=torch.long)print(x)# 根據數據創建Tensorx = torch.tensor([5.5,3])print(x)# 修改原Tensor為全1的Tensorx = x.new_ones(5,3,dtype=torch.float64)print(x)
# 修改數據類型x = torch.rand_like(x,dtype=torch.float64)print(x)print(x.size())print(x.shape)
這些創建方法都可以在創建的時候指定數據類型dtype和存放device(cpu/gpu)。
1.2.1 算術操作
在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)我們還可以使⽤類似NumPy的索引操作來訪問 Tensor 的一部分,需要注意的是:索引出來的結果與原數據共享內存,也即修改⼀個,另⼀個會跟著修改。
y = x[0,:]y += 1print(y)print(x[0,:]) # 觀察x是否改變了1.2.3 改變形狀
注意 view() 返回的新tensor與源tensor共享內存(其實是同⼀個tensor),也即更改其中的⼀個,另 外⼀個也會跟著改變。(顧名思義,view僅是改變了對這個張量的觀察角度)
y = x.view(15)z = x.view(-1,5) print(x.size(),y.size(),z.size())所以如果我們想返回⼀個真正新的副本(即不共享內存)該怎麼辦呢?Pytorch還提供了⼀ 個 reshape() 可以改變形狀,但是此函數並不能保證返回的是其拷貝,所以不推薦使用。推薦先 ⽤ clone 創造一個副本然後再使⽤ view 。
x_cp = x.clone().view(15)x -= 1print(x)print(x_cp)另外⼀個常用的函數就是 item() , 它可以將⼀個標量 Tensor 轉換成⼀個Python
number:x = torch.randn(1)print(x)print(x.item())
1.2.4 線性代數
官方文檔:https://pytorch.org/docs/stable/torch.html1.3 廣播機制
前⾯我們看到如何對兩個形狀相同的 Tensor 做按元素運算。當對兩個形狀不同的 Tensor 按元素運算時,可能會觸發廣播(broadcasting)機制:先適當複製元素使這兩個 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相互轉化
我們很容易⽤ numpy() 和 from_numpy() 將 Tensor 和NumPy中的數組相互轉換。但是需要注意的⼀點是:這兩個函數所產生的的 Tensor 和NumPy中的數組共享相同的內存(所以他們之間的轉換很快),改變其中⼀個時另⼀個也會改變!!!
a = torch.ones(5)b = a.numpy()print(a,b)使⽤ from_numpy() 將NumPy數組轉換成 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 object y = torch.ones_like(x, device=device) # directly create a tensor on GPU x = x.to(device) # or just use strings ``.to("cuda")`` z = x + y print(z) print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!二、自動求梯度(非常重要)
很多人看到這裡是懵的,因為為什麼會得出導數的結果,在這裡我給出自動求導的一些原理性的知識,希望能幫助大家更好的學習pytorch這個重要的框架。該autograd軟體包是PyTorch中所有神經網絡的核心。讓我們首先簡要地訪問它,然後我們將去訓練我們的第一個神經網絡。該autograd軟體包可自動區分張量上的所有操作。這是一個按運行定義的框架,這意味著您的backprop是由代碼的運行方式定義的,並且每次迭代都可以不同。如果想了解數值微分數值積分和自動求導的知識,可以查看邱錫鵬老師的《神經網絡與深度學習》第四章第五節:下載地址:https://nndl.github.io/在 處的導數。我們的做法是利用鏈式法則分解為一系列的操作:
2.1 張量及張量的求導(Tensor)
# 加入requires_grad=True參數可追蹤函數求導x = torch.ones(2,2,requires_grad=True)print(x)print(x.grad_fn)# 進行運算y = x + 2print(y)print(y.grad_fn) # 創建了一個加法操作<AddBackward0 object at 0x0000017AF2F86EF0>像x這種直接創建的稱為葉子節點,葉子節點對應的 grad_fn 是 None 。
print(x.is_leaf,y.is_leaf)z = y * y * 3out = z.mean()print(z,out).requires_grad_( ... )改變requires_grad 的屬性。a = torch.randn(2,2) # 缺失情況下默認 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)現在讓我們反向傳播:因為out包含單個標量,out.backward()所以等效於out.backward(torch.tensor(1.))。
out.backward()print(x.grad)out2 = x.sum()out2.backward()print(x.grad)
out3 = x.sum()x.grad.data.zero_()out3.backward()print(x.grad)
三、神經網絡設計的pytorch版本這是一個簡單的前饋網絡。它獲取輸入,將其一層又一層地饋入,然後最終給出輸出。神經網絡的典型訓練過程如下:3.1 定義網絡import torchimport torch.nn as nnimport torch.nn.functional as F
class Net(nn.Module):
def __init__(self): super(Net,self).__init__() # 1 input image channel, 6 output channels, 3x3 square convolution # kernel self.conv1 = nn.Conv2d(1,6,3) self.conv2 = nn.Conv2d(6,16,3) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16*6*6,120) # 6*6 from image dimension self.fc2 = nn.Linear(120,84) self.fc3 = nn.Linear(84,10)
def forward(self,x): # Max pooling over a (2, 2) window x = 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 x
def num_flat_features(self,x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s print(num_features) return num_features
net = Net()print(net)# 模型的可學習參數由返回 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)# 用隨機梯度將所有參數和反向傳播器的梯度緩衝區歸零: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屬性的屬性向後移動,可查看網絡結構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實踐中使用的最簡單的更新規則是隨機梯度下降(SGD):weight = weight - learning_rate * gradient
import torch.optim as optim
optimizer = optim.SGD(net.parameters(),lr = 0.01)
optimizer.zero_grad() output = net(input)loss = criterion(output,target)loss.backward()optimizer.step()576
四、寫到最後
今天,要講的Pytorch基礎教程到這裡就結束了,相信大家通過上邊的學習已經對Pytorch基礎教程有了初步的了解。關於Pytorch的項目實踐,阿里天池「零基礎入門NLP」學習賽中提供了Pytorch版實踐教程,供學習參考(閱讀原文直接跳轉):
https://tianchi.aliyun.com/competition/entrance/531810/forum獲取一折本站知識星球優惠券,複製連結直接打開:
https://t.zsxq.com/yFQV7am
本站qq群1003271085。
加入微信群請掃碼進群: