昇思25天學習打卡營第03天 | 張量 Tensor
文章目錄
- 昇思25天學習打卡營第03天 | 張量 Tensor
- 張量
- 張量的創建
- 張量的屬性
- Tensor與NumPy轉換
- 稀疏張量
- CSRTensor
- COOTensor
- 總結
- 打卡
張量
張量(Tensor)是一種類似于數組和矩陣的特殊數據結構,是神經網絡中參與運算的基本結構。
對于 n n n維空間中的一個張量,其具有 n r n^r nr個坐標分量,其中 r r r被稱為該張量的秩或階。
張量的創建
- 從列表創建
data = [1, 0, 1, 0]
x_data = Tensor(data)
- 從NumPy數組創建
np_array = np.array(data)
x_np = Tensor(np_array)
- 使用
init
初始化器創建,需要傳入三個參數,主要用于并行模式下的延后初始化。init
:支持initializer的子類,如One()
和Normal()
shape
:支持list
、tuple
、int
dtype
:支持mindspore.dtype
tensor1 = mindspore.Tensor(shape=(2, 2), dtype=mindspore.float32, init=One())# Initialize a tensor from normal distribution
tensor2 = mindspore.Tensor(shape=(2, 2), dtype = mindspore.float32, init=Normal())
- 從一個張量創建新的張量
from mindspore import opsx_ones = ops.ones_like(x_data) # [1 1 1 1]
x_zeros = ops.zeros_like(x_data) # [0 0 0 0]
張量的屬性
MindSpore中一個張量具有下面的屬性:
- shape
- dtype
- itemsize:單個元素所占的字節大小
- nbytes:Tensor所占的總字節數
- ndim:Tensor的秩
- size:Tensor中元素的個數
- strides:Tensor每一維所需要的字節數
Tensor與NumPy轉換
- 使用
Tensor.asnumpy()
將Tensor轉換為Numpy數組。 - 使用
Tensor.from_numpy()
將numpy數組轉換為Tensor
稀疏張量
在很多場景中,張量中只有少量的非零元素,如果用普通張量進行存儲,會引入大量不必要的開銷,這時就可以使用稀疏張量來表示。
MindSpore中定了了三種稀疏張量結構:CSRTensor
、COOTensor
,RowTensor
CSRTensor
CSR (Compressed Sparse Row) Tensor 具有高效的存儲和計算優勢。
indptr
:一維整數張量,表示非零元素在values中的起始位置和結束位置;indices
:一維整數張量,表示非零元素在列中的位置,與values
長度相等;values
:一維張量,表示非零元素;shape
:表示被壓縮的張量的形狀。
indptr = Tensor([0, 1, 2])
indices = Tensor([0, 1])
values = Tensor([1, 2], dtype=mindspore.float32)
shape = (2, 4)# Make a CSRTensor
csr_tensor = CSRTensor(indptr, indices, values, shape)
上述代碼對應的Tensor為:
[ 1 0 0 0 0 2 0 0 ] \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \end{bmatrix} [10?02?00?00?]
COOTensor
COO (Coordinate Format) Tensor用來表示給定索引上非零元素的集合,其參數為:
indices
:二維證書張量,每行代表非零元素的下標。values
:一維張量,表示非零元素值。shape
:表示被壓縮的稀疏張量的形狀。
indices = Tensor([[0, 1], [1, 2]], dtype=mindspore.int32)
values = Tensor([1, 2], dtype=mindspore.float32)
shape = (3, 4)# Make a COOTensor
coo_tensor = COOTensor(indices, values, shape)
總結
這一節內容對MindSpore框架中的Tensor進行了較為詳細的介紹,包括Tensor的創建、Tensor的索引和簡單運算、與NumPy數組之間的轉換。此外,還介紹了稀疏矩陣的兩種表示方法和創建方法,為之后對張量的操作建立了初步的認識。