0
0
NumPydata~5 mins

np.eye() for identity matrices in NumPy

Choose your learning style9 modes available
Introduction

We use np.eye() to create identity matrices easily. Identity matrices have 1s on the diagonal and 0s elsewhere, which are useful in math and data science.

When you need a matrix that does not change other matrices when multiplied.
When initializing weights or parameters in machine learning models.
When you want to create a simple square matrix with 1s on the diagonal for testing.
When performing linear algebra operations that require identity matrices.
Syntax
NumPy
np.eye(N, M=None, k=0, dtype=float, order='C')

N is the number of rows (and columns if M is not given).

M is the number of columns (optional, defaults to N).

Examples
Creates a 3x3 identity matrix with 1s on the main diagonal.
NumPy
np.eye(3)
Creates a 3x4 matrix with 1s on the main diagonal and 0s elsewhere.
NumPy
np.eye(3, 4)
Creates a 4x4 matrix with 1s on the diagonal just above the main diagonal.
NumPy
np.eye(4, k=1)
Sample Program

This program shows three examples of np.eye():

  • A 4x4 identity matrix.
  • A 3x5 matrix with 1s on the main diagonal.
  • A 5x5 matrix with 1s just below the main diagonal.
NumPy
import numpy as np

# Create a 4x4 identity matrix
identity_matrix = np.eye(4)
print(identity_matrix)

# Create a 3x5 matrix with 1s on the main diagonal
rect_matrix = np.eye(3, 5)
print(rect_matrix)

# Create a 5x5 matrix with 1s on the diagonal below the main diagonal
offset_matrix = np.eye(5, k=-1)
print(offset_matrix)
OutputSuccess
Important Notes

The k parameter shifts the diagonal: k=0 is the main diagonal, positive k moves above, negative k moves below.

You can specify the data type with dtype, for example dtype=int to get integers.

Summary

np.eye() creates identity or diagonal matrices with 1s on a chosen diagonal.

It is useful for math, machine learning, and testing.

You can control size, shape, and which diagonal has the 1s.