DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Updated on

diag in PyTorch

Buy Me a Coffee

*Memos:

diag() can create the 2D tensor of zero or more elements on the diagonal and zero or more 0, 0., 0.+0.j or False elsewhere from the 1D tensor of zero or more elements or can extract the 1D tensor of zero or more elements on the diagonal from the 2D tensor of zero or more elements as shown below:

*Memos:

  • diag() can be used with torch or a tensor.
  • The 1st argument(input) with torch or using a tensor(Required-Type:tensor of int, float, complex or bool). *Only a 2D or 1D tensor can be used.
  • The 2nd argument with torch or the 1st argument with a tensor is diagonal(Optional-Default:0-Type:int).
  • There is out argument with torch(Optional-Default:None-Type:tensor): *Memos:
    • out= must be used.
    • My post explains out argument.
  • A 2D tensor creates a 1D tensor.
  • A 1D tensor creates a 2D tensor.
import torch

my_tensor = torch.tensor([7, -4, 5])

torch.diag(input=my_tensor)
my_tensor.diag()
torch.diag(input=my_tensor, diagonal=0)
# tensor([[7, 0, 0],
#         [0, -4, 0],
#         [0, 0, 5]])

torch.diag(input=my_tensor, diagonal=1)
# tensor([[0, 7, 0, 0],
#         [0, 0, -4, 0],
#         [0, 0, 0, 5],
#         [0, 0, 0, 0]])

torch.diag(input=my_tensor, diagonal=-1)
# tensor([[0, 0, 0, 0],
#         [7, 0, 0, 0],
#         [0, -4, 0, 0],
#         [0, 0, 5, 0]])

torch.diag(input=my_tensor, diagonal=2)
# tensor([[0, 0, 7, 0, 0],
#         [0, 0, 0, -4, 0],
#         [0, 0, 0, 0, 5],
#         [0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0]])

torch.diag(input=my_tensor, diagonal=-2)
# tensor([[0, 0, 0, 0, 0],
#         [0, 0, 0, 0, 0],
#         [7, 0, 0, 0, 0],
#         [0, -4, 0, 0, 0],
#         [0, 0, 5, 0, 0]])

my_tensor = torch.tensor([7., -4., 5.])

torch.diag(input=my_tensor)
# tensor([[7., 0., 0.],
#         [0., -4., 0.],
#         [0., 0., 5.]])

my_tensor = torch.tensor([7.+0.j, -4.+0.j, 5.+0.j])

torch.diag(input=my_tensor)
# tensor([[7.+0.j, 0.+0.j, 0.+0.j],
#         [0.+0.j, -4.+0.j, 0.+0.j],
#         [0.+0.j, 0.+0.j, 5.+0.j]])

my_tensor = torch.tensor([True, True, True])

torch.diag(input=my_tensor)
# tensor([[True, False, False],
#         [False, True, False],
#         [False, False, True]])

my_tensor = torch.tensor([[7, -4, 5],
                          [-6, -3, 8],
                          [9, 1, -2]])
torch.diag(input=my_tensor)
torch.diag(input=my_tensor, diagonal=0)
# tensor([7, -3, -2])

torch.diag(input=my_tensor, diagonal=1)
# tensor([-4, 8])

torch.diag(input=my_tensor, diagonal=-1)
# tensor([-6, -1])

torch.diag(input=my_tensor, diagonal=2)
# tensor([5])

torch.diag(input=my_tensor, diagonal=-2)
# tensor([9])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)