原理介绍:
①用排序方法sort对张量按列排序,得到排序后索引“new_sort_index”
②将new_sort_index中,每行中所有元素的索引,替换成“某列”的索引
③用重索引方法gather把原张量按新索引重构,得到结果
import torch
# !!!!!!!!!!张量排序,按某个竖轴的大小来排序!!!!!!!!!!!!!!!!!!
tensor = torch.rand((5, 99))
# 作为“索引依据”的列位置
main_index = 0
# 进行排序,按每一“列”中的数据大小排序
_, new_sort_index = torch.sort(tensor, descending=False, dim=0) # descending“正序or倒序”,dim=0“竖轴”
# 把每一列的其它数据,都按”排序依据“的大小来排序
for index in range(new_sort_index.shape[0]):
for flag in range(new_sort_index[index].shape[0]):
if flag != main_index:
# 把其它被打乱的索引,都换成当前”排序依据“的索引
new_sort_index[index][flag] = new_sort_index[index][main_index]
# 将原列表,按排序后的索引重新生成
tensor = torch.gather(tensor, 0, new_sort_index)