IKH

chapter 18

Linear Algebra function from linalg module

numpy.linalg ==> contains functions to perform linear algebra operations.

  • inv() ==> to find inverse of a matrix.
  • matrix_power() ==> to find power of a matrix like A^n.
  • det ==> to find the determinant of a matrix.
  • solve() ==> to solve linear algebra equations.

inv() –> to find inverse of a matrix

Example

Python
import numpy as np
help(np.linalg.inv)

Output

PowerShell
Help on function inv in module numpy.linalg:

inv(a)
    Compute the (multiplicative) inverse of a matrix.

inverse of 2-D array(matrix)

figar banana

Example

Python
# To Find inverse of a matrix
a = np.array([[1,2],[3,4]])
ainv = np.linalg.inv(a)
print(f"Original Matrix :: \n {a}")
print(f"Inverse of the Matrix :: \n {ainv}")

Output

PowerShell
Original Matrix ::
 [[1 2]
 [3 4]]
Inverse of the Matrix ::
 [[-2.  1. ]
[ 1.5 -0.5]]

How to check the inverse of the matrix is correct or not

  • dot(a,ainv) = dot(ainv,a) = eye(a,shape[0]).

Example

Python
# To check the inverse of the matrix correct or not
a = np.array([[1,2],[3,4]])
ainv = np.linalg.inv(a)
dot_produt = np.dot(a,ainv)
i = np.eye(2) # Identity matrix for the shape 2 ==> 2-D Arrray
print(f"Original Matrix :: \n {a}")
print(f"Inverse of the Matrix :: \n {ainv}")
print(f"Dot product of Matrix and Inverse of Matrix :: \n {dot_produt}")
print(f"Identity Matrix(2-D array using eye() function):: \n {i}")

Output

PowerShell
Original Matrix ::
 [[1 2]
 [3 4]]
Inverse of the Matrix ::
 [[-2.  1. ]
 [ 1.5 -0.5]]
Dot product of Matrix and Inverse of Matrix ::
 [[1.00000000e+00 1.11022302e-16]
 [0.00000000e+00 1.00000000e+00]]
Identity Matrix(2-D array using eye() function)::
 [[1. 0.]
 [0. 1.]]

figar banana

np.allclose()

  • np.allclose() ==> method is used to check the matrices are equal at element level.

Note

  • The results of floating point arithmetic varies from platform to platform.

Example

Python
# help allclose() function
help(np.allclose)

Output

PowerShell
Help on function allclose in module numpy:

allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
    Returns True if two arrays are element-wise equal within a tolerance.

Example

Python
# demo for allclose() function
a = np.array([[1,2],[3,4]])
ainv = np.linalg.inv(a)
dot_produt = np.dot(a,ainv)
np.allclose(dot_produt,i)

Output

PowerShell
True

Note:

We can find inverse only for square matrices, otherwise we will get
error(LinAlgError)

Example

Python
a = np.arange(10).reshape(5,2)
np.linalg.inv(a)

Output

PowerShell
---------------------------------------------------------------------------
LinAlgError                            Traceback (most recent call last)
<ipython-input-430-bb2ecf710117> in <module>
      1 a = np.arange(10).reshape(5,2)
----> 2 np.linalg.inv(a)

<__array_function__ internals> in inv(*args, **kwargs)

F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in inv(a)
    538       a, wrap = _makearray(a)
    539      _assert_stacked_2d(a)
--> 540      _assert_stacked_square(a)
    541       t, result_t = _commonType(a)
    542
    
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in _assert_stacked_square(*arrays)
    201      m, n = a.shape[-2:]
    202      if m != n:
--> 203          raise LinAlgError('Last 2 dimensions of the array must besquare')
    204
    205 def _assert_finite(*arrays):
    
LinAlgError: Last 2 dimensions of the array must be square

inverse of 3-D array

  • 3-D array is the collection of 2-D arrays.
  • Finding inverse of 3-D array means finding the inverse of every 2-D array.

Example

Python
a = np.arange(8).reshape(2,2,2)
ainv = np.linalg.inv(a)
print(f"Original 3-D array :: \n {a}")
print(f"Inverse of 3-D array :: \n {ainv}")

Output

PowerShell
Original 3-D array ::
 [[[0 1]
 [2 3]]
 [[4 5]
 [6 7]]]
Inverse of 3-D array ::
 [[[-1.5 0.5]
 [ 1.   0. ]]
 [[-3.5 2.5]
 [ 3. -2. ]]]

matrix_power()

To find power of a matrix like A^n

matrix_power(a, n) ==> Raise a square matrix to the (integer) power n .

  • if n == 0 ==> Identity Matrix.
  • if n > 0 ==> Normal Power operation.
  • if n < 0 ==> First inverse and then power operation for absolute value of n abs(n).

Example

Python
import numpy as np
help(np.linalg.matrix_power)

Output

PowerShell
Help on function matrix_power in module numpy.linalg:

matrix_power(a, n)
    Raise a square matrix to the (integer) power `n`.
    
For positive integers `n`, the power is computed by repeated matrix squarings and matrix multiplications. If ``n == 0``, the identity matrix of the same shape as M is returned. If ``n < 0``, the inverse is computed and then raised to the ``abs(n)``.

Example

Python
# if n=0 ==> Identity Matrix
a = np.array([[1,2],[3,4]])
matrix_power = np.linalg.matrix_power(a,0)

Output

PowerShell
output nhi h

Example

Python
print(f"Original 2-D array(Matrix) :: \n {a}")
print(f"Matrix Power of 2-D array :: \n {matrix_power}")

Output

PowerShell
Original 2-D array(Matrix) ::
 [[1 2]
 [3 4]]
Matrix Power of 2-D array ::
 [[1 0]
 [0 1]]

Example

Python
# if n > 0 ==> Normal power operation
a = np.array([[1,2],[3,4]])
matrix_power = np.linalg.matrix_power(a,2)
print(f"Original 2-D array(Matrix) :: \n {a}")
print(f"Matrix Power of 2-D array :: \n {matrix_power}")

Output

PowerShell
Original 2-D array(Matrix) ::
 [[1 2]
 [3 4]]
Matrix Power of 2-D array ::
 [[ 7 10]
 [15 22]]

Example

Python
# if n < 0 ==> First inverse opeartion and then power operation
a = np.array([[1,2],[3,4]])
matrix_power = np.linalg.matrix_power(a,-2)
print(f"Original 2-D array(Matrix) :: \n {a}")
print(f"Matrix Power of 2-D array :: \n {matrix_power}")

Output

PowerShell
Original 2-D array(Matrix) ::
 [[1 2]
 [3 4]]
Matrix Power of 2-D array ::
 [[ 5.5 -2.5 ]
 [-3.75 1.75]]

Example

Python
# dot product of inverse matrix => dot(ainv) * dot(ainv) = result of n < 0 case
a = np.array([[1,2],[3,4]])

Output

PowerShell
output nhi h

Example

Python
ainv = np.linalg.inv(a)
dot_product = np.dot(ainv,ainv)
print(f"Original 2-D array(Matrix) :: \n {a}")
print(f"Inverse of Matrix :: \n {ainv}")
print(f"Dot product of Inverse of Matrix :: \n {dot_product}")

Output

PowerShell
Original 2-D array(Matrix) ::
 [[1 2]
 [3 4]]
Inverse of Matrix ::
 [[-2.  1. ]
 [ 1.5 -0.5]]
Dot product of Inverse of Matrix ::
 [[ 5.5 -2.5 ]
 [-3.75 1.75]]

Example

Python
# matrix power of inverse matrix and abs(n)
a = np.array([[1,2],[3,4]])
ainv = np.linalg.inv(a)
matrix_power = np.linalg.matrix_power(ainv,2)
print(f"Original 2-D array(Matrix) :: \n {a}")
print(f"Inverse of Matrix :: \n {ainv}")
print(f"Matrix power of Inverse of Matrix and abs(n) :: \n {matrix_power}")

Output

PowerShell
Original 2-D array(Matrix) ::
 [[1 2]
 [3 4]]
Inverse of Matrix ::
 [[-2.   1. ]
 [ 1.5 -0.5]]
Matrix power of Inverse of Matrix and abs(n) ::
 [[ 5.5 -2.5 ]
 [-3.75 1.75]]

figar banana

Note

We can find matrix_power only for square matrices, otherwise we will get
error(LinAlgError).

Example

Python
a = np.arange(10).reshape(5,2)
np.linalg.matrix_power(a,2)

Output

PowerShell
---------------------------------------------------------------------------
LinAlgError                            Traceback (most recent call last)
<ipython-input-438-99f952561699> in <module>
      1 a = np.arange(10).reshape(5,2)
----> 2 np.linalg.matrix_power(a,2)

<__array_function__ internals> in matrix_power(*args, **kwargs)

F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in matrix_power(a, n)
    618a       = asanyarray(a)
    619        _assert_stacked_2d(a)
--> 620        _assert_stacked_square(a)
    621
    622        try:
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in _assert_stacked_square(*arrays)
    201m      , n = a.shape[-2:]
    202         if m != n:
--> 203         raise LinAlgError('Last 2 dimensions of the array must be square')
    204
    205def _assert_finite(*arrays):
    
LinAlgError: Last 2 dimensions of the array must be square

det()

To find the determinant of a matrix.

  • determinant of the matrix = ad-bc.
Python
import numpy as np
help(np.linalg.det)

Output

PowerShell
Help on function det in module numpy.linalg:

det(a)
    Compute the determinant of an array.

figar banana

determinant of 2-D arrays

Python
a = np.array([[1,2],[3,4]])
adet = np.linalg.det(a)
print(f"Original Matrix : \n {a}")
print(f"Determinant of Matrix : \n {adet}")

Output

PowerShell
Original Matrix :
 [[1 2]
 [3 4]]
Determinant of Matrix :
 -2.0000000000000004

determinant of 3-D arrays

Example

Python
a = np.arange(9).reshape(3,3)
adet = np.linalg.det(a)
print(f"Original Matrix : \n {a}")
print(f"Determinant of Matrix : \n {adet}")

Output

PowerShell
Original Matrix :
 [[0 1 2]
 [3 4 5]
 [6 7 8]]
Determinant of Matrix :
 0.0

Note

We can find determinant only for square matrices, otherwise we will get
error(LinAlgError).

Python
a = np.arange(10).reshape(5,2)
np.linalg.det(a)

Output

PowerShell
---------------------------------------------------------------------------
LinAlgError                            Traceback (most recent call last)
<ipython-input-442-52a5a7a95a82> in <module>
      1 a = np.arange(10).reshape(5,2)
----> 2 np.linalg.det(a)

<__array_function__ internals> in det(*args, **kwargs)

F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in det(a)
   2153      a = asarray(a)
   2154      _assert_stacked_2d(a)
-> 2155      _assert_stacked_square(a)
   2156       t, result_t = _commonType(a)
   2157       signature = 'D->D' if isComplexType(t) else 'd->d'
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\linalg\linalg.py in _assert_stacked_square(*arrays)
    201m, n = a.shape[-2:]
    202if m != n:
--> 203
raise LinAlgError('Last 2 dimensions of the array must be
square')
    204
    205 def _assert_finite(*arrays):
    
LinAlgError: Last 2 dimensions of the array must be square

solve()

To solve linear algebra equations.

solve(a, b) ==> Solve a linear matrix equation, or system of linear scalar equations.

  • a : (…, M, M) array_like ==> Coefficient matrix.
  • b : {(…, M,), (…, M, K)}, array_like ==> Ordinate or “dependent variable” values.

2 variables

case study:
Problem:
  • Boys and Girls are attending Durga sir’s datascience class.
  • For boys fee is $3 and for girls fee is $8 .
  • For a certain batch 2200 people attented and $10100 fee collected.
  • How many boys and girls attended for that batch?

Figar banana

Python
# solution
# x+y = 2200
# 3x+8y=10100

coef = np.array([[1,1],[3,8]])
dep = np.array([2200,10100])
result = np.linalg.solve(coef,dep)
print(f"Coefficient Matrix : \n {coef}")
print(f"Dependent Matrix : \n {dep}")
print(f"Solution array : {result}")
print(f"Type of result : {type(result)}")

Output

PowerShell
Coefficient Matrix :
 [[1 1]
 [3 8]]
Dependent Matrix :
 [ 2200 10100]
Solution array : [1500. 700.]
Type of result : <class 'numpy.ndarray'>

3 variables

figar banana

Example

Python
# Finding the values of the 3 variables

# -4x+7y-2z = 2
# x-2y+z = 3
# 2x-3y+z = -4

coef = np.array([[-4,7,-2],[1,-2,1],[2,-3,1]])
dep = np.array([2,3,-4])
result = np.linalg.solve(coef,dep)
print(f"Coefficient Matrix : \n {coef}")
print(f"Dependent Matrix : \n {dep}")
print(f"Solution array : {result}")

Output

PowerShell
Coefficient Matrix :
 [[-4 7 -2]
 [ 1 -2 1]
 [ 2 -3 1]]
Dependent Matrix :
 [ 2 3 -4]
Solution array : [-13. -6. 4.]