【问题标题】:How can I replace the entries of a tensor with the appropriate ranking of each entry?如何用每个条目的适当排名替换张量的条目?
【发布时间】:2025-12-10 07:55:02
【问题描述】:

假设我有以下张量:

>> i = 3
>> j = 5
>> k = 2
>> sor = torch.randn(i,j,k)

>> sor
Out[20]: 
tensor([[[ 0.5604, -0.9675],
         [-1.0953, -0.5615],
         [ 0.4250, -0.9176],
         [-1.6188, -1.0217],
         [-0.0778,  1.9407]],

        [[-0.1034, -0.7925],
         [-0.2955,  0.8058],
         [-0.5349,  1.1040],
         [ 1.1240,  0.8249],
         [ 0.0827, -1.2471]],

        [[ 0.5924,  0.4777],
         [-2.4640, -1.9527],
         [-0.4519,  0.4788],
         [-0.2308, -0.2368],
         [-1.6786,  0.1360]]])

假设对于每个固定的ij,我想计算k 中元素的数字等级,并用这些等级替换张量sor 的元素。例如,从上面的示例中,我想将条目 [ 0.5604, -0.9675](即 sor[0,0,:])更改为 [1, 2],因为 0.5604 > -0.9675

谢谢,

【问题讨论】:

    标签: python tensorflow pytorch ranking tensor


    【解决方案1】:

    我想你在找torch.argsort:

    torch.argsort(sor, dim=2)
    
    Out[ ]:
    tensor([[[1, 0],
             [0, 1],
             [1, 0],
             [0, 1],
             [0, 1]],
    
            [[1, 0],
             [0, 1],
             [0, 1],
             [1, 0],
             [1, 0]],
    
            [[1, 0],
             [0, 1],
             [0, 1],
             [1, 0],
             [0, 1]]])
    

    【讨论】:

      最近更新 更多