Python 使用_scatter()替换矩阵中的值

Python 使用_scatter()替换矩阵中的值,python,sorting,pytorch,tensor,Python,Sorting,Pytorch,Tensor,给定以下两个张量: x=torch.tensor([[1,2], [2, 0], [0, 0]], [[2, 2], [2, 0], [3,3]]]#[批量大小x序列长度x子序列长度] y=火炬张量([[2,1,0], [2,1,2]]#[批次大小x序列长度] 我想根据序列的子序列长度对x中的序列进行排序(0对应于序列中的填充)y对应于x中子序列的长度。我尝试了以下方法: y\u排序,y\u排序\u idx=y.sort(dim=1,降序=True) 打印(x.scatter(dim=1,in

给定以下两个张量:

x=torch.tensor([[1,2],
[2, 0],
[0, 0]],
[[2, 2],
[2, 0],
[3,3]]]#[批量大小x序列长度x子序列长度]
y=火炬张量([[2,1,0],
[2,1,2]]#[批次大小x序列长度]
我想根据序列的子序列长度对x中的序列进行排序(0对应于序列中的填充)
y
对应于x中子序列的长度。我尝试了以下方法:

y\u排序,y\u排序\u idx=y.sort(dim=1,降序=True)
打印(x.scatter(dim=1,index=y\u sort\u idx.unsqueze(2),src=x))
这导致:

张量([[1,2],
[2, 0],
[0, 0]],
[[2, 2],
[2, 0],
[2, 3]]])
然而,我想要实现的是:

张量([[1,2],
[2, 0],
[0, 0]],
[[2, 2],
[3, 3],
[2, 0]]])
这应该可以

y_sorted, y_sort_idx = y.sort(dim=1, descending=True)
index = y_sort_idx.unsqueeze(2).expand_as(x)
x = x.gather(dim=1, index=index)