【问题标题】:Pytorch: accessing a subtensor using lists of indicesPytorch:使用索引列表访问子张量
【发布时间】:2020-06-04 16:55:24
【问题描述】:

我有一对张量 ST,尺寸为 (s1,...,sm)(t1,...,tn)si < ti。我想在T 的每个维度中指定一个索引列表以“嵌入”ST 中。如果I1(0,1,...,t1) 中的s1 索引列表,同样对于I2In,我想做类似的事情 T.select(I1,...,In)=S 这将产生现在T 的条目等于S 在索引(I1,...,In) 上的条目的效果。 例如

`S=
[[1,1],
[1,1]]

T=
[[0,0,0],
[0,0,0],
[0,0,0]]

T.select([0,2],[0,2])=S

T=
[[1,0,1],
[0,0,0],
[1,0,1]]`

【问题讨论】:

  • 为什么我们不“填写”T 的第二行?这些信息在哪里编码?

标签: python pytorch tensor matrix-indexing tensor-indexing


【解决方案1】:

如果您可以灵活地使用 NumPy仅用于索引部分,那么这是一种方法,即使用 numpy.ix_() 构造一个开放网格并使用此网格填充张量中的值S。如果这不可接受,那么您可以使用torch.meshgrid()

下面是这两种方法的说明,其中散布在 cmets 中的描述。

# input tensors to work with
In [174]: T 
Out[174]: 
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])

# I'm using unique tensor just for clarity; But any tensor should work.
In [175]: S 
Out[175]: 
tensor([[10, 11],
        [12, 13]])

# indices where we want the values from `S` to be filled in, along both dimensions
In [176]: idxs = [[0,2], [0,2]] 

现在我们将利用np.ix_()torch.meshgrid() 通过传入索引来生成开放网格:

# mesh using `np.ix_`
In [177]: mesh = np.ix_(*idxs)

# as an alternative, we can use `torch.meshgrid()` 
In [191]: mesh = torch.meshgrid([torch.tensor(lst) for lst in idxs])

# replace the values from tensor `S` using basic indexing
In [178]: T[mesh] = S 

# sanity check!
In [179]: T 
Out[179]:
tensor([[10,  0, 11],
        [ 0,  0,  0],
        [12,  0, 13]])

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2019-11-26
    • 2019-02-05
    • 1970-01-01
    • 2022-11-24
    • 2021-12-16
    • 1970-01-01
    • 2020-09-26
    • 2021-11-04
    相关资源
    最近更新 更多