当前位置:   article > 正文

《昇思25天学习打卡营第2天 | 张量 Tensor》

《昇思25天学习打卡营第2天 | 张量 Tensor》

《昇思25天学习打卡营第2天 | 张量 Tensor

什么是张量(Tensor)

张量(Tensor)是一个多维数组或矩阵的概念,它是向量和矩阵的推广。

在数学和物理学中,张量是一个具有多个分量的量,这些分量之间的关系可以通过一组坐标变换来描述。
在计算机科学和工程领域,特别是在机器学习和深度学习中,张量通常指的是多维数组,它是数据的基本表示形式。
在 MindSpore 网络运算中张量(Tensor)是基本的数据结构。张量是一种特殊的数据结构,与数组和矩阵非常相似。

张量的创建方式

根据数据直接生成

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

data = [1, 0, 1, 0]
x_data = Tensor(data)
print(x_data, x_data.shape, x_data.dtype)
  • 1
  • 2
  • 3

[1 0 1 0] (4,) Int64

从NumPy数组生成

可以从NumPy数组创建张量。

np_array = np.array(data)
x_np = Tensor(np_array)
print(x_np, x_np.shape, x_np.dtype)
  • 1
  • 2
  • 3

[1 0 1 0] (4,) Int64

使用init初始化器构造张量

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

  • init: 支持传入initializer的子类。如:下方示例中的 One() 和 Normal()。

  • shape: 支持传入 list、tuple、 int。

  • dtype: 支持传入mindspore.dtype。

from mindspore.common.initializer import One, Normal

# Initialize a tensor with ones
# init主要用于并行模式下的延后初始化,在正常情况下不建议使用init对参数进行初始化。
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

tensor1:
[[1. 1.]
[1. 1.]]
tensor2:
[[ 0.01183298 0.00573333]
[ 0.01764924 -0.00527418]]

在这里插入图片描述

继承另一个张量的属性,形成新的张量
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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Ones Tensor:
[1 1 1 1]
Zeros Tensor:
[0 0 0 0]

张量的属性

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

  • 形状(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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/784674
推荐阅读
  

闽ICP备14008679号