What does numpy.eye() do in Python?

The numpy.eye() function in NumPy is used to create an identity matrix. An identity matrix is a special kind of square matrix where all the elements on the main diagonal are ones, and all other elements are zeros. This kind of matrix plays a crucial role in linear algebra, particularly in matrix operations such as matrix inversion and solving linear equations.

Example of Creating an Identity Matrix using numpy.eye()

Here’s a basic example of how to use numpy.eye() to create a 5×5 identity matrix:

import numpy as np

# Create a 5x5 identity matrix
arr = np.eye(5)

print(arr)

When this code is executed, it produces the following output:

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

In this output, you can clearly see the structure of the identity matrix: ones on the diagonal from the top left to the bottom right, and zeros in all other positions.

Additional Parameters

The numpy.eye() function also allows for additional customization:

  1. N: The number of rows in the output matrix.
  2. M (optional): The number of columns in the output matrix. If not specified, it defaults to N, making the matrix square.
  3. k (optional): Index of the diagonal. The default is 0. A positive value refers to an upper diagonal, and a negative value to a lower diagonal.

Example with Non-Default Parameters in numpy.eye()

Here’s an example demonstrating the use of these additional parameters:

import numpy as np

# Create a 4x5 matrix with the diagonal 
# shifted one column to the right
arr = np.eye(4, 5, k=1)

print(arr)

Output:

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

In this example, the matrix is not square (4×5) and the main diagonal is shifted one step to the right (k=1).

Summary

Identity matrices are often used in linear algebra to represent the equivalent of the number 1 for matrix operations. They are crucial in algorithms for matrix inversion and solving systems of linear equations. Additionally, identity matrices are used in the field of machine learning, particularly in regularization techniques.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top