使用Pytorch進(jìn)行深度學(xué)習(xí)谆扎,60分鐘閃電戰(zhàn)
本次課程的目標(biāo):
- 從更高水平理解Pytorch的Tensor(張量)和神經(jīng)網(wǎng)絡(luò)
- 訓(xùn)練一個小的圖像分類神經(jīng)網(wǎng)絡(luò)
注意確定已經(jīng)安裝了torch和torchvision
什么是Pytorch
Pytorch是一個針對兩類受眾的科學(xué)計算包
- Numpy替代挂捅,可以使用GPU
- 深度學(xué)習(xí)研究平臺,提供靈活性和速度
開始
Tensors(張量)
張量和Numpy的ndarrays類似燕酷,此外籍凝,張量還可以應(yīng)用于GPU加速計算。以下是幾個常用的方法
生成一個(5,3)的0張量和一個(5,3)的隨機(jī)張量
from __future__ import print_function
import torch
x = torch.empty(5, 3)
print('x=',x)
y = torch.rand(5, 3)
print('y=',y)
x= tensor(1.00000e-43 *
[[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 7.3989, 0.0000],
[ 0.0000, 0.0000, 0.0000]])
y= tensor([[ 0.9796, 0.0775, 0.3972],
[ 0.5790, 0.8416, 0.7846],
[ 0.8820, 0.8076, 0.9701],
[ 0.6431, 0.1062, 0.0848],
[ 0.0472, 0.7201, 0.4488]])
生成shape為(5,3)苗缩,由0填充,類型為long的張量
a= torch.zeros(5,3,dtype=torch.long)
print('a=',a)
a= tensor([[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]])
直接從數(shù)據(jù)構(gòu)建張量
# b=torch.tensor([5.6,3])
b=torch.tensor(5.6)
print('b=',b)
獲取張量的大小声诸,注意size()生成的是一個tuple類型數(shù)據(jù)酱讶,支持所有tuple操作。
size= x.size()
print(size)
張量的運(yùn)算彼乌,可以直接相加泻肯,也可以使用torch.add()等方法渊迁。
需要resize和reshape張量的時候,可以使用torch.view()
c=torch.randn(4,4)
d=c.view(16)
e=c.view(-1,8)
print(c.size(),d.size(),e.size())
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
如果有一個元素張量灶挟,使用.item()可以將值作為Python數(shù)字
x=torch.randn(1)
print(x)
print(x.item())
tensor([-0.9725])
-0.9725168943405151
Numpy橋
將一個Torch的張量轉(zhuǎn)為Numpy的array琉朽,同理也可以轉(zhuǎn)回來。torch張量和Numpy的array共享同一個記憶地址稚铣,改變一個就會改變另一個箱叁。
h=torch.ones(5)
print(h)
i=h.numpy()
print(i)
tensor([ 1., 1., 1., 1., 1.])
[1. 1. 1. 1. 1.]
CUDA張量
張量可以移動到任何硬件,通過使用.to方法
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))
x= tensor([[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.1691, 0.0000]])
y= tensor([[ 0.5423, 0.4364, 0.6140],
[ 0.9988, 0.3274, 0.4991],
[ 0.1386, 0.8057, 0.3958],
[ 0.4735, 0.1752, 0.5884],
[ 0.8408, 0.0302, 0.3169]])
a= tensor([[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0],
[ 0, 0, 0]])