【问题标题】:How to slice a Torch tensor by a set of indices?如何通过一组索引切片 Torch 张量?
【发布时间】:2021-02-21 00:31:33
【问题描述】:

我想知道是否有一种有效的方法可以通过一组索引对张量进行切片?在 Matlab 中,我可以执行以下操作:

A = rand(2, 3, 6);
B = A(:,:, 1:2:end);

那么 B 是 A 的第 1、3、5 个切片。

在 Torch 中,您似乎只能在连续范围内进行切片。这是真的吗?

一个更普遍的问题是我是否可以通过诸如

之类的任意索引获得一个子集
A(:, :, [1 2 6]) 

在 Matlab 中。

提前致谢!

【问题讨论】:

    标签: python slice torch


    【解决方案1】:

    使用index 运算符,例如:

    t = torch.rand(2, 3, 6)
    -- (1,.,.) = 
    --   0.1790  0.7774  0.5343  0.0628  0.3077  0.7203
    --   0.0677  0.5847  0.2401  0.6885  0.8724  0.4413
    --   0.1849  0.2704  0.2745  0.5508  0.4634  0.6340
    -- 
    -- (2,.,.) = 
    --   0.2523  0.6135  0.6037  0.0194  0.6456  0.0229
    --   0.9966  0.8688  0.2078  0.7169  0.1528  0.5708
    --   0.8671  0.7731  0.4596  0.0636  0.8873  0.2205
    -- [torch.DoubleTensor of size 2x3x6]
    
    
    t:index(3, torch.LongTensor{1, 3, 5})
    -- (1,.,.) = 
    --   0.1790  0.5343  0.3077
    --   0.0677  0.2401  0.8724
    --   0.1849  0.2745  0.4634
    -- 
    -- (2,.,.) = 
    --   0.2523  0.6037  0.6456
    --   0.9966  0.2078  0.1528
    --   0.8671  0.4596  0.8873
    -- [torch.DoubleTensor of size 2x3x3]
    

    你也可以t:index(3, torch.LongTensor{1, 2, 6})

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 2017-09-11
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多