Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.eye function

PyTorch torch.eye function


PyTorch torch reference manual 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:

Return Value:


Usage examples

Example 1: Create a square matrix

Example

import

torch

Create a 3x3 identity matrix

I

=

torch.

eye

(

3

)

print

(

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

)

print

(

I

)

The output is:

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

        [0., 1., 0., 0.],

        [0., 0., 1., 0.]])


PyTorch torch reference manual PyTorch torch reference manual