DEV Community

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

Posted on • Edited on

eye in PyTorch

Buy Me a Coffee

*Memos:

eye() can create the 2D tensor with zero or more 1.(Default), 1, 1.+0.j or True on the diagonal and zero or more 0.(Default), 0, 0.+0.j or False elsewhere as shown below:

*Memos:

  • eye() can be used with torch but not with a tensor.
  • The 1st argument with torch is n(Required-Type:int) which is the number of rows.
  • The 2nd argument with torch is m(Optional-Default:n-Type:int) which is the number of columns.
  • There is dtype argument with torch(Optional-Default:None-Type:dtype): *Memos:
  • There is device argument with torch(Optional-Default:None-Type:str, int or device()): *Memos:
  • There is requires_grad argument with torch(Optional-Default:False-Type:bool): *Memos:
    • requires_grad= must be used.
    • My post explains requires_grad argument.
  • There is out argument with torch(Optional-Default:None-Type:tensor): *Memos:
    • out= must be used.
    • My post explains out argument.
import torch

torch.eye(n=0)
# tensor([], size=(0, 0))

torch.eye(n=1)
# tensor([[1.]])

torch.eye(n=2)
# tensor([[1., 0.],
#         [0., 1.]])

torch.eye(n=3)
# tensor([[1., 0., 0.],
#         [0., 1., 0.],
#         [0., 0., 1.]])

torch.eye(n=4)
# tensor([[1., 0., 0., 0.],
#         [0., 1., 0., 0.],
#         [0., 0., 1., 0.],
#         [0., 0., 0., 1.]])

torch.eye(n=4, m=0)
# tensor([], size=(4, 0))

torch.eye(n=4, m=1)
# tensor([[1.],
#         [0.],
#         [0.],
#         [0.]])

torch.eye(n=4, m=2)
# tensor([[1., 0.],
#         [0., 1.],
#         [0., 0.],
#         [0., 0.]])

torch.eye(n=4, m=3)
# tensor([[1., 0., 0.],
#         [0., 1., 0.],
#         [0., 0., 1.],
#         [0., 0., 0.]])

torch.eye(n=4, m=4)
# tensor([[1., 0., 0., 0.],
#         [0., 1., 0., 0.],
#         [0., 0., 1., 0.],
#         [0., 0., 0., 1.]])

torch.eye(n=4, m=5)
# tensor([[1., 0., 0., 0., 0.],
#         [0., 1., 0., 0., 0.],
#         [0., 0., 1., 0., 0.],
#         [0., 0., 0., 1., 0.]])

torch.eye(n=4, m=6)
# tensor([[1., 0., 0., 0., 0., 0.],
#         [0., 1., 0., 0., 0., 0.],
#         [0., 0., 1., 0., 0., 0.],
#         [0., 0., 0., 1., 0., 0.]])

torch.eye(n=4, m=6, dtype=torch.int64)
# tensor([[1, 0, 0, 0, 0, 0],
#         [0, 1, 0, 0, 0, 0],
#         [0, 0, 1, 0, 0, 0],
#         [0, 0, 0, 1, 0, 0]])

torch.eye(n=4, m=6, dtype=torch.complex64)
# tensor([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
#         [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
#         [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
#         [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])

torch.eye(n=4, m=6, dtype=torch.bool)
# tensor([[True, False, False, False, False, False],
#         [False, True, False, False, False, False],
#         [False, False, True, False, False, False],
#         [False, False, False, True, False, False]])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)