1.Pytorch與張量
%matplotlib inline
2.PyTorch是什么
PyTorch是一個(gè)基于Torch的Python開源機(jī)器學(xué)習(xí)庫(kù),用于深度學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)構(gòu)建AI應(yīng)用程序。 它主要由Facebook的人工智能研究小組開發(fā)。Uber的"Pyro"也是使用的這個(gè)庫(kù)。
PyTorch是一個(gè)Python包,提供兩個(gè)高級(jí)功能:
- 具有強(qiáng)大的GPU加速的張量計(jì)算(如NumPy),可以使用GPU的強(qiáng)大計(jì)算能力
- 包含自動(dòng)求導(dǎo)系統(tǒng)的的深度神經(jīng)網(wǎng)絡(luò)
2.1 開始
2.1.1 Tensors(張量)
Tensors與Numpy中的 ndarrays類似,但是在PyTorch中
Tensors 可以使用GPU進(jìn)行計(jì)算.
神經(jīng)網(wǎng)絡(luò)其實(shí)底層就是很多的tensor計(jì)算


from __future__ import print_function
import torch
創(chuàng)建一個(gè)5*3的矩陣 但并未初始化
x = torch.empty(5,3)
print(x)

創(chuàng)建一個(gè)隨機(jī)初始化矩陣
x = torch.rand(5,3)
print(x)

創(chuàng)建一個(gè)0填充的矩陣,數(shù)據(jù)類型為long:
x = torch.zeros(5,3,dtype = torch.long)
print(x)

創(chuàng)建tensor并使用現(xiàn)有數(shù)據(jù)初始化
x = torch.tensor([5.5 , 3])
print(x)

根據(jù)現(xiàn)有的張量創(chuàng)建矩陣。這些方法將重用輸入張量的屬性,例如 dtype,除非設(shè)置新的值進(jìn)行覆蓋
x = x.new_ones(5,3 , dtype = torch.double) #new_*方法創(chuàng)建對(duì)象
print(x)
x = torch.randn_like(x , dtype = torch.float) #覆蓋 dtype
print(x) #對(duì)象的size是相同的,知識(shí)值和類型發(fā)生了變化

獲取 size
使用size方法與Numpy的shape屬性返回的相同,張量也支持shape屬性,后面會(huì)詳細(xì)介紹
print(x.size())

torch.Size 返回值是 tuple類型, 所以它支持tuple類型的所有操作.
操作
操作有多種語(yǔ)法。
我們將看一下加法運(yùn)算。
加法1:
y = torch.rand(5,3)
print(x +y)

加法2:
print(torch.add(x,y))

提供輸出tensor作為參數(shù)
result = torch.empty(5,3)
torch.add(x , y , out=result)
print(result)

替換
#add x to y
y.add(x)
print(y)

任何以"" 結(jié)尾的操作都會(huì)用結(jié)果替換原變量,例如:"x.copy(y)" , "x.t_()" , 都會(huì)改變"x"
你可以使用與Numpy索引方式相同的操作來(lái)進(jìn)行對(duì)張量的操作
print(x[: , 1])

torch.view: 可以改變張量的維度和大小
torch.view 與Numpy 的reshape類似
x = torch.randn(4,4)
y = x.view(16)
z = x.view(-1,8) #size -1 從其他維度推斷
print(x.size() , y.size() , z.size())

如果你有只有一個(gè)元素的張量,使用 .item來(lái)得到Python數(shù)據(jù)類型的數(shù)值
x = torch.randn(1)
print(x)
print(x.item())

2.2Numpy轉(zhuǎn)換
Converting a Torch Tensor to a NumPy array and vice versa is a breeze.
The Torch Tensor and NumPy array will share their underlying memory
locations, and changing one will change the other.
Converting a Torch Tensor to a NumPy Array
a = torch.ones(5)
print(a)

b = a.numpy()
print(b)

See how the numpy array changed in value.
a.add_(1)
print(a)
print(b)

NumPy Array 轉(zhuǎn)化成 Torch Tensor
使用from_numpy自動(dòng)轉(zhuǎn)化
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out= a)
print(a)
print(b)

所有的Tensor 類型默認(rèn)都是基于CPU , CharTensor 類型不支持到Numpy的轉(zhuǎn)換
2.3 CUDA張量
使用.to方法,可以將Tensor移動(dòng)到任何設(shè)備中
# is_available 函數(shù)判斷是否有cuda可以使用
# ``torch.device``將張量移動(dòng)到指定的設(shè)備中
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA 設(shè)備對(duì)象
y = torch.ones_like(x, device=device) # 直接從GPU創(chuàng)建張量
x = x.to(device) # 或者直接使用``.to("cuda")``將張量移動(dòng)到cuda中
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` 也會(huì)對(duì)變量的類型做更改
