Initialize an identity matrix for linear algebra or model components.
Identity matrices
PyTorch · Function
Creates a two-dimensional tensor with ones on its diagonal and zeros elsewhere. It can produce square or rectangular shapes and accepts options for dtype, layout, device, output reuse, and gradient tracking.
torch.eye creates a two-dimensional tensor of shape (n, m) whose diagonal entries are 1 and all other entries are 0. Omitting m makes the tensor square; keyword options control storage, device, data type, and gradient tracking.
torch.eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)| Name | Type | Description |
|---|---|---|
n | int | Number of rows. |
m | int, optional | Optional number of columns; defaults to n. |
out | Tensor, optional | Optional destination tensor. |
dtype | torch.dtype, optional | Optional element type; defaults through the global default dtype when omitted. |
layout | torch.layout, optional | Optional tensor layout; defaults to torch.strided. |
device | torch.device, optional | Optional target device. |
requires_grad | bool, optional | Whether autograd records operations on the returned tensor; defaults to False. |
A 2-D Tensor containing ones on the diagonal and zeros elsewhere.
import torch
identity = torch.eye(3, dtype=torch.float32)
rectangular = torch.eye(2, 3, dtype=torch.float64)
print(identity)
print(rectangular)Creates square and rectangular two-dimensional tensors with ones on the main diagonal.
Identity matrices
Rectangular diagonal masks
Controlled tensor creation
torch.eye(n, m=None, ...) returns a 2-D tensor with ones on the diagonal and zeros elsewhere. With only n, it produces an n-by-n tensor; m changes the column count.
Follow-up: How would you create a rectangular 2-by-3 tensor? Call torch.eye(2, 3), optionally supplying dtype or device keywords.
The function accepts n as the row count and optional m as the column count. It also supports out, dtype, layout, device, and requires_grad keyword arguments.
Follow-up: How can the tensor be placed on an accelerator? Pass an appropriate device, such as device='cuda' when CUDA is available.
requires_grad defaults to False, so autograd does not record operations on the returned tensor unless requested. Set requires_grad=True when gradient tracking is needed.
Follow-up: What controls the element type if dtype is omitted? PyTorch uses the global default dtype.
torch.onestorch.zerostorch.emptytorch.fulltorch.nn.init.eye_