【pytorch】torch.gather()函数

dim=0时

python 复制代码
index=[ [x1,x2,x2],
		[y1,y2,y2],
		[z1,z2,z3] ]

如果dim=0
填入方式为:
index=[ [(x1,0),(x2,1),(x3,2)]
		[(y1,0),(y2,1),(y3,2)]
		[(z1,0),(z2,1),(z3,2)] ]
python 复制代码
input = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
] # shape(3,4)
input = torch.tensor(input)
length = torch.LongTensor([
    [2,2,2,2],
    [1,1,1,1],
    [0,0,0,0],
    [0,1,2,0]
])# shape(4,4)
out = torch.gather(input, dim=0, index=length)
print(out)
python 复制代码
tensor([[9, 10, 11, 12],
        [5, 6, 7, 8],
        [1, 2, 3, 4],
        [1, 6, 11, 4]])
python 复制代码
#### dim=0后,根据new_index对input进行索引
new_index=[ [(2,0),(2,1),(2,2),(2,3)],
			[(1,0),(1,1),(1,2),(1,3)],
			[(0,0),(0,1),(0,2),(0,3)],
			[(0,0),(1,1),(2,2),(0,3)] ]
			
可以观察到第四行,行索引变为0,所以当gather函数里的index超过input的唯独时,会从0重新计数。

dim=1时

python 复制代码
input = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
] # shape(3,4)
input = torch.tensor(input)
length = torch.LongTensor([
    [2,2,2,2],
    [1,1,1,1],
    [0,1,2,0]
]) # shape(3,4)
out = torch.gather(input, dim=1, index=length)
print(out)
python 复制代码
tensor([[3, 3, 3, 3],
        [6, 6, 6, 6],
        [9, 10, 11, 9]])
python 复制代码
new_index = [
	[(0,2),(0,2),(0,2),(0,2)],
	[(1,1),(1,1),(1,1),(1,1)],
	[(2,0),(2,1),(2,2)(2,0)]
]
相关推荐
研华科技Advantech3 分钟前
储能AI化的数据瓶颈与破解路径:研华全栈方案实践分析
数据库·人工智能·储能·智能体
一瞬祈望7 分钟前
【环境配置】Windows 下使用 Anaconda 创建 Python 3.8 环境 + 安装 PyTorch + CUDA(完整教程)
pytorch·windows·python
小兔崽子去哪了18 分钟前
RFM 模型 项目实战
python
Likeadust29 分钟前
视频直播点播平台EasyDSS助力企业打造全场景数字化宣传体系
运维·人工智能·音视频
昨天那个谁谁30 分钟前
ROS2运行时报无法加载create_key等符号错误
c++·python·ros2
韩曙亮44 分钟前
【AI 大模型】LangChain 框架 ① ( LangChain 简介 | LangChain 模块 | LangChain 文档 )
人工智能·ai·langchain·llm·大语言模型·prompts·agents
码农阿豪1 小时前
本地 AI 模型随心用!Cherry Studio + cpolar解锁跨设备智能办公
人工智能
通义灵码1 小时前
用 Qoder 加速前端巨石应用的架构演进
前端·人工智能·架构·qoder
一水鉴天1 小时前
整体设计 定稿 之21 拼语言表述体系之3 dashboard.html V5(codebuddy)
前端·人工智能·架构
nju_spy1 小时前
python 算法题基础常用总结(比赛 or 机试 or 面试)
python·记忆化搜索·位运算·二分查找 - bisect·排序与lambda·最短路和最小生成树·堆与优先队列