首页 > 解决方案 > 将 1d 张量连同 pytorch 中 2d 张量的对角线展开为 2d 张量

问题描述

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

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

标签: pythonpytorchtensor

解决方案


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)

推荐阅读