【昇思25天学习打卡营打卡指南-第二天】张量Tensor

张量 Tensor

定义

张量(Tensor)是一个可用来表示在一些矢量、标量和其他张量之间的线性关系的多线性函数,这些线性关系的基本例子有内积、外积、线性映射以及笛卡儿积。其坐标在  n n n 维空间内,有  n r n^{r} nr 个分量的一种量,其中每个分量都是坐标的函数,而在坐标变换时,这些分量也依照某些规则作线性变换。 r r r 称为该张量的秩或阶(与矩阵的秩和阶均无关系)。

张量是一种特殊的数据结构,与数组和矩阵非常相似。

张量API地址:Tensor

张量也是MindSpore网络运算中的基本数据结构,本教程主要介绍张量和稀疏张量的属性及用法。

创建张量

张量的创建方式有多种,构造张量时,支持传入Tensorfloatintbooltuplelistnumpy.ndarray类型。

  • 根据数据直接生成

    可以根据数据创建张量,数据类型可以设置或者通过框架自动推断。

代码示例:

python 复制代码
data = [1, 0, 1, 0]
x_data = Tensor(data)
print(x_data, x_data.shape, x_data.dtype)

运行结果:

复制代码
[1 0 1 0] (4,) Int64
  • 从NumPy数组生成

    可以从NumPy数组创建张量。

代码示例

python 复制代码
np_array = np.array(data)
x_np = Tensor(np_array)
print(x_np, x_np.shape, x_np.dtype)

运行结果

python 复制代码
[1 0 1 0] (4,) Int64
  • 使用init初始化器构造张量

    当使用init初始化器对张量进行初始化时,支持传入的参数有initshapedtype

代码示例

python 复制代码
from mindspore.common.initializer import One, Normal

# Initialize a tensor with ones
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())

print("tensor1:\n", tensor1)
print("tensor2:\n", tensor2)

运行结果:

复制代码
tensor1:
 [[1. 1.]
 [1. 1.]]
tensor2:
 [[-0.022815   -0.01483201]
 [ 0.026975   -0.00120748]]

init主要用于并行模式下的延后初始化,在正常情况下不建议使用init对参数进行初始化。

  • 继承另一个张量的属性,形成新的张量

代码示例

python 复制代码
from mindspore import ops

x_ones = ops.ones_like(x_data)
print(f"Ones Tensor: \n {x_ones} \n")

x_zeros = ops.zeros_like(x_data)
print(f"Zeros Tensor: \n {x_zeros} \n")

运行结果:

复制代码
Ones Tensor: 
 [1 1 1 1] 

张量的属性

张量的属性包括形状、数据类型、转置张量、单个元素大小、占用字节数量、维数、元素个数和每一维步长。

  • 形状(shape):Tensor的shape,是一个tuple。

  • 数据类型(dtype):Tensor的dtype,是MindSpore的一个数据类型。

  • 单个元素大小(itemsize): Tensor中每一个元素占用字节数,是一个整数。

  • 占用字节数量(nbytes): Tensor占用的总字节数,是一个整数。

  • 维数(ndim): Tensor的秩,也就是len(tensor.shape),是一个整数。

  • 元素个数(size): Tensor中所有元素的个数,是一个整数。

  • 每一维步长(strides): Tensor每一维所需要的字节数,是一个tuple。

代码示例

python 复制代码
x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32)

print("x_shape:", x.shape)
print("x_dtype:", x.dtype)
print("x_itemsize:", x.itemsize)
print("x_nbytes:", x.nbytes)
print("x_ndim:", x.ndim)
print("x_size:", x.size)
print("x_strides:", x.strides)

运行结果

复制代码
x_shape: (2, 2)
x_dtype: Int32
x_itemsize: 4
x_nbytes: 16
x_ndim: 2
x_size: 4
x_strides: (8, 4)

张量索引

Tensor索引与Numpy索引类似,索引从0开始编制,负索引表示按倒序编制,冒号:...用于对数据进行切片。

代码示例

python 复制代码
tensor = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))

print("First row: {}".format(tensor[0]))
print("value of bottom right corner: {}".format(tensor[1, 1]))
print("Last column: {}".format(tensor[:, -1]))
print("First column: {}".format(tensor[..., 0]))

运行结果

复制代码
First row: [0. 1.]
value of bottom right corner: 3.0

张量运算

张量之间有很多运算,包括算术、线性代数、矩阵处理(转置、标引、切片)、采样等,张量运算和NumPy的使用方式类似,下面介绍其中几种操作。

普通算术运算有:加(+)、减(-)、乘(*)、除(/)、取模(%)、整除(//)。

代码示例

python 复制代码
x = Tensor(np.array([1, 2, 3]), mindspore.float32)
y = Tensor(np.array([4, 5, 6]), mindspore.float32)

output_add = x + y
output_sub = x - y
output_mul = x * y
output_div = y / x
output_mod = y % x
output_floordiv = y // x

print("add:", output_add)
print("sub:", output_sub)
print("mul:", output_mul)
print("div:", output_div)
print("mod:", output_mod)
print("floordiv:", output_floordiv)
复制代码
运行结果

add: [5. 7. 9.]

sub: [-3. -3. -3.]

mul: [ 4. 10. 18.]

div: [4. 2.5 2. ]

mod: [0. 1. 0.]

floordiv: [4. 2. 2.]

复制代码
concat将给定维度上的一系列张量连接起来。
```python
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
output = ops.concat((data1, data2), axis=0)

print(output)
print("shape:\n", output.shape)

运行结果

复制代码
[[0. 1.]
 [2. 3.]
 [4. 5.]
 [6. 7.]]
shape:
 (4, 2)

stack则是从另一个维度上将两个张量合并起来。

python 复制代码
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
output = ops.stack([data1, data2])

print(output)
print("shape:\n", output.shape)

运行结果

复制代码
[[[0. 1.]
  [2. 3.]]

 [[4. 5.]
  [6. 7.]]]
shape:
 (2, 2, 2)

Tensor与NumPy转换

Tensor可以和NumPy进行互相转换。

Tensor转换为NumPy

与张量创建相同,使用 Tensor.asnumpy() 将Tensor变量转换为NumPy变量。

python 复制代码
t = Tensor([1., 1., 1., 1., 1.])
print(f"t: {t}", type(t))
n = t.asnumpy()
print(f"n: {n}", type(n))

运行结果

复制代码
t: [1. 1. 1. 1. 1.] <class 'mindspore.common.tensor.Tensor'>
n: [1. 1. 1. 1. 1.] <class 'numpy.ndarray'>

NumPy转换为Tensor

使用Tensor()将NumPy变量转换为Tensor变量。

python 复制代码
n = np.ones(5)
t = Tensor.from_numpy(n)

np.add(n, 1, out=n)
print(f"n: {n}", type(n))
print(f"t: {t}", type(t))

运行结果

复制代码
n: [2. 2. 2. 2. 2.] <class 'numpy.ndarray'>
t: [2. 2. 2. 2. 2.] <class 'mindspore.common.tensor.Tensor'>

稀疏张量

稀疏张量是一种特殊张量,其中绝大部分元素的值为零。

在某些应用场景中(比如推荐系统、分子动力学、图神经网络等),数据的特征是稀疏的,若使用普通张量表征这些数据会引入大量不必要的计算、存储和通讯开销。这时就可以使用稀疏张量来表征这些数据。

MindSpore现在已经支持最常用的CSRCOO两种稀疏数据格式。

常用稀疏张量的表达形式是<indices:Tensor, values:Tensor, shape:Tensor>。其中,indices表示非零下标元素, values表示非零元素的值,shape表示的是被压缩的稀疏张量的形状。在这个结构下,我们定义了三种稀疏张量结构:CSRTensorCOOTensorRowTensor

CSRTensor

CSR(Compressed Sparse Row)稀疏张量格式有着高效的存储与计算的优势。其中,非零元素的值存储在values中,非零元素的位置存储在indptr(行)和indices(列)中。各参数含义如下:

  • indptr: 一维整数张量, 表示稀疏数据每一行的非零元素在values中的起始位置和终止位置, 索引数据类型支持int16、int32、int64。

  • indices: 一维整数张量,表示稀疏张量非零元素在列中的位置, 与values长度相等,索引数据类型支持int16、int32、int64。

  • values: 一维张量,表示CSRTensor相对应的非零元素的值,与indices长度相等。

  • shape: 表示被压缩的稀疏张量的形状,数据类型为Tuple,目前仅支持二维CSRTensor

CSRTensor的详细文档,请参考mindspore.CSRTensor

下面给出一些CSRTensor的使用示例:

python 复制代码
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)

print(csr_tensor.astype(mindspore.float64).dtype)

运行结果
Float64

上述代码会生成如下所示的CSRTensor:

1 0 0 0 0 2 0 0 \] \\left\[ \\begin{matrix} 1 \& 0 \& 0 \& 0 \\\\ 0 \& 2 \& 0 \& 0 \\end{matrix} \\right\] \[10020000

COOTensor

COO(Coordinate Format)稀疏张量格式用来表示某一张量在给定索引上非零元素的集合,若非零元素的个数为N,被压缩的张量的维数为ndims。各参数含义如下:

  • indices: 二维整数张量,每行代表非零元素下标。形状:[N, ndims], 索引数据类型支持int16、int32、int64。

  • values: 一维张量,表示相对应的非零元素的值。形状:[N]

  • shape: 表示被压缩的稀疏张量的形状,目前仅支持二维COOTensor

COOTensor的详细文档,请参考mindspore.COOTensor

下面给出一些COOTensor的使用示例:

python 复制代码
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)

print(coo_tensor.values)
print(coo_tensor.indices)
print(coo_tensor.shape)
print(coo_tensor.astype(mindspore.float64).dtype)  # COOTensor to float64

运行结果

复制代码
[1. 2.]
[[0 1]
 [1 2]]
(3, 4)
Float64

上述代码会生成如下所示的COOTensor:

0 1 0 0 0 0 2 0 0 0 0 0 \] \\left\[ \\begin{matrix} 0 \& 1 \& 0 \& 0 \\\\ 0 \& 0 \& 2 \& 0 \\\\ 0 \& 0 \& 0 \& 0 \\end{matrix} \\right\] 000100020000 ### 附录 显示名字和学习时间代码 ```python import time print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),'JeffDing') ```

相关推荐
西岸行者5 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意5 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码5 天前
嵌入式学习路线
学习
毛小茛5 天前
计算机系统概论——校验码
学习
babe小鑫5 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms5 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下5 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。5 天前
2026.2.25监控学习
学习
im_AMBER5 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
CodeJourney_J5 天前
从“Hello World“ 开始 C++
c语言·c++·学习