pytorch是類似tensorflow的一種深度學習科學計算包,它具有以下的特點:
- numpy的替代品,可以利用gpu的性能進行計算。
- 深度學習研究平臺具有足夠的靈活性和速度。
Tensor(張量)
tensor類似numpy的ndarrays,同時tensor可以使用gpu進行計算,但是numpy是只能在cpu上進行計算。
首先導入pytorch包
import torch
很簡單,有木有。
構造一個5*3的矩陣,不初始化
x = torch.empty(5, 3)
print(x)
輸出
tensor(1.00000e-04 *
[[-0.0000, 0.0000, 1.5135],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000],
[ 0.0000, 0.0000, 0.0000]])
構造一個隨機初始化的矩陣
x = torch.rand(5, 3)
print(x)
輸出
tensor([[ 0.6291, 0.2581, 0.6414],
[ 0.9739, 0.8243, 0.2276],
[ 0.4184, 0.1815, 0.5131],
[ 0.5533, 0.5440, 0.0718],
[ 0.2908, 0.1850, 0.5297]])
構造一個矩陣全爲0, 而且數據類型是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]])
構造一個張量,直接使用數據:
x = torch.sensor([5.5, 3])
print(x)
輸出
tensor([ 5.5000, 3.0000])
創建一個tensor基於已經存在的tensor
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float)
print(x)
輸出
tensor([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]], dtype=torch.float64)
tensor([[-0.2183, 0.4477, -0.4053],
[ 1.7353, -0.0048, 1.2177],
[-1.1111, 1.0878, 0.9722],
[-0.7771, -0.2174, 0.0412],
[-2.1750, 1.3609, -0.3322]])
獲取它的維度信息
print(x.size()
輸出
torch.Size([5, 3])
注意: torch.Size是一個元組,所以它支持左右的元組操作。
操作
在接下來的例子中,我們會學到加法操作。
加法方式一
y = torch.rand(5, 3)
print(x + y)
輸出
tensor([[-0.1859, 1.3970, 0.5236],
[ 2.3854, 0.0707, 2.1970],
[-0.3587, 1.2359, 1.8951],
[-0.1189, -0.1376, 0.4647],
[-1.8968, 2.0164, 0.1092]])
加法方式二
print(torch.add(x, y))
輸出
tensor([[-0.1859, 1.3970, 0.5236],
[ 2.3854, 0.0707, 2.1970],
[-0.3587, 1.2359, 1.8951],
[-0.1189, -0.1376, 0.4647],
[-1.8968, 2.0164, 0.1092]])
加法:提供一個輸出tensor作爲參數
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)
輸出
tensor([[-0.1859, 1.3970, 0.5236],
[ 2.3854, 0.0707, 2.1970],
[-0.3587, 1.2359, 1.8951],
[-0.1189, -0.1376, 0.4647],
[-1.8968, 2.0164, 0.1092]])
加法:in-place
y.add_(x)
print(y)
輸出
tensor([[-0.1859, 1.3970, 0.5236],
[ 2.3854, 0.0707, 2.1970],
[-0.3587, 1.2359, 1.8951],
[-0.1189, -0.1376, 0.4647],
[-1.8968, 2.0164, 0.1092]])
注意:任何使張量會發生變化的操作都有一個前綴 _ 。例如:x.copy_(y), x.t_()
,將會改變x。
索引操作
可以使用標準的numpy類似的索引操作
print(x[:, 1])
輸出
tensor([ 0.4477, -0.0048, 1.0878, -0.2174, 1.3609])
改變大小操作
可以使用torch.view改變一個tensor的大小和形狀
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())
輸出
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
獲取tensor的value
可以使用.item()來獲取這個value
x = torch.randn(1)
print(x)
print(x.item())
輸出
tensor([ 0.9422])
0.9422121644020081