You are currently viewing Basic linear algebra with NumPy

Basic linear algebra with NumPy

NumPy provides a powerful set of linear algebra functions that can be used for a variety of data analysis tasks.

Here are some basic linear algebra operations that can be performed with NumPy:

  1. Dot product: The dot product of two vectors or matrices can be calculated using the dot() function.
import numpy as np

# Create two vectors
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Calculate the dot product of the two vectors
c = np.dot(a, b)
print(c)

# Create two matrices
d = np.array([[1, 2], [3, 4]])
e = np.array([[5, 6], [7, 8]])

# Calculate the dot product of the two matrices
f = np.dot(d, e)
print(f)

2. Matrix inverse: The inverse of a matrix can be calculated using the inv() function.

import numpy as np

# Create a matrix
a = np.array([[1, 2], [3, 4]])

# Calculate the inverse of the matrix
b = np.linalg.inv(a)
print(b)

3. Eigenvalues and eigenvectors: The eigenvalues and eigenvectors of a matrix can be calculated using the eig() function.

import numpy as np

# Create a matrix
a = np.array([[1, 2], [3, 4]])

# Calculate the eigenvalues and eigenvectors of the matrix
eigenvalues, eigenvectors = np.linalg.eig(a)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:", eigenvectors)

4. Singular value decomposition: The singular value decomposition (SVD) of a matrix can be calculated using the svd() function.

import numpy as np

# Create a matrix
a = np.array([[1, 2], [3, 4]])

# Calculate the SVD of the matrix
u, s, vh = np.linalg.svd(a)
print("U:", u)
print("S:", s)
print("Vh:", vh)

These are just a few basic linear algebra operations that can be performed with NumPy. NumPy’s linear algebra functions are powerful and flexible, and can be used in a variety of data analysis tasks, such as machine learning, image processing, and scientific computing.