PyTorch torch.eye() Method

The torch.eye() method returns a 2-D tensor with ones on the diagonal and zeros elsewhere.

Syntax

torch.eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, 
          device=None, requires_grad=False)

Parameters

  1. n (int): The number of rows in the returned tensor.
  2. m (int, optional): The number of columns in the returned tensor. If None, it defaults to n.
  3. out (Tensor, optional): The output tensor.
  4. dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: If none, use a global default.
  5. layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
  6. device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
  7. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.

Example 1: How to Use torch.eye() method

import torch

# Create a 3x3 identity matrix
tensor = torch.eye(3)

print(tensor)

Output

tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

Example 2: Non-square Identity Matrix

Generate a 3×5 tensor with ones on the diagonal and zeros elsewhere.

import torch

# Create a 3x5 matrix with ones on the diagonal
tensor1 = torch.eye(3, 5)

print(tensor1)

Output

tensor([[1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.]])

Example 3: Identity Matrix with requires_grad Parameter

Generate a 4×4 identity matrix with gradient computation enabled.

import torch

# Create a 4x4 identity matrix with gradient computation enabled
tensor2 = torch.eye(4, requires_grad=True)

print(tensor2)

Output

tensor([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]], requires_grad=True)

Executing the above code examples will produce tensors as described. The first tensor will be a 3×5 matrix with ones on the diagonal and zeros elsewhere. The second tensor will be a 4×4 identity matrix with gradient computation enabled.

That’s it!

Leave a Comment