【问题标题】:getting values of a torch tensor from a tensor of indices从索引张量中获取火炬张量的值
【发布时间】:2022-10-23 05:37:26
【问题描述】:

我提前为我的 pytorch 基础知识道歉,但是这个问题困扰了我一段时间。

假设我有一个形状为 (8,8,1) 的火炬张量 u,例如

u = tensor([[0.0000, 0.1429, 0.2857, 0.4286, 0.5714, 0.7143, 0.8571, 1.0000],
[0.0000, 0.1429, 0.2886, 0.4470, 0.5896, 0.7171, 0.8571, 1.0000],
[0.0000, 0.1446, 0.3182, 0.4934, 0.6302, 0.7424, 0.8588, 1.0000],
[0.0000, 0.1470, 0.3154, 0.4734, 0.5974, 0.7258, 0.8603, 1.0000],
[0.0000, 0.1397, 0.2742, 0.4026, 0.5266, 0.6846, 0.8530, 1.0000],
[0.0000, 0.1412, 0.2576, 0.3698, 0.5066, 0.6818, 0.8554, 1.0000],
[0.0000, 0.1429, 0.2829, 0.4104, 0.5530, 0.7114, 0.8571, 1.0000],
[0.0000, 0.1429, 0.2857, 0.4286, 0.5714, 0.7143, 0.8571, 1.0000]])

以及我感兴趣的 u 索引的大小 (2,8,8) 的张量

indices = tensor(
[[[0, 0, 0, 0, 0, 1, 0, 2],
[0, 3, 0, 4, 0, 5, 0, 5],
[0, 0, 0, 0, 0, 1, 0, 2],
[0, 3, 0, 4, 0, 5, 0, 5],
[1, 0, 0, 0, 0, 1, 0, 2],
[1, 3, 1, 4, 1, 5, 1, 5],
[2, 0, 1, 0, 1, 1, 1, 2],
[2, 3, 2, 4, 2, 5, 2, 5]],    

[[3, 0, 2, 0, 2, 0, 2, 1],
 [3, 2, 3, 3, 3, 4, 3, 5],
 [4, 0, 3, 0, 3, 0, 3, 1],
 [4, 2, 4, 3, 4, 4, 4, 5],
 [5, 0, 5, 0, 4, 0, 4, 1],
 [5, 2, 5, 3, 5, 5, 5, 5],
 [5, 0, 5, 0, 5, 1, 5, 2],
 [5, 3, 5, 4, 5, 5, 5, 5]]])

我想要一个与 u 大小相同的火炬张量结果,但在 result[i][j] = u[indices[0][i][j],indices[1][i][j] 的位置(例如:result[0][0] = u[0][3], result[0][1] = u[3][0], result[4][5] = u[5][0]...)

我尝试使用 torch.gather 但我根本无法让它工作,我尝试更改张量的 .view 但我无法匹配尺寸。有没有办法做到这一点?

【问题讨论】:

    标签: pytorch tensor torch indices


    【解决方案1】:

    首先重复 u 张量,如索引 [(8, 8) -> (2,8,8)] 的大小。之后你可以使用收集。

    repeated_u = u.unsqueeze(dim=0).repeat(indices.shape[0],1,1)
    result = torch.gather(repeated_u, 2, indices)
    

    【讨论】:

    • 感谢您的回答,问题是这样做我得到的是维度 (2,8,8) 的张量,其中计算两个第一个元素时考虑到索引的相应第一个和第二个元素(因此计算 repeated_u[0]通过indices[0]repeated_u[1] 通过indices[1]。我需要的可能可以通过将u 视为元素矩阵u[i][j] 来理解。由此我需要计算一个相同维度的张量,其中每个元素都有indices[0] 作为行索引和indices[1] 作为列索引的各自值。抱歉不清楚,我希望这是
    【解决方案2】:

    对于呈现的形状(u.shape -- (8, 8)indices.shape -- (2, 8, 8))似乎幼稚的索引工作正常result = u[indices[0], indices[1]]

    【讨论】:

    • 哦,我的上帝,谢谢,我不敢相信这会这么容易....我刚刚拿到了筹码,非常感谢
    猜你喜欢
    • 2022-07-20
    • 2016-07-20
    • 2016-06-27
    • 2020-06-11
    • 1970-01-01
    • 2020-10-26
    • 2021-06-18
    • 2020-08-02
    • 2021-07-19
    相关资源
    最近更新 更多