.eye()
Published Dec 16, 2024
Contribute to Docs
The .eye()
function in PyTorch is used to create a 2D tensor representing an identity matrix. An identity matrix is a square matrix in which all elements of the principal diagonal are ones, and all other elements are zeros.
This function is commonly used in linear algebra operations and initializing neural network weights.
Syntax
torch.eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
n
: Specifies the number of rows in the resulting 2-D tensor.m
(Optional): Specifies the number of columns in the resulting tensor. Defaults toNone
, in which case the result is a square matrix withm = n
.out
(Optional): A tensor to store the output. If specified, the result is written into this tensor. Defaults toNone
.dtype
(Optional): Specifies the desired data type of the resulting tensor. Defaults to the global PyTorch settings if not provided.layout
(Optional): Defines the desired memory layout of the tensor. Defaults totorch.strided
.device
(Optional): The desired device on which to create the tensor. If not specified, the tensor will be created on the current device.requires_grad
(Optional): IfTrue
, the resulting tensor will be created with gradient computation enabled. Defaults toFalse
.
Example
Here is an example that demonstrates the use of .eye()
to create a 3x3 identity matrix:
import torch# Create a 3x3 identity matrixidentity_matrix = torch.eye(3)print(identity_matrix)
The output of the above code will be as follows:
tensor([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]])
Codebyte Example
Here is an example that demonstrates the use of .eye()
to create a 4x4 identity matrix:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours