张量(Tensor)操作
目录
1、torch.cat():将张量按照dim维度进行拼接
2、torch.stack():将张量在新创建的dim维度上进行拼接
3、torch.chunk():将张量按照维度 dim 进行平均切分。若不能整除,则最后一份张量小于其他张量
4、torch.split():将张量按照维度 dim 进行平均切分。可以指定每一个分量的切分长度
5、torch.index_select():在维度 dim 上,按照 index 索引取出数据拼接为张量返回
6、torch.mask_select():按照 mask 中的 True 进行索引拼接得到一维张量返回
7、torch.reshape():变换张量的形状
8、torch.transpose():交换张量的两个维度
9、torch.t():2 维张量转置
10、torch.squeeze()和torch.unsqueeze()见:
11、torch.add():逐元素计算 input + alpha * other
⭐首先补充一个tensor形状与维度之间的关系:
[[[1., 1., 1., 1.],[1., 1., 1., 1.],[1., 1., 1., 1.]],[[1., 1., 1., 1.],[1., 1., 1., 1.],[1., 1., 1., 1.]]
]
第一层(最外层)中括号里面包含了两对中括号(以逗号进行分割),这就是(2,3,4)中的2,即第0维度是2。
第二层中括号里面包含了三对中括号(以逗号进行分割),这就是(2,3,4)中的3,即第1维度是3。
第三层中括号里面包含了四个数(以逗号进行分割),这就是(2,3,4)中的4,即第2维度是4。
参考:张量——Pytorch中Tensor的维度,形状,意义_Discipline※的博客-CSDN博客_pytorch tensor维度
1、torch.cat():将张量按照dim维度进行拼接
torch.cat(tensors, dim=0, out=None)
tensors: 张量序列
dim: 要拼接的维度
例子:
import torch
t1 = torch.ones(2,3)
t2 = torch.zeros(2,3)
t_cat1 = torch.cat([t1,t2],dim = 0)
t_cat2 = torch.cat([t2,t1],dim = 0)
t_cat3 = torch.cat([t1,t2],dim = 1)
print(f"t_cat1:{t_cat1}")
print(f"t_cat2:{t_cat2}")
print(f"t_cat3:{t_cat3}")
运行后的结果为:
t_cat1:tensor([[1., 1., 1.],[1., 1., 1.],[0., 0., 0.],[0., 0., 0.]])
t_cat2:tensor([[0., 0., 0.],[0., 0., 0.],[1., 1., 1.],[1., 1., 1.]])
t_cat3:tensor([[1., 1., 1., 0., 0., 0.],[1., 1., 1., 0., 0., 0.]])
从t_cat1和t_cat2可以看出,拼接的两个张量如果顺序不同,输出的结果也不同。
2、torch.stack():将张量在新创建的dim维度上进行拼接
torch.stack(tensors, dim=0, out=None)
tensors: 张量序列
dim: 要拼接的维度
例子:
import torch
t1 = torch.ones(2,3)
t2 = torch.zeros(2,3)
t3 = torch.full((2,3),2)
t_stack1 = torch.stack([t1,t2,t3],dim = 0)
t_stack2 = torch.stack([t1,t2,t3],dim = 1)
t_stack3 = torch.stack([t1,t2,t3],dim = 2)
print(f"t_stack1:{t_stack1}")
print(f"t_stack2:{t_stack2}")
print(f"t_stack3:{t_stack3}")
运行后的结果为:
t_stack1:tensor([[[1., 1., 1.],[1., 1., 1.]],[[0., 0., 0.],[0., 0., 0.]],[[2., 2., 2.],[2., 2., 2.]]])
t_stack2:tensor([[[1., 1., 1.],[0., 0., 0.],[2., 2., 2.]],[[1., 1., 1.],[0., 0., 0.],[2., 2., 2.]]])
t_stack3:tensor([[[1., 0., 2.],[1., 0., 2.],[1., 0., 2.]],[[1., 0., 2.],[1., 0., 2.],[1., 0., 2.]]])
第一次指定拼接的维度 dim =2,结果的维度是 [2, 3, 3]。后面指定拼接的维度 dim =0,由于原来的 tensor 已经有了维度 0,因此会把 tensor 往后移动一个维度变为 [1,2,3],再拼接变为 [3,2,3]。
3、torch.chunk():将张量按照维度 dim 进行平均切分。若不能整除,则最后一份张量小于其他张量
torch.chunk(input, chunks, dim=0)
input: 要切分的张量
chunks: 要切分的份数
dim: 要切分的维度
例子:
a = torch.ones((2, 7)) # 7
list_of_tensors = torch.chunk(a, dim=1, chunks=3) # 3
for idx, t in enumerate(list_of_tensors):
print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
运行后的结果为:
第1个张量:tensor([[1., 1., 1.],[1., 1., 1.]]), shape is torch.Size([2, 3])
第2个张量:tensor([[1., 1., 1.],[1., 1., 1.]]), shape is torch.Size([2, 3])
第3个张量:tensor([[1.],[1.]]), shape is torch.Size([2, 1])
由于 7 不能整除 3,7/3 再向上取整是 3,因此前两个维度是 [2, 3],所以最后一个切分的张量维度是 [2,1]。
4、torch.split():将张量按照维度 dim 进行平均切分。可以指定每一个分量的切分长度
torch.split(tensor, split_size_or_sections, dim=0)
tensor: 要切分的张量
split_size_or_sections: 为 int 时,表示每一份的长度,如果不能被整除,则最后一份张量小于其他张量;为 list 时,按照 list 元素作为每一个分量的长度切分。如果 list 元素之和不等于切分维度 (dim) 的值,就会报错。
dim: 要切分的维度
例子:
t = torch.ones((2, 5))
list_of_tensors = torch.split(t, [2, 1, 2], dim=1)
for idx, t in enumerate(list_of_tensors):
print("第{}个张量:{}, shape is {}".format(idx+1, t, t.shape))
运行后的结果为:
第1个张量:tensor([[1., 1.],[1., 1.]]), shape is torch.Size([2, 2])
第2个张量:tensor([[1.],[1.]]), shape is torch.Size([2, 1])
第3个张量:tensor([[1., 1.],[1., 1.]]), shape is torch.Size([2, 2])
5、torch.index_select():在维度 dim 上,按照 index 索引取出数据拼接为张量返回
torch.index_select(input, dim, index, out=None)
input: 要索引的张量
dim: 要索引的维度
index: 要索引数据的序号
例子:
# 创建均匀分布
t = torch.randint(0, 9, size=(3, 3))
# 注意 idx 的 dtype 不能指定为 torch.float
idx = torch.tensor([0, 2], dtype=torch.long)
# 取出第 0 行和第 2 行
t_select = torch.index_select(t, dim=0, index=idx)
print("t:\n{}\nt_select:\n{}".format(t, t_select))
运行后的结果为:
t:
tensor([[4, 5, 0],[5, 7, 1],[2, 5, 8]])
t_select:
tensor([[4, 5, 0],[2, 5, 8]])
6、torch.mask_select():按照 mask 中的 True 进行索引拼接得到一维张量返回
torch.masked_select(input, mask, out=None)
要索引的张量
mask: 与 input 同形状的布尔类型张量
例子:
import torch
t = torch.randint(0, 9, size=(3, 3))
mask = t.le(5)
# 取出小于 5 的数
t_select = torch.masked_select(t, mask)
print("t:\n{}\nmask:\n{}\nt_select:\n{} ".format(t, mask, t_select))
运行后的结果为:
t:
tensor([[3, 2, 2],[4, 0, 4],[8, 7, 2]])
mask:
tensor([[ True, True, True],[ True, True, True],[False, False, True]])
t_select:
tensor([3, 2, 2, 4, 0, 4, 2])
7、torch.reshape():变换张量的形状
⭐当张量在内存中是连续时,返回的张量和原来的张量共享数据内存,当改变一个变量时,另一个变量也会被改变。
torch.reshape(input, shape)
input: 要变换的张量
shape: 新张量的形状
例子:
# 生成 0 到 8 的随机排列
t = torch.randperm(8)
# -1 表示这个维度是根据其他维度计算得出的
t_reshape = torch.reshape(t, (-1, 2, 2))
print("t:{}\nt_reshape:\n{}".format(t, t_reshape))
运行后的结果为:
t:tensor([6, 3, 5, 4, 2, 1, 0, 7])
t_reshape:
tensor([[[6, 3],[5, 4]],[[2, 1],[0, 7]]])
在上面代码的基础上,修改张量中的元素,新张量的元素也会随之改变。
8、torch.transpose():交换张量的两个维度
torch.transpose(input, dim0, dim1)
input: 要交换的变量
dim0: 要交换的第一个维度
dim1: 要交换的第二个维度
例子:
t = torch.rand((2, 3, 4))
t_transpose = torch.transpose(t, dim0=1, dim1=2) # c*h*w c*w*h
print("t shape:{}\nt_transpose shape: {}".format(t.shape, t_transpose.shape))
运行后的结果为:
t shape:torch.Size([2, 3, 4])
t_transpose shape: torch.Size([2, 4, 3])
9、torch.t():2 维张量转置
例子:
t = torch.randint(1,5,size=(3,3))
t_t = torch.t(t)
print("t:\n{}\nt_t:\n{}".format(t,t_t))
运行后的结果为:
tensor([[2, 2, 2],[3, 1, 3],[3, 4, 2]])
t_t:
tensor([[2, 3, 3],[2, 1, 4],[2, 3, 2]])
10、torch.squeeze()和torch.unsqueeze()见:
pytorch中squeeze()和unsqueeze()函数介绍_冲冲冲鸭鸭鸭~的博客-CSDN博客_pytorch squeeze()
11、torch.add():逐元素计算 input + alpha * other
torch.add(input, other, out=None)
torch.add(input, other, *, alpha=1, out=None)
input: 第一个张量
alpha: 乘项因子
other: 第二个张量
参考:[PyTorch 学习笔记] 1.3 张量操作与线性回归
张量(Tensor)操作相关推荐
- pytorch张量(tensor)常用高级操作函数
张量创建 张量拼接.切分.索引和变换 torch.cat(),torch.concentrate(),torch.concat() 注:这三个函数是等价的 函数:torch.cat(tensors, ...
- Tensorflow:张量(Tensor)的创建及其基础操作
Tensorflow版本:V2.8.0 Tensorflow中所有的运算操作都是基于张量进行的.Tensorflow中的张量Tensor是具有统一类型的多维数组.这篇博文主要介绍张量的创建及基础操 ...
- Pytorch张量tensor的使用
1. 张量Tensor Tensors张量: 张量的概念类似于Numpy中的ndarray数据结构, 最大的区别在于Tensor可以利用GPU的加速功能. 张量是一个统称,其中包含很多类型: [各 ...
- 深度学习框架pytorch入门之张量Tensor(一)
文章目录 一.简介 二.查看帮助文档 三.Tensor常用方法 1.概述 2.新建方法 (1)Tensor(*sizes) tensor基础构造函数 (2)ones(*sizes) 构造一个全为1的T ...
- 张量tensor学习笔记
一.前言 上篇博文我们介绍了numpy和pandas.这篇博文我们主要来介绍下pytorch里面的数据结构tensor.tensor是pytorch中最基础的知识,下面我们主要介绍tensor的基 ...
- Pytorch入门之张量tensor
一.张量tensor 张量的三个特征:秩.轴.形状 张量的秩是指索引的个数,轴是指每一个维度的最大的索引的值,张量的形状提供了维度和索引的数量关系. 经常需要对张量进行重塑 t.reshape(1,9 ...
- tensor转换为图片_pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
1, 创建pytorch 的Tensor张量: torch.rand((3,224,224)) #创建随机值的三维张量,大小为(3,224,224) torch.Tensor([3,2]) #创建张量 ...
- pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换 1, 创建pytorch 的Tensor张量: torch.rand((3,224,224)) #创建随机值的三维张量,大小为 ...
- 什么是张量 (tensor)?
在TensorFlow 官方文档中文版中学习cifar10时,对张量Tensor的概念一知半解,特别在理解代码如何批量读取图片,如何实现卷积的细节困扰了我好几天,在查询网上的资料后总结如下: 一.Te ...
- pytorch 创建张量tensor
pytorch 创建张量tensor 先看下面一张图 通过上图有了一个直观了解后,我们开始尝试创建一下. 先创建一个标量和一个向量 a = torch.tensor([1]) #标量 print(a) ...
最新文章
- 二叉查找树的C语言实现(一)
- VSCode 启动 Vue 项目 npm install 报错
- [ZJOI2008] 树的统计(树链剖分)
- javascript构造函数继承
- C# 10 完整特性介绍
- JavaEE基础(03):Http请求详解,握手挥手流程简介
- eclipse 快捷键收藏
- ARM版Win11系统(intel版Win10/11系统)
- Java创建型设计模式之简单工厂,工厂方法,抽象工厂
- 微信公众号js复制到手机剪贴板
- 数据治理-数据质量-数据质量参考架构
- 电脑鼠标双击桌面图标打不开怎么办
- 使用软碟通安装win7
- 彻底解决Missing privilege separation directory: /run/sshd
- WPS如何生成指定区间随机数
- Python获取日期是星期几
- Aimersoft iMusic for mac(音乐下载传输工具)
- 双十一活动三个阶段分别需要做什么,双十一怎样引流,双十一怎样开直通车
- 如何c语言解析html中的图片地址,【c语言】使用gumbo解析HTML
- 《Deep Learning from Scratch》鱼书学习笔记 3-6,7 手写数字的识别