Pyorch基礎:張量

Autograd:Automatic Differentiation

autograd是Pytorch中神經網絡的核心
autograd包對所有在Tensor上的操作提供自動微分。是一個按運行定義的框架。這意味着backprop是由代碼的運行方式定義的,並且每個迭代可以是不同的

Tensor

torch.Tensor是這個包的核心類。

  • .requires_grad=True可以追蹤所有在其的操作。

Pytorch 基礎:張量

import torch
print(torch.__version__)
1.1.0

張量(Tensor)

Pytorch裏基礎運算單位,與Numpy的ndarray相同都是表示一個多維的矩陣。與ndarray的最大區別是,Tensor可以在GPU上運行,而numpy的ndarrary只能在CPU上運行,在GPU上可以加速運算

# 簡單張量
x = torch.randn(2, 2)
x
tensor([[ 0.6559, -0.4488],
        [-0.6773,  0.1955]])
# 查看大小 ,可以使用與numpy相同的shape屬性
x.shape
torch.Size([2, 2])
x.size()
# 也可以使用size()函數
torch.Size([2, 2])

張量(Tensor)是一個定義在一些向量空間和對偶空間的笛卡爾乘積上的多重線性映射,其座標是n維空間內,有n個分量的一種量,其中每個分量都是座標的函數,在座標變換時,這些分量也按照某些規則作線性變化。r稱爲該向量的秩或階

y = torch.rand(2, 3, 4)
y
tensor([[[0.5697, 0.8745, 0.3675, 0.1490],
         [0.0393, 0.9375, 0.8695, 0.9460],
         [0.9790, 0.3922, 0.5406, 0.3504]],

        [[0.5684, 0.1488, 0.7164, 0.7056],
         [0.5746, 0.5168, 0.6269, 0.4023],
         [0.6346, 0.5118, 0.0181, 0.3209]]])

在同構的意義下,第零階張量(r=0)爲標量,第一階張量(r=1)爲向量,第二階張量(r=2)爲矩陣,第三階及以上統稱爲多維向量

# 標量
scalar = torch.tensor(3.1415926)
print(scalar)
print(scalar.size())
tensor(3.1416)
torch.Size([])
# 對於標量可以直接使用.item() 從中取出對應的數值
scalar.item()
3.141592502593994
# 張量中只有一個元素的tensor也可以調用.item()方法
tensor = torch.tensor([3.14159])
print(tensor)
print(tensor.shape)
tensor.item()
tensor([3.1416])
torch.Size([1])





3.141590118408203

基本類型

Tensor的基本數據類型:

  • 32位浮點型:torch.FloatTensor (default)
  • 64位浮點型:torch.DoubleTensor
  • 64位整型:torch.LongTensor
  • 32位整型:torch.IntTensor
  • 16位整型:torch.ShortTensor
  • 除以上數字類型外還有byte和chart型
long = torch.LongTensor()
long
tensor([], dtype=torch.int64)
double = torch.DoubleTensor()
double
tensor([], dtype=torch.float64)
Float = torch.FloatTensor()
Float
tensor([])
short = torch.ShortTensor()
short
tensor([], dtype=torch.int16)
Int = torch.IntTensor()
Int
tensor([], dtype=torch.int32)
char = torch.CharTensor()
char
tensor([], dtype=torch.int8)
bt = torch.ByteTensor()
bt
tensor([], dtype=torch.uint8)

Numpy轉換

使用numpy方法將tensor轉換爲ndarray

a = torch.randn(2, 2)
numpy_a = a.numpy()
numpy_a
array([[-0.04118568,  0.83802617],
       [ 0.19688779, -0.8153309 ]], dtype=float32)
# ndarray轉換位numpy
torch_a = torch.from_numpy(numpy_a)
torch_a
tensor([[-0.0412,  0.8380],
        [ 0.1969, -0.8153]])

Tensor和Numpy對象共享內存,所以轉換他們相互之間轉換很快

設備間轉換

一般使用.cuda方法將tensor移動到gpu

cpu_a = torch.randn(2, 2)
cpu_a.type()
'torch.FloatTensor'
gpu_a = cpu_a.cuda()
print(gpu_a)
print(gpu_a.type())
tensor([[0.8202, 0.8172],
        [0.1292, 2.1433]], device='cuda:0')
torch.cuda.FloatTensor
# 使用.cpu將tensor移動到cpu
cpu_b = gpu_a.cpu()
cpu_b.type()
'torch.FloatTensor'

如果有多GPU可用,可使用to方法確定使用設備

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
gpu_b=cpu_b.to(device)
gpu_b.type()
cuda





'torch.cuda.FloatTensor'

初始化

Pytorch中有許多初始化的方法

# 使用[0, 1]均勻分佈初始化數組
rand = torch.rand(3, 2)
rand
tensor([[0.5435, 0.6259],
        [0.8157, 0.4474],
        [0.6790, 0.9695]])
# 使用0填充
zero = torch.zeros(2, 2)
zero
tensor([[0., 0.],
        [0., 0.]])
# 使用1填充
one = torch.ones(2, 2)
one
tensor([[1., 1.],
        [1., 1.]])
# 初始化單位矩陣(對角線爲1,其餘爲0)
eye = torch.eye(2, 2)
eye
tensor([[1., 0.],
        [0., 1.]])

Pytorch中對張量的操作類似Numpy操作

x = torch.randn(2, 2)
x
tensor([[ 1.1412, -1.0689],
        [-0.1724, -0.6650]])
# 最大值, 沿行取 指定 dim=0/1
max_value = torch.max(x)
max_value
tensor(1.1412)
# 求和
sum_x = torch.sum(x, dim=1)
sum_x
tensor([ 0.0723, -0.8374])
y = torch.randn(2, 2)
z = x + y 
z
tensor([[ 2.0838, -0.6529],
        [ 1.5526, -0.9550]])
# 以_結尾的方法,均會改變調用的值
x.add_(y)
tensor([[ 2.0838, -0.6529],
        [ 1.5526, -0.9550]])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章