NumPy
NumPy is a python library for working with arrays.
Memory Usage
To optimize memory usage, try to use views instead of actual arrays where possible.
Indexing into an array will return a view. See numpy indexing for details.
Fancy indexing, using a list of indices, will not return a view.
The following functions also return views
- np.broadcast_to
- np.reshape - usually returns a view
- ndarray.view
Most function calls will return a new array. E.g. a+b
will return a new array with the broadcasted size which requires memory allocation.
To output to an existing array c
, you can use np.add(a, b, out=c)
.
If you need to perform an operation over multiple arrays, you can use np.ufunc.reduce. E.g. np.logical_and.reduce((a, b, c))
.
Batched Multiplication
If you need batched matrix multiplication, use np.tensordot
and transpose the result.