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.]]])
"""
相关推荐
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8247 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员7 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋7 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
AntBlack8 小时前
不当韭菜V1.1 :增强能力 ,辅助构建自己的交易规则
后端·python·pyqt
Moshow郑锴9 小时前
机器学习的特征工程(特征构造、特征选择、特征转换和特征提取)详解
人工智能·机器学习
C++、Java和Python的菜鸟10 小时前
第六章 统计初步
算法·机器学习·概率论
杜子不疼.10 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
myzzb11 小时前
基于uiautomation的自动化流程RPA开源开发演示
运维·python·学习·算法·自动化·rpa
TLuoQiu11 小时前
小电视视频内容获取GUI工具
爬虫·python