Tensor是一種特殊的資料結構,非常類似于陣列和矩陣,在PyTorch中,我們使用tensor編碼模型的輸入和輸出,以及模型的引數,
Tensor類似于Numpy的ndarrays,除了tensor能在GPUs或其它硬體加速器上運行,事實上,tensor和NumPy陣列可以共享相同的底層記憶體,而不需要拷貝資料(see Bridge with NumPy),Tensor還被優化用于自動微分(Autograd),如果你熟悉ndarray,那么你也將對Tensor API也很熟悉,如果不是,跟著學吧!
import torch
import numpy as np
初始化Tensor
Tensor初始化有多種方式,查看下面的例子,
直接從資料初始化
Tensor可以直接利用data創建,資料型別是自動判斷的,
data = https://www.cnblogs.com/DeepRS/archive/2022/01/25/[[1, 2], [3, 4]]
x_data = torch.tesnor(data)
從Numpy array初始化
Tensor可以從NumPy array初始化,反之亦可,見Bridge with NumPy
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
從另一個tensor初始化
新的tensor保留引數tensor的屬性(shape, datatype),除非明確重寫,
x_ones = torch.ones_like(x_data) # 保留x_data的屬性
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 重寫x_data的資料型別
print(f"Random Tensor: \n {x_rand} \n")
輸出:
Ones Tensor:
tensor([[1, 1],
[1, 1]])
Random Tensor:
tensor([[0.4557, 0.7406],
[0.5935, 0.1859]])
使用隨機值或常數初始化
shape 是表示tensor維度的元組,在下面的函式中,它決定了輸出tensor的維度
shape = (2, 3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeroat32s(shape)
print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
輸出:
Random Tensor:
tensor([[0.8012, 0.4547, 0.4156],
[0.6645, 0.1763, 0.3860]])
Ones Tensor:
tensor([[1., 1., 1.],
[1., 1., 1.]])
Zeros Tensor:
tensor([[0., 0., 0.],
[0., 0., 0.]])
Tensor的屬性
Tensor的屬性描述了它們的shape,datatype,以及保存的硬體
tensor = torch.rand(3, 4)
print(f"Shape of tensor: {tensor.shape}")
print(f"Dataype of tenor: {tensor.dtype}")
print(f"Device tenor is stored on: {tenosr.device}")
輸出:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
Tensor的操作
有超過100種的tensor操作,包括運算、線性代數、矩陣操作(轉置、索引、切片),抽樣,更多有關tensor操作的全面描述見here
每一種操作都可以在GPU(通常速度快于CPU)運行,
默認情況下,tensor是在CPU上創建的,我們需要使用 .to 方法明確地將tensor移動到GPU(在檢查GPU可用后),注意,跨設備復制大型的tensor需要花費大量的時間和記憶體,
# We move our tensor to the GPU if available
if torch.cuda.is_available():
tensor = tensor.to('cuda')
嘗試list的一些操作,如果你熟悉NumPy API,你會發現Tensor API使用也會很容易,
標準的類似于numpy的indexing和slicing
tensor = torch.ones(4, 4)
print('First row: ', tensor[0])
print('First column: ', tensor[:, 0])
print('Last column: ', tenosr[..., -1])
tensor[:, 1] = 0
print(tensor)
輸出:
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor拼接
你可以使用 torch.cat 沿著給定維度拼接一系列的tensor,還有torch.stack,它是另一個tensor拼接操作,與 torch.cat 有細微的差別,
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
輸出:
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])
數學運算
# 計算tensor的矩陣乘法. y1,y2,y3是相同的
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)
y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)
# 逐像素相乘. z1,z2,z3是相同的
z1 = tensor * tensor
z2 = tensor.mul(tensor)
z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)
單元素tensor
如果是單元素tensor,例如把一個tensor的所有值聚合一個,你可以使用 item() 將其轉換成Python數值
12.0 <class 'float'>
In-place operations
In-place operations 會將結果保存到in-place運算元中,它們用下綴 _ 表示,例如: x.copy(), x.t_(),將會改變 x,
print(tensor, '\n')
tensor.add_(5)
print(tensor)
輸出:
tensor([[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.],
[1., 0., 1., 1.]])
tensor([[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.],
[6., 5., 6., 6.]])
注意:In-place操作節約記憶體,但是在計算導數時可能會出問題,因為會立即丟失歷史值,因此,不推薦使用,
Bridge with NumPy
CPU上的Tensor和NumPy陣列共享底層記憶體位置,改變其中一個將改變另一個,
Tensor to NumPy array
t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"t: {n}")
輸出:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]
在tensor上發生的改變將會反應在NumPy陣列上,
t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
輸出:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]
NumPy array to Tensor
n = np.ones(5)
t = torch.from_numy(n)
在NumPy陣列上發生的改變也會反應在Tensor上:
np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
輸出:
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/421345.html
標籤:其他
