Tensor基础实践
Tensor基礎實踐
飛槳(PaddlePaddle,以下簡稱Paddle)和其他深度學習框架一樣,使用Tensor來表示數據,在神經網絡中傳遞的數據均為Tensor。
Tensor可以將其理解為多維數組,其可以具有任意多的維度,不同Tensor可以有不同的數據類型 (dtype) 和形狀 (shape)。
同一Tensor的中所有元素的dtype均相同。如果對 Numpy 熟悉,Tensor是類似于 Numpy array 的概念。
Tensor的創建
首先,讓開始創建一個 Tensor , 并用 ndim 表示 Tensor 維度的數量:
- 創建類似于vector的1-D Tensor,其 ndim 為1
可通過dtype來指定Tensor數據類型,否則會創建float32類型的Tensor
ndim_1_tensor = paddle.to_tensor([2.0, 3.0, 4.0], dtype=‘float64’)
print(ndim_1_tensor)
Tensor(shape=[3], dtype=float64, place=CUDAPlace(0), stop_gradient=True,
[2., 3., 4.])
特殊地,如果僅輸入單個scalar類型數據(例如float/int/bool類型的單個元素),則會創建shape為[1]的Tensor
paddle.to_tensor(2)
paddle.to_tensor([2])
上述兩種創建方式完全一致,shape均為[1],輸出如下:
Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
[2])
2. 創建類似于matrix的2-D Tensor,其 ndim 為2
ndim_2_tensor = paddle.to_tensor([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
print(ndim_2_tensor)
Tensor(shape=[2, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
[[1., 2., 3.],
[4., 5., 6.]])
3. 同樣地,還可以創建 ndim 為3、4…N等更復雜的多維Tensor
Tensor可以有任意數量的軸(也稱為維度)
ndim_3_tensor = paddle.to_tensor([[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]],
[[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]])
print(ndim_3_tensor)
Tensor(shape=[2, 2, 5], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
[[[1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]],
[[11, 12, 13, 14, 15],[16, 17, 18, 19, 20]]])
上述不同ndim的Tensor可以可視化的表示為:
圖1 不同ndim的Tensor可視化表示
可以通過 Tensor.numpy() 方法方便地將 Tensor 轉化為 Numpy array:
ndim_2_tensor.numpy()
array([[1., 2., 3.],
[4., 5., 6.]], dtype=float32)
Tensor不僅支持 floats、ints 類型數據,也支持 complex numbers數據:
ndim_2_complex_tensor = paddle.to_tensor([[1+1j, 2+2j],
[3+3j, 4+4j]])
如果輸入為復數數據,則Tensor的dtype為 complex64 或 complex128 ,其每個元素均為1個復數:
Tensor(shape=[2, 2], dtype=complex64, place=CUDAPlace(0), stop_gradient=True,
[[(1+1j), (2+2j)],
[(3+3j), (4+4j)]])
Tensor必須形狀規則,類似于“矩形”的概念,也就是,沿任何一個軸(也稱作維度)上,元素的數量都是相等的,如果為以下情況:
ndim_2_tensor = paddle.to_tensor([[1.0, 2.0],
[4.0, 5.0, 6.0]])
該情況下將會拋出異常:
ValueError:
Faild to convert input data to a regular ndarray :
- Usually this means the input data contains nested lists with different lengths.
上面介紹了通過Python數據來創建Tensor的方法,也可以通過 Numpy array 來創建Tensor:
ndim_1_tensor = paddle.to_tensor(numpy.array([1.0, 2.0]))
ndim_2_tensor = paddle.to_tensor(numpy.array([[1.0, 2.0],
[3.0, 4.0]]))
ndim_3_tensor = paddle.to_tensor(numpy.random.rand(3, 2))
創建的 Tensor 與原 Numpy array 具有相同的 shape 與 dtype。
如果要創建一個指定shape的Tensor,Paddle也提供了一些API:
paddle.zeros([m, n]) # 創建數據全為0,shape為[m, n]的Tensor
paddle.ones([m, n]) # 創建數據全為1,shape為[m, n]的Tensor
paddle.full([m, n], 10) # 創建數據全為10,shape為[m, n]的Tensor
paddle.arange( start, end, step) # 創建從start到end,步長為step的Tensor
paddle.linspace( start, end, num) # 創建從start到end,元素個數固定為num的Tensor
Tensor的shape
基本概念
查看一個Tensor的形狀可以通過 Tensor.shape,shape是 Tensor 的一個重要屬性,以下為相關概念:
- shape:描述了tensor的每個維度上元素的數量
- ndim: tensor的維度數量,例如vector的 ndim 為1,matrix的 ndim 為2.
- axis或者dimension:指tensor某個特定的維度
- size:指tensor中全部元素的個數
讓來創建1個4-D Tensor,并通過圖形來直觀表達以上幾個概念之間的關系;
ndim_4_tensor = paddle.ones([2, 3, 4, 5])
圖2 Tensor的shape、axis、dimension、ndim之間的關系
print(“Data Type of every element:”, ndim_4_tensor.dtype)
print(“Number of dimensions:”, ndim_4_tensor.ndim)
print(“Shape of tensor:”, ndim_4_tensor.shape)
print(“Elements number along axis 0 of tensor:”, ndim_4_tensor.shape[0])
print(“Elements number along the last axis of tensor:”, ndim_4_tensor.shape[-1])
Data Type of every element: VarType.FP32
Number of dimensions: 4
Shape of tensor: [2, 3, 4, 5]
Elements number along axis 0 of tensor: 2
Elements number along the last axis of tensor: 5
對shape進行操作
重新定義Tensor的shape在實際編程中具有重要意義。
ndim_3_tensor = paddle.to_tensor([[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]],
[[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]],
[[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30]]])
print(“the shape of ndim_3_tensor:”, ndim_3_tensor.shape)
the shape of ndim_3_tensor: [3, 2, 5]
Paddle提供了reshape接口來改變Tensor的shape:
ndim_3_tensor = paddle.reshape(ndim_3_tensor, [2, 5, 3])
print(“After reshape:”, ndim_3_tensor.shape)
After reshape: [2, 5, 3]
在指定新的shape時存在一些技巧:
- -1 表示這個維度的值是從Tensor的元素總數和剩余維度推斷出來的。因此,有且只有一個維度可以被設置為-1。 2.0 表示實際的維數是從Tensor的對應維數中復制出來的,因此shape中0的索引值不能超過x的維度。
有一些例子可以很好解釋這些技巧:
origin:[3, 2, 5] reshape:[3, 10] actual: [3, 10]
origin:[3, 2, 5] reshape:[-1] actual: [30]
origin:[3, 2, 5] reshape:[0, 5, -1] actual: [3, 5, 2]
可以發現,reshape為[-1]時,會將tensor按其在計算機上的內存分布展平為1-D Tensor。
print(“Tensor flattened to Vector:”, paddle.reshape(ndim_3_tensor, [-1]).numpy())
Tensor flattened to Vector: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30]
Tensor其他屬性
Tensor的dtype
Tensor的數據類型,可以通過 Tensor.dtype 來查看,dtype支持:‘bool’,‘float16’,‘float32’,‘float64’,‘uint8’,‘int8’,‘int16’,‘int32’,‘int64’。
? 通過Python元素創建的Tensor,可以通過dtype來進行指定,如果未指定:
o 對于python整型數據,則會創建int64型Tensor
o 對于python浮點型數據,默認會創建float32型Tensor,并且可以通過set_default_type來調整浮點型數據的默認類型。
? 通過Numpy array創建的Tensor,則與其原來的dtype保持相同。
print(“Tensor dtype from Python integers:”, paddle.to_tensor(1).dtype)
print(“Tensor dtype from Python floating point:”, paddle.to_tensor(1.0).dtype)
Tensor dtype from Python integers: VarType.INT64
Tensor dtype from Python floating point: VarType.FP32
Paddle提供了cast接口來改變dtype:
float32_tensor = paddle.to_tensor(1.0)
float64_tensor = paddle.cast(float32_tensor, dtype=‘float64’)
print(“Tensor after cast to float64:”, float64_tensor.dtype)
int64_tensor = paddle.cast(float32_tensor, dtype=‘int64’)
print(“Tensor after cast to int64:”, int64_tensor.dtype)
Tensor after cast to float64: VarType.FP64
Tensor after cast to int64: VarType.INT64
Tensor的place
初始化Tensor時可以通過place來指定其分配的設備位置,可支持的設備位置有三種:CPU/GPU/固定內存,其中固定內存也稱為不可分頁內存或鎖頁內存,其與GPU之間具有更高的讀寫效率,并且支持異步傳輸,這對網絡整體性能會有進一步提升,但其缺點是分配空間過多時可能會降低主機系統的性能,因為其減少了用于存儲虛擬內存數據的可分頁內存。
? 創建CPU上的Tensor:
cpu_tensor = paddle.to_tensor(1, place=paddle.CPUPlace())
print(cpu_tensor)
Tensor(shape=[1], dtype=int64, place=CPUPlace, stop_gradient=True,
[1])
? 創建GPU上的Tensor:
gpu_tensor = paddle.to_tensor(1, place=paddle.CUDAPlace(0))
print(gpu_tensor)
Tensor(shape=[1], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
[1])
? 創建固定內存上的Tensor:
pin_memory_tensor = paddle.to_tensor(1, place=paddle.CUDAPinnedPlace())
print(pin_memory_tensor)
Tensor(shape=[1], dtype=int64, place=CUDAPinnedPlace, stop_gradient=True,
[1])
Tensor的name
Tensor的name是其唯一的標識符,為python 字符串類型,查看一個Tensor的name可以通過Tensor.name屬性。默認地,在每個Tensor創建時,Paddle會自定義一個獨一無二的name。
print(“Tensor name:”, paddle.to_tensor(1).name)
Tensor name: generated_tensor_0
Tensor的操作
索引和切片
可以通過索引或切片方便地訪問或修改 Tensor。Paddle 使用標準的 Python 索引規則與 Numpy 索引規則,與 Indexing a list or a string in Python類似。具有以下特點:
- 基于 0-n 的下標進行索引,如果下標為負數,則從尾部開始計算
- 通過冒號: 分隔切片參數 start:stop:step 來進行切片操作,其中 start、stop、step 均可缺省
訪問 Tensor
? 針對1-D Tensor,則僅有單個軸上的索引或切片:
ndim_1_tensor = paddle.to_tensor([0, 1, 2, 3, 4, 5, 6, 7, 8])
print(“Origin Tensor:”, ndim_1_tensor.numpy())
print(“First element:”, ndim_1_tensor[0].numpy())
print(“Last element:”, ndim_1_tensor[-1].numpy())
print(“All element:”, ndim_1_tensor[:].numpy())
print(“Before 3:”, ndim_1_tensor[:3].numpy())
print(“From 6 to the end:”, ndim_1_tensor[6:].numpy())
print(“From 3 to 6:”, ndim_1_tensor[3:6].numpy())
print(“Interval of 3:”, ndim_1_tensor[::3].numpy())
print(“Reverse:”, ndim_1_tensor[::-1].numpy())
Origin Tensor: [0 1 2 3 4 5 6 7 8])
First element: [0]
Last element: [8]
All element: [0 1 2 3 4 5 6 7 8]
Before 3: [0 1 2]
From 6 to the end: [6 7 8]
From 3 to 6: [3 4 5]
Interval of 3: [0 3 6]
Reverse: [8 7 6 5 4 3 2 1 0]
? 針對2-D及以上的 Tensor,則會有多個軸上的索引或切片:
ndim_2_tensor = paddle.to_tensor([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
print(“Origin Tensor:”, ndim_2_tensor.numpy())
print(“First row:”, ndim_2_tensor[0].numpy())
print(“First row:”, ndim_2_tensor[0, :].numpy())
print(“First column:”, ndim_2_tensor[:, 0].numpy())
print(“Last column:”, ndim_2_tensor[:, -1].numpy())
print(“All element:”, ndim_2_tensor[:].numpy())
print(“First row and second column:”, ndim_2_tensor[0, 1].numpy())
Origin Tensor: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
First row: [0 1 2 3]
First row: [0 1 2 3]
First column: [0 4 8]
Last column: [ 3 7 11]
All element: [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
First row and second column: [1]
索引或切片的第一個值對應 axis 0,第二個值對應 axis 1,以此類推,如果某個 axis 上未指定索引,則默認為 : 。例如:
ndim_2_tensor[1]
ndim_2_tensor[1, :]
這兩種操作的結果是完全相同的。
Tensor(shape=[4], dtype=int64, place=CPUPlace, stop_gradient=True,
[4, 5, 6, 7])
修改 Tensor
注意:
通過索引或切片修改 Tensor,該操作會原地修改該 Tensor 的數值,且原值不會被保存。如果被修改的 Tensor 參與梯度計算,將僅會使用修改后的數值,這可能會給梯度計算引入風險。Paddle 之后將會對具有風險的操作進行檢測和報錯。
與訪問 Tensor 類似,修改 Tensor 可以在單個或多個軸上通過索引或切片操作。同時,支持將多種類型的數據賦值給該 Tensor,當前支持的數據類型有:int, float, numpy.ndarray, Tensor。
import paddle
import numpy as np
x = paddle.to_tensor(np.ones((2, 3)).astype(np.float32)) # [[1., 1., 1.], [1., 1., 1.]]
x[0] = 0 # x : [[0., 0., 0.], [1., 1., 1.]] id(x) = 4433705584
x[0:1] = 2.1 # x : [[2.1, 2.1, 2.1], [1., 1., 1.]] id(x) = 4433705584
x[…] = 3 # x : [[3., 3., 3.], [3., 3., 3.]] id(x) = 4433705584
x[0:1] = np.array([1,2,3]) # x : [[1., 2., 3.], [3., 3., 3.]] id(x) = 4433705584
x[1] = paddle.ones([3]) # x : [[1., 2., 3.], [1., 1., 1.]] id(x) = 4433705584
同時,Paddle 還提供了豐富的 Tensor 操作的 API,包括數學運算符、邏輯運算符、線性代數相關等100余種 API,這些 API 調用有兩種方法:
x = paddle.to_tensor([[1.1, 2.2], [3.3, 4.4]], dtype=“float64”)
y = paddle.to_tensor([[5.5, 6.6], [7.7, 8.8]], dtype=“float64”)
print(paddle.add(x, y), “\n”)
print(x.add(y), “\n”)
Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,
[[6.60000000, 8.80000000],
[ 11., 13.20000000]])
Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,
[[6.60000000, 8.80000000],
[ 11., 13.20000000]])
可以看出,使用 Tensor 類成員函數 和 Paddle API 具有相同的效果,由于 類成員函數 操作更為方便,以下均從 Tensor 類成員函數 的角度,對常用 Tensor 操作進行介紹。
數學運算符
x.abs() #逐元素取絕對值
x.ceil() #逐元素向上取整
x.floor() #逐元素向下取整
x.round() #逐元素四舍五入
x.exp() #逐元素計算自然常數為底的指數
x.log() #逐元素計算x的自然對數
x.reciprocal() #逐元素求倒數
x.square() #逐元素計算平方
x.sqrt() #逐元素計算平方根
x.sin() #逐元素計算正弦
x.cos() #逐元素計算余弦
x.add(y) #逐元素相加
x.subtract(y) #逐元素相減
x.multiply(y) #逐元素相乘
x.divide(y) #逐元素相除
x.mod(y) #逐元素相除并取余
x.pow(y) #逐元素冪運算
x.max() #指定維度上元素最大值,默認為全部維度
x.min() #指定維度上元素最小值,默認為全部維度
x.prod() #指定維度上元素累乘,默認為全部維度
x.sum() #指定維度上元素的和,默認為全部維度
Paddle對python數學運算相關的魔法函數進行了重寫,以下操作與上述結果相同。
x + y -> x.add(y) #逐元素相加
x - y -> x.subtract(y) #逐元素相減
x * y -> x.multiply(y) #逐元素相乘
x / y -> x.divide(y) #逐元素相除
x % y -> x.mod(y) #逐元素相除并取余
x ** y -> x.pow(y) #逐元素冪運算
邏輯運算符
x.isfinite() #判斷tensor中元素是否是有限的數字,即不包括inf與nan
x.equal_all(y) #判斷兩個tensor的全部元素是否相等,并返回shape為[1]的bool Tensor
x.equal(y) #判斷兩個tensor的每個元素是否相等,并返回shape相同的bool Tensor
x.not_equal(y) #判斷兩個tensor的每個元素是否不相等
x.less_than(y) #判斷tensor x的元素是否小于tensor y的對應元素
x.less_equal(y) #判斷tensor x的元素是否小于或等于tensor y的對應元素
x.greater_than(y) #判斷tensor x的元素是否大于tensor y的對應元素
x.greater_equal(y) #判斷tensor x的元素是否大于或等于tensor y的對應元素
x.allclose(y) #判斷tensor x的全部元素是否與tensor y的全部元素接近,并返回shape為[1]的bool Tensor
同樣地,Paddle對python邏輯比較相關的魔法函數進行了重寫,以下操作與上述結果相同。
x == y -> x.equal(y) #判斷兩個tensor的每個元素是否相等
x != y -> x.not_equal(y) #判斷兩個tensor的每個元素是否不相等
x < y -> x.less_than(y) #判斷tensor x的元素是否小于tensor y的對應元素
x <= y -> x.less_equal(y) #判斷tensor x的元素是否小于或等于tensor y的對應元素
x > y -> x.greater_than(y) #判斷tensor x的元素是否大于tensor y的對應元素
x >= y -> x.greater_equal(y) #判斷tensor x的元素是否大于或等于tensor y的對應元素
以下操作僅針對bool型Tensor:
x.logical_and(y) #對兩個bool型tensor逐元素進行邏輯與操作
x.logical_or(y) #對兩個bool型tensor逐元素進行邏輯或操作
x.logical_xor(y) #對兩個bool型tensor逐元素進行邏輯亦或操作
x.logical_not(y) #對兩個bool型tensor逐元素進行邏輯非操作
線性代數相關
x.cholesky() #矩陣的cholesky分解
x.t() #矩陣轉置
x.transpose([1, 0]) #交換axis 0 與axis 1的順序
x.norm(‘fro’) #矩陣的Frobenius 范數
x.dist(y, p=2) #矩陣(x-y)的2范數
x.matmul(y) #矩陣乘法
需要注意,Paddle中Tensor的操作符均為非inplace操作,即 x.add(y) 不會在tensor x上直接進行操作,而會返回一個新的Tensor來表示運算結果。
總結
以上是生活随笔為你收集整理的Tensor基础实践的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Paddle预训练模型应用工具Paddl
- 下一篇: Paddle广播 (broadcasti