- 步骤
- 使用
torch.fliplr()
将张量左右颠倒 - 使用
torch.triu( )
取出颠倒后的张量的(主对角线的)上三角部分 - 再次使用
torch.fliplr()
将得到的张量左右颠倒
- 副对角线上的元素是否保留可以通过
torch.triu( )
中的参数diagonal
来控制,
- 当
diagonal=1
时即可不保留副对角线上的元素
import torch
b = torch.arange(0, 25).view((5, 5))
print(b)
'''
tensor([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
'''
o = torch.fliplr(b)
print(o)
'''
tensor([[ 4, 3, 2, 1, 0],
[ 9, 8, 7, 6, 5],
[14, 13, 12, 11, 10],
[19, 18, 17, 16, 15],
[24, 23, 22, 21, 20]])
'''
o = torch.triu(o, diagonal=0)
print(o)
'''
tensor([[ 4, 3, 2, 1, 0],
[ 0, 8, 7, 6, 5],
[ 0, 0, 12, 11, 10],
[ 0, 0, 0, 16, 15],
[ 0, 0, 0, 0, 20]])
'''
o = torch.fliplr(o)
print(o)
'''
tensor([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 0],
[10, 11, 12, 0, 0],
[15, 16, 0, 0, 0],
[20, 0, 0, 0, 0]])
'''