NumPy (Numerical Python)
NumPy is the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
Key Concepts
- ndarray: The core data structure, an N-dimensional array.
- Vectorization: Performing operations on entire arrays without explicit loops.
- Broadcasting: A mechanism that allows NumPy to work with arrays of different shapes when performing arithmetic operations.
Basic Usage
import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Create a 2D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Array operations
squared = arr ** 2
sum_arr = np.sum(arr)
# Matrix multiplication
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
c = np.dot(a, b) # or a @ b
Why it is essential for AI
Almost all other data science and AI libraries ([Pandas](../Ch-6 Data-Manipulation/Pandas.mdx), [Scikit-Learn](../Ch-7 Classical-Machine-Learning/Scikit-Learn.mdx), [PyTorch](../Ch-9 Deep-Learning-Frameworks/PyTorch.mdx), TensorFlow) use NumPy arrays under the hood or interoperate closely with them.