【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)]
]
相关推荐
victory04317 分钟前
Gradio实现中英文切换,不影响页面状态,不得刷新页面情况下
人工智能
u0109272718 分钟前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
MediaTea15 分钟前
<span class=“js_title_inner“>Python:实例对象</span>
开发语言·前端·javascript·python·ecmascript
微光闪现22 分钟前
践行“科技向善”,微乐播捐赠108,888元助力唇腭裂儿童绽放笑容
人工智能
闵帆30 分钟前
反演学习器面临的鸿沟
人工智能·学习·机器学习
feasibility.32 分钟前
多模态模型Qwen3-VL在Llama-Factory中断LoRA微调训练+测试+导出+部署全流程--以具身智能数据集open-eqa为例
人工智能·python·大模型·nlp·llama·多模态·具身智能
我需要一个支点32 分钟前
douyin无水印视频下载
爬虫·python
喵手34 分钟前
Python爬虫实战:采集各大会展平台的展会名称、举办时间、展馆地点、主办方、行业分类等结构化数据(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集大会展平台信息·展会名称举办时间展馆地址·采集数据csv/json导出
编码者卢布1 小时前
【Azure APIM】如何实现对经过APIM并到达后端服务请求的全链路追踪呢?
python·flask·azure
CDA数据分析师干货分享1 小时前
【干货】CDA一级知识点拆解1:《CDA一级商业数据分析》第1章 数据分析思维
数据库·人工智能·数据分析·cda证书·cda数据分析师