基础知识
基础的数据格式和结构
; 张量的数学结构
三维张量
Tensor是MindSpore网络运算的一个基本数据结构,MindSpore的所有运算或者数学操作都是基于Tensor的。
创建张量
通过数据直接创建
from mindspore import Tensor
x = Tensor(0.1)
print(x)
print(type(x))
根据Numpy数组生成
import numpy as np
arr = np.array([1, 0, 1, 0])
tensor_arr = Tensor(arr)
print(arr)
print(type(arr))
print(tensor_arr)
print(type(tensor_arr))
使用init初始化器构造张量
Tensor构建的时候已经适用过构造器了,为什么还需要使用构造器构造张量?
张量在神经网络中是一个高维数据,如果一开始的初始化做的好可能有助于神经网络模型的学习,假设需要全1的张量,只需要在第三个参数中传入 One()
即可。
当使用init初始化器对张量进行初始化时,支持传入的参数有init、shape、dtype。
- init: 支持传入initializer的子类。
- shape: 支持传入 list、tuple、 int。
- dtype: 支持传入mindspore.dtype。
from mindspore import set_seed
from mindspore import dtype as mstype
from mindspore.common.initializer import One, Normal
set_seed(1)
tensor1 = Tensor(shape=(2, 2), dtype=mstype.float32, init=One())
tensor2 = Tensor(shape=(2, 2), dtype=mstype.float32, init=Normal())
print("tensor1:\n", tensor1)
print("tensor2:\n", tensor2)
通过继承的方式构造张量
from mindspore import ops
oneslike = ops.OnesLike()
x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
output = oneslike(x)
print(output)
print(x)
print("input shape:", x.shape)
print("output shape:", output.shape)
张量的属性
张量的属性包括形状、数据类型、转置张量、单个元素大小、占用字节数量、维数、元素个数和每一维步长。
- 形状(shape):
Tensor
的shape,是一个tuple。 - 数据类型(dtype):
Tensor
的dtype,是MindSpore的一个数据类型。 - 转置张量(T):
Tensor
的转置,是一个Tensor
。 - 单个元素大小(itemsize):
Tensor
中每一个元素占用字节数,是一个整数。 - 占用字节数量(nbytes):
Tensor
占用的总字节数,是一个整数。 - 维数(ndim):
Tensor
的秩,也就是len(tensor.shape),是一个整数。 - 元素个数(size):
Tensor
中所有元素的个数,是一个整数。 - 每一维步长(strides):
Tensor
每一维所需要的字节数,是一个tuple。
张量索引
Tensor索引与Numpy索引类似,索引从0开始,负索引表示按倒序编制,冒号 :
和 ...
用于对数据进行切片。
张量运算
张量之间有很多运算,包括算术、线性代数、矩阵处理(转置、标引、切片)、采样等,张量运算和NumPy的使用方式类似。
普通算术运算有:加(+)、减(-)、乘(*)、除(/)、取模(%)、整除(//)。
Concat
Concat
可以将给定维度上的一系列张量连接起来。
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
op = ops.Concat()
output = op((data1, data2))
print(output)
print("shape:\n", output.shape)
Stack
Stack
则是从另一个维度上将两个张量合并起来。
data1 = Tensor(np.array([[0, 1], [2, 3]]).astype(np.float32))
data2 = Tensor(np.array([[4, 5], [6, 7]]).astype(np.float32))
op = ops.Stack()
output = op([data1, data2])
print(output)
print("shape:\n", output.shape)
Tensor与NumPy转换
Tensor可以和NumPy进行互相转换,一般在网络模型的输出之后会对Tensor做一些下游任务的处理或者把它编程具体的机器学习的任务。
Tensor转换为NumPy
与张量创建相同,使用 asnumpy()
将Tensor变量转换为NumPy变量。
zeros = ops.Zeros()
output = zeros((2, 2), mstype.float32)
print("output: {}".format(type(output)))
n_output = output.asnumpy()
print("n_output: {}".format(type(n_output)))
NumPy转换为Tensor
使用 Tensor()
将NumPy变量转换为Tensor变量。
output = np.array([1, 0, 1, 0])
print("output: {}".format(type(output)))
t_output = Tensor(output)
print("t_output: {}".format(type(t_output)))
Original: https://blog.csdn.net/weixin_47365232/article/details/125571736
Author: weixin_47365232
Title: MindSpore入门——张量Tensor
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/760769/
转载文章受原作者版权保护。转载请注明原作者出处!