240624_昇思学习打卡-Day6-张量Tensor

发布于:2024-06-25 ⋅ 阅读:(122) ⋅ 点赞:(0)

240624_昇思学习打卡-Day6-张量Tensor

今儿扭头回来看看基础,看看最基本的数据结构,张量(Tensor)。

张量和数组、矩阵非常相似。是MindSpore网络运算中的基本数据结构,本文主要介绍张量和稀疏张量的属性及用法。


上来还是先导包

import numpy as np
import mindspore
from mindspore import ops
from mindspore import Tensor, CSRTensor, COOTensor

创建张量

俗话说的好,巧妇难为无米之炊,要玩儿张量,得先new一个出来啊

张量支持传入Tensorfloatintbooltuplelistnumpy.ndarray类型。也就是说,张量可以支持张量套张量套张量套张量套张量套张量……套娃,只要你数的清有多少括号,理论上说可以无限嵌套,但是在实际测试中我发现,使用numpy创建最高好像只支持到32维

import numpy as np

# 给定的一维数组
array_1d = np.array([0, 1, 0, 1])

# 目标维度数
target_dims = 32

# 创建一个形状为 (1, 1, ..., 1, 4) 的张量
tensor_32d = np.expand_dims(array_1d, axis=tuple(range(target_dims - array_1d.ndim)))

print(tensor_32d.shape)
print(tensor_32d)

'''
输出结果:
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4)
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[0 1 0 1]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
'''

直接根据数据生成:

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数组创建张量

np_array=np.array(data)
x_np=Tensor(np_array)
print(x_np)

'''
输出结果:[1 0 1 0]
'''

使用init初始化器构造张量

from mindspore.common.initializer import One,Normal
tensor1=mindspore.Tensor(shape=(2,2),dtype=mindspore.float32,init=One())
tensor2=mindspore.Tensor(shape=(2,2),dtype=mindspore.float32,init=Normal())
print(tensor1,'\n',tensor2)

'''
输出结果:
[[1. 1.]
 [1. 1.]] 
 [[-0.02382057  0.00478452]
 [-0.01158325 -0.0060997 ]]
'''

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

from mindspore import ops
x_ones=ops.ones_like(x_data)
x_zeros=ops.zeros_like(x_data)
print(x_ones,'\n',x_zeros)

'''
输出结果:
[1 1 1 1] 
 [0 0 0 0]
'''

张量的属性

目前我们用到了Tensor的两个属性,shape,dtype,但其不止两个属性。

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

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

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

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

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

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

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

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

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)
'''

张量索引

张量的索引和numpy的索引使用方法基本一致,都支持整数索引、切片索引、布尔索引等,这里就随便提一嘴

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
Last column: [1. 3.]
First column: [0. 2.]
'''

张量运算

运算也是和numpy基本一致,直接记录

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实现在某个维度上把张量连接起来

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是从另一个维度上把两个张量合并起来,直接变成三维了

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.asnumpy()将Tensor变量转换为NumPy变量。

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'>
'''

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

n = np.ones(5)
t = Tensor(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: [1. 1. 1. 1. 1.] <class 'mindspore.common.tensor.Tensor'>
'''

稀疏张量

在一些应用场景中,比如训练二值化图像分割时,图像的特征是稀疏的,使用一堆0和极个别的1表示这些特征即费事又难看,此时就可以使用稀疏张量

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的使用示例:

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.values)


上述代码会生成如下所示的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的使用示例:

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

上述代码会生成如下所示的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
打卡截图:

image-20240624235132675


网站公告

今日签到

点亮在社区的每一天
去签到