Environment Setup
To begin working with numerical arrays in Python, the NumPy library is essential. It can be installed using the following command:
pip install numpy
Users encountering installation issues may need to upgrade their package management tool first:
python -m pip install --upgrade pip
Working with Vectors
NumPy provides the ndarray object, which supports efficient operations on large datasets. Import the library using the standard alias to enable access to its methods.
import numpy as np
# Initializing a one-dimensional array (vector)
data_vector = np.array([1.5, 2.5, 3.5])
print(f"Array content: {data_vector}")
print(f"Data type: {type(data_vector)}")
# Vector arithmetic operations
offset_vector = np.array([0.5, 1.5, 2.5])
print("Addition:", data_vector + offset_vector)
print("Subtraction:", data_vector - offset_vector)
print("Multiplication:", data_vector * offset_vector)
print("Division:", data_vector / offset_vector)
# Scalar operations (Broadcasting)
print("Scalar division:", data_vector / 5.0)
Matrix Operations
Two-dimensional arrays, or matrices, allow for the representation of grid-like data. The shape and data type attributes provide metadata about the structure.
# Creating a 2x2 matrix
matrix_a = np.array([[10, 20], [30, 40]])
print("Matrix A:\n", matrix_a)
print("Shape:", matrix_a.shape)
print("Type:", matrix_a.dtype)
# Broadcasting with a scalar
print("Scalar multiplication:\n", matrix_a * 2)
# Broadcasting with a vector
vector_b = np.array([1, 2])
print("Row-wise multiplication:\n", matrix_a * vector_b)
Tensors and Dimensions
In the context of deep learning, the dimensionality of data structures is often categorized as follows:
- Vector: A one-dimensional array (1D).
- Matrix: A two-dimensional array (2D).
- Tensor: A generalization of vectors and matrices to N dimensions, where N is 3 or higher.
Broadcasting Mechanics
Broadcasting allows arithmetic operations between arrays of different shapes. NumPy handles this automatically based on specific rules:
- Arrays with a smaller number of dimensions are padded with leading ones to match the dimensionality of the larger array.
- Arrays with size 1 in any dimension are virtually replicated along that dimension to match the shape of the other array.
- If dimensions are mismatched and neither is 1, the operation is invalid and raises an error.
Element Access and Slicing
Accessing specific data points within an array is done using zero-based indexing. For multi-dimensional arrays, indices are separated by commas or chained brackets.
# Sample data grid
data_grid = np.array([[51, 55], [14, 19], [0, 4]])
print("Original Grid:\n", data_grid)
print("First row:", data_grid[0])
print("Element at (0,1):", data_grid[0, 1])
Advanced Indexing
NumPy supports sophisticated retrieval methods, such as using arrays of indices or boolean masks.
# Flatten to 1D for easier selection
flat_data = data_grid.flatten()
print("Flattened array:", flat_data)
# Select specific indices
indices = np.array([0, 2, 4])
print("Elements at indices [0, 2, 4]:", flat_data[indices])
# Boolean filtering (condition-based access)
threshold = 15
filtered_result = flat_data[flat_data > threshold]
print(f"Elements greater than {threshold}:", filtered_result)