NumPy: Difference between revisions

From David's Wiki
No edit summary
 
Line 16: Line 16:


===Batched Multiplication===
===Batched Multiplication===
If you need batched matrix multiplication, use [https://numpy.org/doc/stable/reference/generated/numpy.tensordot.html <code>np.tensordot</code>].
If you need batched matrix multiplication, use [https://numpy.org/doc/stable/reference/generated/numpy.tensordot.html <code>np.tensordot</code>] and transpose the result.

Latest revision as of 14:56, 6 February 2021

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

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.