昇思25天学习打卡营第2天|MindSpore快速入门-张量

devtools/2024/10/18 0:30:48/

张量 Tensor

张量(Tensor)是一个可用来表示在一些矢量、标量和其他张量之间的线性关系的多线性函数,这些线性关系的基本例子有内积、外积、线性映射以及笛卡儿积。

张量是一种特殊的数据结构,与数组和矩阵非常相似。张量(Tensor)是MindSpore网络运算中的基本数据结构,本教程主要介绍张量和稀疏张量的属性及用法。

创建张量

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

根据数据直接生成

- 从NumPy数组生成

- 使用init初始化器构造张量

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

import numpy as np
import mindspore
from mindspore import ops
from mindspore import Tensor, CSRTensor, COOTensor# 创建张量 data = [1, 0, 1, 0]
x_data = Tensor(data)
print(x_data, x_data.shape, x_data.dtype)np_array = np.array(data)
x_np = Tensor(np_array)
print(x_np, x_np.shape, x_np.dtype)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)from mindspore import opsx_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")

张量的属性

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

  • 形状(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)# 张量索引
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]))

张量运算¶

张量之间有很多运算,包括算术、线性代数、矩阵处理(转置、标引、切片)、采样等,张量运算和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 // xprint("add:", output_add)
print("sub:", output_sub)
print("mul:", output_mul)
print("div:", output_div)
print("mod:", output_mod)
print("floordiv:", output_floordiv)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)# 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)

Tensor与NumPy转换

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

# Tensor转换为NumPy
t = Tensor([1., 1., 1., 1., 1.])
print(f"t: {t}", type(t))
n = t.asnumpy()
print(f"n: {n}", type(n))# NumPy转换为Tensor
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))

稀疏张量

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

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

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

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)

COOTensor

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

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

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

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

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


http://www.ppmy.cn/devtools/56468.html

相关文章

.NET C# 使用OpenCV实现人脸识别

.NET C# 使用OpenCV实现模型训练、人脸识别 码图~~~ 1 引入依赖 OpenCvSHarp4 - 4.10.0.20240616 OpenCvSHarp4.runtime.win - 4.10.0.20240616 2 人脸数据存储结构 runtime directory | face | {id}_{name} | *.jpg id - 不可重复 name - 人名 *.jpg - 人脸照片3 Demo 3.…

基于springboot、logback的日志脱敏组件

Logback⽇志数据脱敏⼯具&#xff1a;隐私和安全的守护者 概述 在涉及敏感数据的⽇志记录环境中&#xff0c;数据保护和个⼈隐私⽆疑是⾄关重要的领域。确保敏感数据不被泄露&#xff0c;脱敏处理成为必不可少的⼀步。数据脱敏是⼀种技术⼿段&#xff0c;其将敏感信息转换为不…

ARM 240625

练习&#xff1a; 汇编实现1-100累加&#xff0c;结果保存在r0 .text 声明下面内容都属于文本段内容 .globl _start 声明 _start 是一个全局启用的标签_start: 封装 _start 标签&#xff0c;汇编的标签和C中函数类似mov r0,#0 mov 把0 搬运到 r0 寄存器mov r1,#1 mov 把1 …

【使用webrtc-streamer解析rtsp视频流】

webrtc-streamer WebRTC (Web Real-Time Communications) 是一项实时通讯技术&#xff0c;它允许网络应用或者站点&#xff0c;在不借助中间媒介的情况下&#xff0c;建立浏览器之间点对点&#xff08;Peer-to-Peer&#xff09;的连接&#xff0c;实现视频流和&#xff08;或&a…

Android中ViewModel+LiveData+DataBinding的配合使用(kotlin)

Android 中 ViewModel、LiveData 和 Data Binding 的配合使用&#xff08;Kotlin&#xff09; 摘要 本文将介绍如何在 Android 开发中结合使用 ViewModel、LiveData 和 Data Binding 进行数据绑定和状态更新。我们将详细探讨这三者之间的关系&#xff0c;并展示如何在 Kotlin…

uni-app的showModal提示框,进行删除的二次确认,可自定义确定或取消操作

实现效果&#xff1a; 此处为删除的二次确认示例&#xff0c;点击删除按钮时出现该提示&#xff0c;该提示写在js script中。 实现方式&#xff1a; 通过uni.showModal进行提示&#xff0c;success为确认状态下的操作自定义&#xff0c;此处调用后端接口进行了删除操作&#…

计算机网络知识整理笔记

目录 1.对网络协议的分层&#xff1f; 2.TCP/IP和UDP之间的区别&#xff1f; 3.建立TCP连接的三次握手&#xff1f; 4.断开TCP连接的四次挥手&#xff1f; 5.TCP协议如何保证可靠性传输&#xff1f; 6.什么是TCP的拥塞控制&#xff1f; 7.什么是HTTP协议&#xff1f; 8…

昇思25天学习打卡营第4天|linchenfengxue

需求&#xff1a;建立一个图像分类模型&#xff0c;提供自动识别有(猫、狗、飞机、汽车等等) 图片的功能 ResNet50图像分类 图像分类是最基础的计算机视觉应用&#xff0c;属于有监督学习类别&#xff0c;如给定一张图像(猫、狗、飞机、汽车等等)&#xff0c;判断图像所属的类…