How to use PyTorch to softmax only the upper triangular elements of a matrix?

Viewed 540

Given input like:

tensor([[[1.9392, -1.9266,  0.9664],
         [0.0000, -1.9266,  0.9664],
         [0.0000, -0.0000,  0.9664]]])

My desired output is:

tensor([[[0.4596,  0.0096, 0.1737],
         [0.0000,  0.0096, 0.1737],
         [0.0000, -0.0000, 0.1737]]])

I.e. just calculating the function over the upper triangular elements.

1 Answers

You can access the upper triangular elements with torch.triu_indices:

t = tensor([[1.9392, -1.9266, 0.9664], 
            [0.0000, -1.9266, 0.9664], 
            [0.0000, -0.0000, 0.9664]]) 

idx = torch.triu_indices(*t.shape)
soft = F.softmax(t[idx[0], idx[1]], dim=0)

If you want to reassign the values as in your desired output:

>>> t[idx[0], idx[1]] = soft
>>> t
tensor([[0.4596,  0.0096, 0.1737],
        [0.0000,  0.0096, 0.1737],
        [0.0000, -0.0000, 0.1737]])
Related