NumPy is a Python library that adds support for matrices and matrix operations. It’s comparable in some ways to operations supported in MATLAB.
We import with import numpy as np
.
Arrays
The main feature of NumPy are arrays and matrices, which expand the functionality of standard lists in Python. We wrap rows in square brackets and separate rows with commas.
x = np.array([[1, 2], [3, 4]])
NumPy arrays have several attributes.
x.shape
gives the dimensions of the array.x.where(cond)
allows us to conditionally find indices of data that meet a certain condition.- We can also access the data themselves with a conditional inside the index.
Interfaces with other packages
- To convert to a PyTorch tensor, use
torch.from_numpy(arr)
.