【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)]
]
相关推荐
小当家.1051 分钟前
AIGrader:一个 AI 作业批改平台的 Java EE 课设实战
java·人工智能·java-ee
weikecms1 分钟前
消费返物业费 + 小区本地生活 CPS 系统|微客云(物业 / 社区 / 本地服务商首选)
人工智能·微信·微客云
用户9940573931452 分钟前
从 Workflow 到 Agent:读 Anthropic 与 OpenAI Agent 指南后的理解
人工智能
萤丰信息2 分钟前
存量焕新 + 绿色低碳,2026 智慧园区转型新路径
大数据·人工智能
ZPC82102 分钟前
如何将机械臂末端定位精度提升至微米如何进行标定
人工智能·算法·机器人
黑暗森林观察者3 分钟前
DiffusionGemma:扩散模型从"画图"走向"写文章",文本生成速度提升4倍
人工智能
Web极客码3 分钟前
使用人工智能翻译WordPress网站
服务器·人工智能·wordpress
m沐沐4 分钟前
【深度学习】PyTorch CNN 手写数字识别(卷积神经网络)
人工智能·pytorch·python·深度学习·机器学习·pycharm·cnn
字节跳动数据库4 分钟前
AI 失控处理术
人工智能·claude
garmin Chen5 分钟前
Prompt工程入门:让AI按你的要求工作(3)--Prompt工程与提示词安全评测概述
java·人工智能·python·安全·prompt