tensor向量按任意维度进行切片、拆分、组合

torch.index_select(input_tensor, 切片维度, 切片索引)

注意:切完之后,转onnx时会生成Gather节点;

torch自带切片操作

start : end : step:

范围前闭后开,将其放在哪个维度上,就对那个维度起作用

torch.cat((a, b) , dim)

已有的轴上拼接 矩阵,默认轴为0,给定轴的维度可以不同,其余轴的维度必须相同

三个操作的组合使用例子如下:

python 复制代码
import torch

x = torch.randn(1, 18, 4, 4)

# print("x:",x)
print("x.shape:",x.shape)

indices_cls = torch.tensor([2, 5, 8, 11, 14, 17])
indices_point = torch.tensor([0,1, 3,4, 6,7, 9,10, 12,13, 15,16])

kpt_point = torch.index_select(x, 1, indices_point)
kpt_cls = torch.index_select(x, 1, indices_cls)

print("kpt_point.shape:",kpt_point.shape)
print("kpt_cls.shape:",kpt_cls.shape)


x_2 = torch.cat([kpt_point[:,0:2:1,],kpt_cls[:,0:1:1,],kpt_point[:,2:4:1,],kpt_cls[:,1:2:1,],kpt_point[:,4:6:1,],kpt_cls[:,2:3:1,],
            kpt_point[:,6:8:1,],kpt_cls[:,3:4:1,],kpt_point[:,8:10:1,],kpt_cls[:,4:5:1,],kpt_point[:,10:12:1,],kpt_cls[:,5:6:1,]],1)

# print("x_2:",x_2)
print("x_2.shape:",x_2.shape)

打印组合前后tensor的输出形状和内容发现,前后一致:

python 复制代码
x.shape: torch.Size([1, 18, 4, 4])
kpt_point.shape: torch.Size([1, 12, 4, 4])
kpt_cls.shape: torch.Size([1, 6, 4, 4])   
x_2.shape: torch.Size([1, 18, 4, 4])   
相关推荐
二十雨辰10 分钟前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码21 分钟前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
前端摸鱼匠1 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove13141 小时前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch1 小时前
大麦网协议分析
javascript·python
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh2 小时前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh2 小时前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
YongCheng_Liang2 小时前
从零开始学 Python:自动化 / 运维开发实战(核心库 + 3 大实战场景)
python·自动化·运维开发
鸽芷咕3 小时前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann