How to create an identity matrix using numpy in python ?

Daidalos October 17, 2019

Examples of how to create an identity matrix using numpy in python ?

Using the numpy function identity

Let's create the following identity matrix

I = \left( \begin{array}{ccc}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{array}\right)

using numpy function identity:

>>> import numpy as np
>>> I = np.identity(3)
>>> I
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])


Another example:

I = \left( \begin{array}{ccc}
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
\end{array}\right)

>>> I = np.identity(5)
>>> I
array([[ 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.]])


Using the numpy function diagonal

Another example using the numpy function diagonal

>>> import numpy as np
>>> A = np.zeros((3,3))
>>> A
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> np.fill_diagonal(A, 1)
>>> A
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])


Multiply the identity matrix by a constant

Example of how to multiply a identity matrix by a constant:

\lambda_{rr}. I = \left( \begin{array}{ccc}
4 & 0 & 0 \\
0 & 4 & 0 \\
0 & 0 & 4
\end{array}\right)

with $\lambda_{rr}=4$ (Ridge Regression)

>>> import numpy as np
>>> I = np.identity(3)
>>> I
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> lamda_rr = 4
>>> lamda_rr * I
array([[ 4.,  0.,  0.],
       [ 0.,  4.,  0.],
       [ 0.,  0.,  4.]])


Another example how to quickly calculate the operation $\lambda_{rr}. I - Y$:

>>> import numpy as np
>>> lamda_rr = 4
>>> Y = np.arange(9)
>>> Y = Y.reshape(3,3)
>>> Y
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fill_diagonal(Y, Y.diagonal() + lamda_rr)
>>> Y
array([[ 4,  1,  2],
       [ 3,  8,  5],
       [ 6,  7, 12]])


References

Identity matrix wikipedia
numpy.identity numpy doc
numpy.fill_diagonal docs.scipy
Comment ajouter un nombre sur la diagonale d'une matrice python ? science-emergence.com

Licence