什么是pytorch?
PyTorch即 Torch 的 Python 版本。Torch 是由 Facebook 發(fā)布的深度學(xué)習(xí)框架,因支持動態(tài)定義計算圖,相比于 Tensorflow 使用起來更為靈活方便,特別適合中小型機(jī)器學(xué)習(xí)項目和深度學(xué)習(xí)初學(xué)者。但因為 Torch 的開發(fā)語言是Lua,導(dǎo)致它在國內(nèi)一直很小眾。所以,在千呼萬喚下,PyTorch應(yīng)運(yùn)而生!PyTorch 繼承了 Troch 的靈活特性,又使用廣為流行的 Python 作為開發(fā)語言,所以一經(jīng)推出就廣受歡迎!
PyTorch是基于python的科學(xué)計算包,與numpy類似,但又能利用GPU來加速計算。
- Tensors
創(chuàng)建一個5×3未初始化的矩陣
import torch
x = torch.Tensor(5,3)
print (x)
結(jié)果:
1.00000e-37 *
8.4745 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.0000
[torch.FloatTensor of size 5x3]
創(chuàng)建一個5×3隨機(jī)初始化的矩陣
import torch
x = torch.rand(5,3)
print (x)
--------------------------------
0.8031 0.4576 0.2146
0.0219 0.8962 0.9953
0.6851 0.8307 0.0741
0.4235 0.4125 0.7773
0.4069 0.5352 0.9514
[torch.FloatTensor of size 5x3]
獲取其大小size
print (x.size())
輸出torch.size([5,3])
- operations
對于torch的運(yùn)算操作有多種語法,比如來看Add操作
1.直接相加
y = torch.rand(5, 3)
print(x + y)
2.使用add()加法函數(shù)
print(torch.add(x, y))
3 .給出一個輸出張量
result = torch.Tensor(5, 3)
torch.add(x, y, out=result)
print(result)
4.替換(in-place)
# adds x to y
y.add_(x)
print(y)