Pytorch Torch Eye
# PyTorch torch.eye Function
* * PyTorch torch Reference Manual](#)
`torch.eye` is a PyTorch function used to create an identity matrix (a matrix with 1s on the diagonal and 0s elsewhere).
This is commonly used in deep learning for initialization, creating masks, and similar scenarios.
### Function Definition
torch.eye(n, m, dtype, device, requires_grad)
**Parameters**:
* `n` (int): Number of rows.
* `m` (int, optional): Number of columns. If not specified, creates an nΓn square matrix.
* `dtype` (torch.dtype, optional): Data type.
* `device` (torch.device, optional): Device.
* `requires_grad` (bool, optional): Whether gradient calculation is required.
**Returns**:
* `torch.Tensor`: Returns the identity matrix.
* * *
## Usage Examples
### Example 1: Create Square Matrix
## Instance
import torch
# Create 3x3 identity matrix
I = torch.eye(3)
print(I)
Output result:
tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
### Example 2: Create Non-square Matrix
## Instance
import torch
# Create 3x4 identity matrix
I = torch.eye(3,4)
print(I)
Output result:
tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]])
* * PyTorch torch Reference Manual](#)
YouTip