【问题标题】:Expand 1d tensor to 2d tensor along with the diagonal of the 2d tensor in pytorch [duplicate]将 1d 张量与 pytorch 中 2d 张量的对角线一起扩展为 2d 张量 [重复]
【发布时间】:2021-06-10 04:18:59
【问题描述】:

有什么方法可以在 Pytorch 中将一维 tensor([[1., 2., 3., 4.]]) 转换为

tensor([[1., 2., 3., 4.], 
        [2., 1., 2., 3.], 
        [3., 2., 1., 2.], 
        [4., 3., 2., 1.]]) 

【问题讨论】:

  • 看起来您正在计算与对角线的距离,而不是扩展。你到底在追求什么?

标签: python pytorch tensor


【解决方案1】:

torch.roll 不幸的是仅适用于维度,因此您必须使用expand 并使用torch.gather 之类的东西,以及一组索引移位:

t = tensor([[1., 2., 3., 4.]])

idx = torch.arange(4)
idx = torch.stack([torch.roll(idx, shift) for shift in range(0,-4,-1)])

torch.gather(t.expand(4,-1), 1, idx)

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多