How to use NumPy for Linear Algebra

Linear algebra comes into play in the data science and machine learning domain a lot. NumPy is the scientific computing library for Python, which provides several linear algebra functionalities. NumPy also provides the module required for linear algebra in the form of linalg.

Below, are some common linear algebra operations that use NumPy.

Matrix manipulation

import numpy as np
from numpy import linalg
A = np.array([[1, 2, 1],
[4, 9, 5],
[4, 8, 11]])
print("Rank of matrix A:", linalg.matrix_rank(A))
print("Determinant of matrix A:", linalg.det(A))
print("Inverse of A:", linalg.inv(A))

Eigenvalues of matrices

import numpy as np
from numpy import linalg
arr = np.array([[3, -4j], [5j, 6]])
print("Given Array:",arr)
e1, e2 = linalg.eigh(arr)
print("Eigen value is :", e1)
print("Eigen value is :", e2)

Solving equations

import numpy as np
# x + y = 6
# −3x + y = 2
arr1 = np.array([[1, 1], [-3, 1]])
arr2 = np.array([6, 2])
arr = np.linalg.solve(arr1, arr2)
print ('x =', arr[0])
print ('y =', arr[1])

Vector, array, and matrix products

import numpy as np
# dot product of two vectors
a = np.array([1+2j,3+4j])
b = np.array([5+6j,7+8j])
product = np.vdot(a, b)
print("Dot Product : ", product)
# inner product of arrays
a = np.array([1,2,3])
b = np.array([0,1,0])
product = np.inner(a, b)
print("Inner Product : ", product)
# matrix multiplication
a = np.array([[1, 0],
[0, 1]])
b = np.array([[4, 1],
[2, 2]])
product = np.matmul(a, b)
print("Product of Matrices : ", product)

Free Resources