Deep Learning with PyTorch: A 60 Minute Blitz
作者: Soumith Chintala
部分翻譯:me
本內容包含:
- 在高級層面理解pytorch的tensor庫以及神經網絡。
- 訓練一個用於圖像分類的小的神經網絡。
This tutorial assumes that you have a basic familiarity of numpy
閱讀本文前,你需要具有numpy的知識。
當然需要安裝好pytorch和torchvision庫。
開始
張量
張量類似於 NumPy的N維數組, 添加了可以在GPU上進行加速計算。
from __future__ import print_function
import torch
構建一個5*3的矩陣,沒有初始化:
x = torch.empty(5, 3) #全部都是0.0
print(x)
print(x.dtype) #數據類型 float32
print(type(x))
tensor([[0.0000e+00, 0.0000e+00, 0.0000e+00], [0.0000e+00, 0.0000e+00, 0.0000e+00], [0.0000e+00, 0.0000e+00, 0.0000e+00], [0.0000e+00, 1.5190e-42, 0.0000e+00], [0.0000e+00, 1.1628e+27, 0.0000e+00]]) torch.float32 <class 'torch.Tensor'>
構建一個隨機的矩陣
x = torch.rand(5, 3)
print(x)
tensor([[0.5689, 0.6057, 0.5855], [0.4125, 0.2739, 0.7563], [0.8674, 0.7034, 0.5811], [0.9939, 0.5941, 0.6916], [0.9194, 0.8064, 0.3800]])
構建一個填充為零的矩陣和類型為長整型(long):
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
直接從數據構建一個Tensor:
x = torch.tensor([5.5, 3])
print(x)
或者基於現有的張量創建一個新的。這些方法會復用輸入張量的性質,例如:dtype,除非一個新的值提供給用戶。
print(x)
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes #這個搞不懂不建議
print(x)
x = torch.randn_like(x, dtype=torch.float) # override dtype! #產生同樣類型的建議使用torch.randn_like, torch.ones_like(tensor)
print(x)
獲取張量的大小:
print(x.size())
h,w=x.size()
print(h,w)
torch.Size([5, 3])
5 3
注意:torch.Size實際上是一個元組
, 所以支持所有元組的操作。.
運算
運算有多種語法格式。在下面的例子里,我們看加法運算。
加法運算的語法1:
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print(x + y)
tensor([[-0.3402, 0.4303, 0.7074], [ 0.4024, 1.4834, -0.7325], [ 0.4572, 1.8391, -0.0452], [ 1.2108, 0.9043, 0.6351], [-0.6921, 0.9278, 2.4968]])
加法運算的語法2:
print(torch.add(x, y))
tensor([[-0.3402, 0.4303, 0.7074], [ 0.4024, 1.4834, -0.7325], [ 0.4572, 1.8391, -0.0452], [ 1.2108, 0.9043, 0.6351], [-0.6921, 0.9278, 2.4968]])
把結果作為參數:
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
加法:直接加到某參數:
# adds x to y
y.add_(x)
print(y)
注意:任何以“_”結尾的運算,都會改變張量自身。例如: x.copy_(y)
, x.t_()
, 將會改變 x
.
可以使用NUmpy里的切片方法對Tensor切片!
print(x[:, 1])
縮放:如果你想對張量縮放/改變維度,可以使用torch.view:
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())
v=x.view(-1) #-1直接把他拉直了。
print(v.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8]) torch.Size([16])
如果你有一個元素的張量,使用.item() 方法來得到其Python自身的數值類型。
x = torch.randn(1)
print(x)
print(x.item())
print(x[0])
print(x[0].item())
tensor([0.4783]) 0.4782998859882355 tensor(0.4783) 0.4782998859882355
后續閱讀:
torch有100+ 個張量運算符, 包括轉置,切片,數學運算,線性代數,隨機數,等,參見: https://pytorch.org/docs/stable/torch.html
連接NumPy
在numpy的數組和torch的tensor 間的轉換非常容易。
torch的tensor和numpy的數組共享內部的存儲單元,改變一個,另一個也改變。例子:
將Torch 張量轉為一個Numpy數組
a = torch.ones(5) print(a)
Out:
tensor([1., 1., 1., 1., 1.])
b = a.numpy() print(b)
Out:
[1. 1. 1. 1. 1.]
可以看到數組里的值發生變換了,也就說一個張量和與之對應的numpy數組是共享內存的:
a.add_(1) print(a) print(b)
Out:
tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
將 NumPy 數組to Torch 張量
例子:
import numpy as np a = np.ones(5) b = torch.from_numpy(a) np.add(a, 1, out=a) print(a) print(b)
Out:
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
除CharTensor外,所有CPU上的張量支持與numpy 數組間的轉換。
CUDA 張量
張量可以被移動到任何設備上,通過.to方法。
# let us run this cell only if CUDA is available 檢測CUDA是否可用
# We will use ``torch.device`` objects to move tensors in and out of GPU 可以使用torch.device對象來移動對象 if 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!
Out:
tensor([2.9218], device='cuda:0')
tensor([2.9218], dtype=torch.float64)
這里注意的是torch.cuda.is_available() torch.device('cuda') device參數,.to(device)