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
- n (int): The number of rows in the returned tensor.
- m (int, optional): The number of columns in the returned tensor. If None, it defaults to n.
- out (Tensor, optional): The output tensor.
- dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: If none, use a global default.
- layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
- device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
- 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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.