昇思MindSpore学习笔记3--张量 Tensor

一、张量Tensor概念

矢量、标量和其他张量的计算函数,有内积、外积、线性映射以及笛卡儿积

张量坐标在 n 维空间内,有 nr 个分量

每个分量都是坐标的函数,变换时每个坐标分量都按规则作线性变换

张量是一种特殊的数据结构,类似于数组和矩阵

张量是MindSpore网络运算中的基本数据结构

二、环境准备

1. 安装minspore模块

!pip uninstall mindspore -y
!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.3.0rc1

2.导入minspore、Tensor等相关模块

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

三、创建张量

支持Tensor、float、int、bool、tuple、listnumpy.ndarray

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

2.从NumPy数组生成

np_array = np.array(data)
x_np = Tensor(np_array)
print(x_np, x_np.shape, x_np.dtype)

输出:[

[1 0 1 0] (4,) Int64

3.init初始化器构造张量

支持参数:

init     :initializer的子类,  例如init=One()主要用于并行模式

shapelist、tuple、int,   例如shape=(2, 2)

dtype mindspore.dtype,例如dtype=mindspore.float32

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.00247062  0.00723172]
 [-0.00915686 -0.00984331]]

4.继承张量生成新张量

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] 

Zeros Tensor: 
 [0 0 0 0] 

四、张量属性

shape   :形状(tuple)

dtype   :MindSpore数据类型

itemsize:单个元素占用字节数(整数)

nbytes  :整个张量占用总字节数(整数)

ndim    :维数,张量的秩=len(tensor.shape)(整数)

size    :张量所有元素的个数(整数)

strides :张量每一维步长,每一维字节数(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)

五、张量索引

从0开始编制

负索引表示倒序编制

切片冒号:和 ...

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.]

六、张量运算

包括算术、线性代数、矩阵处理(转置、标引、切片)、采样等

1.算术运算:

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.]

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)

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

七、张量与NumPy转换

1. Tensor转换为NumPy

 Tensor.asnumpy()

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

2.NumPy转换为Tensor

Tensor.from_numpy()

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

八、稀疏张量

绝大部分元素的值为零或者某个确定值。

常用CSR和COO两种稀疏数据格式

稀疏张量的表达形式

<indices:Tensor, values:Tensor, shape:Tensor>

indices 非零下标元素

values 非零元素的值

shape 被压缩的稀疏张量的形状

三种稀疏张量结构:CSRTensor、COOTensor和RowTensor。

1.CSRTensor

Compressed Sparse Row压缩稀疏

values :非零元素的值,一维张量

indptr :维度,非零元素在values中起始位置和终止位置,一维整数张量

indices维度,非零元素在列中的位置,其长度与values相等,一维整数张量

       索引数据类型支持int16、int32、int64

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

参考mindspore.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.astype(mindspore.float64).dtype)

输出:

Float64

生成的CSRTensor:

2.COOTensor

Coordinate Format坐标格式

values :非零元素的值,一维张量,形状:[N]

indices:每行代表非零元素下标,二维整数张量,形状:[N, ndims]

索引数据类型支持int16、int32、int64。

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

参考mindspore.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

输出:

[1. 2.]
[[0 1]
 [1 2]]
(3, 4)
Float64

生成的COOTensor:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

muren

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值