【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)]
]
相关推荐
小虎AI生活10 分钟前
朋友圈发了没人理?这个AI技能一句话甩你4个版本,做私域的都能用
人工智能·超级个体·青玥ai
龙腾AI白云17 分钟前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
aimartec27 分钟前
不动老旧 ERP 核心总账,如何以高性价比方案落地外勤与车间移动协同?
人工智能
艾派森40 分钟前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔1 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
Csvn1 小时前
让 AI 少返工:任务卡六要素与四维验收怎么写
人工智能
老纪的技术唠嗑局1 小时前
新增项目知识库,网关也能帮 Agent 找回记忆|PowerContext v1.6.0 发布
人工智能
用户842558130871 小时前
插值选错,峰值就没了
人工智能
小宋10211 小时前
embedding 返回全零向量,索引却照收不误:入库前的向量健康门禁、隔离重算与召回恢复判据
linux·服务器·网络·人工智能
2401_868534781 小时前
55 个热门网络面试问题及答案
网络·python