Torch.gather

1.官方文档

2.使用要点

  • 输入index的shape等于输出value的shape
  • 输入index的索引值仅替换该index中对应dim的index值
  • 最终输出为替换index后在原tensor中的值

最终输出的shape和index的shape相同

根据dim的值 选择将index[i,j,k]这个结果替换input[i,j,k]里面对应的i or j or k ,并将结果存储到output[i,j,k]

3.实际应用

一维

python 复制代码
import torch
import torch.nn as nn
arr = torch.tensor([1, 2, 3])
index = torch.tensor([0, 1])
result = torch.gather(arr,0, index)
print(result)
"""
tensor([1, 2])
"""

二维

python 复制代码
import torch
arr = torch.tensor([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
index = torch.tensor([[0, 1],
                  [1, 2]])
result = torch.gather(arr,1, index)
print(result)
"""
dim=0
tensor([[1, 5],
        [4, 8]])
dim=1
tensor([[1, 2],
        [5, 6]])
"""

三维

python 复制代码
import torch
# 创建一个较小的三维张量
tensor_3d = torch.tensor([
    [[1, 2],
     [3, 4]],
    [[5, 6],
     [7, 8]]
], dtype=torch.float32)
# 创建索引张量
index_3d = torch.tensor([
    [[0, 1],
     [1, 0]],
    [[1, 0],
     [0, 1]]
], dtype=torch.long)
# 在 dim = 0 上进行 gather 操作
result_dim0 = tensor_3d.gather(dim=0, index=index_3d)
print("在 dim = 0 上的 gather 结果:")
print(result_dim0)
# 在 dim = 1 上进行 gather 操作
result_dim1 = tensor_3d.gather(dim=1, index=index_3d)
print("在 dim = 1 上的 gather 结果:")
print(result_dim1)
# 在 dim = 2 上进行 gather 操作
result_dim2 = tensor_3d.gather(dim=2, index=index_3d)
print("在 dim = 2 上的 gather 结果:")
print(result_dim2)
"""
在 dim = 0 上的 gather 结果:
tensor([[[1., 6.],
         [7., 4.]],

        [[5., 2.],
         [3., 8.]]])
在 dim = 1 上的 gather 结果:
tensor([[[1., 4.],
         [3., 2.]],

        [[7., 6.],
         [5., 8.]]])
在 dim = 2 上的 gather 结果:
tensor([[[1., 2.],
         [4., 3.]],

        [[6., 5.],
         [7., 8.]]])
"""
相关推荐
大霞上仙37 分钟前
nonlocal 与global关键字
开发语言·python
Mark_Aussie1 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙1 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
红衣小蛇妖1 小时前
神经网络-Day44
人工智能·深度学习·神经网络
ZHOU_WUYI1 小时前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
且慢.5892 小时前
Python_day47
python·深度学习·计算机视觉
佩奇的技术笔记2 小时前
Python入门手册:异常处理
python
大写-凌祁2 小时前
论文阅读:HySCDG生成式数据处理流程
论文阅读·人工智能·笔记·python·机器学习
柯南二号2 小时前
深入理解 Agent 与 LLM 的区别:从智能体到语言模型
人工智能·机器学习·llm·agent
爱喝喜茶爱吃烤冷面的小黑黑2 小时前
小黑一层层削苹果皮式大模型应用探索:langchain中智能体思考和执行工具的demo
python·langchain·代理模式