How to create an identity matrix using numpy in python ?

Published: October 17, 2019

DMCA.com Protection Status

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

Using the numpy function identity

Let's create the following identity matrix

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

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:

\begin{equation}
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)
\end{equation}

>>> 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:

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

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