PyTorch torch.eye function
PyTorch torch reference manual
torch.eye is a PyTorch function for creating 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, an n x n square matrix is created.dtype(torch.dtype, optional): Data type.device(torch.device, optional): Device.requires_grad(bool, optional): Whether gradients need to be computed.
Return Value:
torch.Tensor: Returns the identity matrix.
Usage examples
Example 1: Create a square matrix
Example
import
torch
Create a 3x3 identity matrix
I
=
torch.
eye
(
3
)
(
I
)
The output is:
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
Example 2: Create a non-square matrix
Example
import
torch
Create a 3x4 identity matrix
I
=
torch.
eye
(
3
,
4
)
(
I
)
The output is:
tensor([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.]])