59.Numpy and Linear Algebra

The Linear Algebra module of NumPy offers various methods to apply linear algebra on any numpy array.
One can find:
  • rank, determinant, trace, etc. of an array.
  • eigen values of matrices
  • matrix and vector products (dot, inner, outer,etc. product), matrix exponentiation
  • solve linear or tensor equations and much more!
Multiplication of matrix using dot function (@ operator can also be used)
import numpy as np
x=np.array([[1,2,3],[4,5,6]])
y=np.array([2,4,1])
print(x.dot(y))
print(x@y)
print(np.dot(x,y))
[13 34]
[13 34]
[13 34]

import numpy as np
 
A = np.array([[6, 1, 1],
                      [4, -2, 5],
                      [2, 8, 7]])
 
Rank of a matrix
print("Rank of A:", np.linalg.matrix_rank(A))
Rank of A: 3
Diagonals of a matrix
print(np.diag(A))
[ 6 -2 7]
print(np.diag(A,k=1)) # above the main diagonal
[1 5]
print(np.diag(A,k=-1)) #below the main diagonal
[4 8]

import numpy as np
y=np.fliplr(A)
print(np.diag(y)) #secondary diagonal
[ 1 -2 2]
z=np.flipud(A)
print(np.diag(z))
[ 2 -2 1]

Trace of matrix A
print("\nTrace of A:", np.trace(A))
Trace of A: 11

Determinant of a matrix
print("\nDeterminant of A:", np.linalg.det(A))
Determinant of A: -306.0

Inverse of matrix A
print("\nInverse of A:\n", np.linalg.inv(A))
Inverse of A:
 [[ 0.17647059 -0.00326797 -0.02287582] 
[ 0.05882353 -0.13071895 0.08496732]
 [-0.11764706 0.1503268 0.05228758]]

Transpose of matrix A
print("\nTranspose of A:\n", A.T)
Transpose of A:
 [[ 6 4 2] 
[ 1 -2 8] 
[ 1 5 7]]

Power
print("\nMatrix A raised to power 3:\n",np.linalg.matrix_power(A, 3))
Matrix A raised to power 3:
 [[336 162 228]
 [406 162 469] 
 [698 702 905]]

Solving system of linear equations
let 2x1+3x2 +5x3= 10
3x1-2x2+x3=3
x1+5x2+7x3=8
the matrix representation is
Ax=b
where
A=[[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])

b=[10,3,8]
The following is the python code to solve the problem

import numpy as np
A=np.array([[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])
b=np.array([10,3,8])
x=np.linalg.solve(A,b)
print(x)
[ 5.69230769 5.30769231 -3.46153846]

Eigen values and eigen vector
Let A be a square matrix. A non-zero vector X is an eigenvector for A with eigenvalue e if
AX=eX
The eigenvalues of a symmetric matrix are always real and the eigenvectors are always orthogonal

import numpy as np
A=np.array([[ 2 , 3, 5],
[ 3, -2 ,1],
[ 1, 5 , 7 ]])
e,v=np.linalg.eig(A)
print(e)
[-2.81422161 0.49572305 9.31849856]
print(v)
[[ 0.09368857 -0.64029415 0.61137707] 
[-0.89093813 -0.55826909 0.2289721 ] 
[ 0.44435537 0.5275974 0.75748918]]
print(v[:,0]*e[0]) # eX
[-0.2636604 2.50729735 -1.25051449]
print(A.dot(v[:,0])) # AX
[-0.2636604 2.50729735 -1.25051449]
# Note that AX=eX

Lot of Matrix Decomposition functions are also available

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020