What are the advantages of using numpy.identity over numpy.eye?

identity just calls eye so there is no difference in how the arrays are constructed. Here's the code for identity:

def identity(n, dtype=None):
    from numpy import eye
    return eye(n, dtype=dtype)

As you say, the main difference is that with eye the diagonal can may be offset, whereas identity only fills the main diagonal.

Since the identity matrix is such a common construct in mathematics, it seems the main advantage of using identity is for its name alone.


To see the difference in an example, run the below codes:

import numpy as np

#Creates an array of 4 x 4 with the main diagonal of 1

arr1 = np.eye(4)
print(arr1)

print("\n")

#or you can change the diagonal position

arr2 = np.eye(4, k=1)  # or try with another number like k= -2
print(arr2)

print("\n")

#but you can't change the diagonal in identity

arr3 = np.identity(4)
print(arr3)

np. identity - returns a SQUARE MATRIX(special case of a 2D-array) which is an identity matrix with the main diagonal(i.e. 'k=0') as 1's and the other values as 0's. you can't change the diagonal k here.

np. eye - returns a 2D-ARRAY, which fills the diagonal, i.e. 'k' which can be set, with 1's and rest with 0's.

so, the main advantage depends on the requirement. If you want an identity matrix, you can go for identity right away, or can call the np. eye leaving the rest to defaults.

But, if you need a 1's and 0's matrix of a particular shape/size or have a control over the diagonal you can go for eye method

Just like how a matrix is a special case of an array, np.identity matrix is also special case of np.eye

references: https://numpy.org/doc/stable/reference/generated/numpy.identity.html [2]: http://ttps://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.eye.html [3]: https://www.hackerrank.com/challenges/np-eye-and-identity/problem