ssymjax
Release 0.0.1
Randall Balestriero
May 21, 2020 a r X i v : . [ c s . M S ] M a y ONTENTS iiymjax, Release 0.0.1 • JAX = XLA + Autograd• SymJAX = JAX + symbolic programming + deep LearningXLA is a compiler that optimizes a computational graph by fusing multiple kernels into one preventing intermediatecomputation, reducing memory operations and increasing performances.JAX is a python interface that provides a Numpy-like software on top of XLA and providing just-in-time compilationa well as advanced automatic differenciation.SymJAX is a symbolic programming version of JAX simplifying graph input, output and updates and providing addi-tional functionalities for general machine learning and deep learning applications. From an user perspective SymJAXapparents to Theano with fast graph optimization/compilation and broad hardware support, along with Lasagne-likedeep learning functionalitiesThis is an under development research project, not an official product, expect bugs and sharp edges; please help bytrying it out, reporting bugs.
CONTENTS 1ymjax, Release 0.0.12 CONTENTSHAPTER
ONECONTENTS1.1 Installation
This installation is restricted to GPU support only.
1. Install all GPU divers and compilers ( cuda , cudnn , and GPU drivers).2. Install jax following Jax Installation. Here is a minimal instruction to install the GPU version $ PYTHON_VERSION=cp37 $ CUDA_VERSION=cuda92 $ PLATFORM=linux_x86_64 $ BASE_URL='https://storage.googleapis.com/jax-releases'$ pip install --upgrade $BASE_URL/$CUDA_VERSION jaxlib-0.1.38-$PYTHON_ ˓ → VERSION-none-$PLATFORM.whl
3. Install SymJAX with $ pip install symjax
1. Clone this repository with $ git clone https://github.com/RandallBalestriero/SymJAX
2. Install. $ cd SymJAX$ pip install -r requirements.txt$ pip install . import sys sys.path.insert(0, "../") import symjax as sjimport symjax.tensor as Timport matplotlib.pyplot as pltimport matplotlib matplotlib.use('Agg') t = T.linspace(-5, 5, 5)x, y = T.meshgrid(t, t)X = T.stack([x.flatten(), y.flatten()], 1)p = T.pdfs.multivariate_normal.pdf(X, T.zeros(2), T.eye(2))p = p.reshape((5, 5)).round(2)print(p) print(p.get()) f = sj.function(outputs=p)print(f()) import sys sys.path.insert(0, "../") import symjaximport symjax.tensor as T mu = T.Variable(T.random.normal((), seed=1)) (continues on next page) (continued from previous page) cost = T.exp(-(mu-1)**2) g = symjax.gradients(cost, mu)print(g) f = symjax.function(outputs=cost, updates={mu:mu-0.2*g}) for i in range(10):print(f()) import sys sys.path.insert(0, "../") import symjax.tensor as Timport symjax as sjimport numpy as np images_train, labels_train, images_test, labels_test = sj.datasets.cifar10.load() images_train /= images_train.max((1, 2, 3), keepdims= True )images_test /= images_test.max((1, 2, 3), keepdims=
True ) BATCH_SIZE = 32inputs = T.Placeholder((BATCH_SIZE,) + images_train.shape[1:], 'float32')outputs = T.Placeholder((BATCH_SIZE,), 'int32')deterministic = T.Placeholder((1,), 'bool')layer = [sj.layers.RandomCrop(inputs, crop_shape=(3, 32, 32),padding=[(0, 0), (4, 4), (4, 4)],deterministic=deterministic)]layer.append(sj.layers.Conv2D(layer[-1], (32, 3, 3, 3))) (continues on next page) (continued from previous page) layer.append(sj.layers.BatchNormalization(layer[-1], [0, 2, 3],deterministic))layer.append(sj.layers.Activation(layer[-1], T.relu))layer.append(sj.layers.Pool2D(layer[-1], (2, 2)))layer.append(sj.layers.Conv2D(layer[-1], (64, 32, 3, 3)))layer.append(sj.layers.BatchNormalization(layer[-1], [0, 2, 3],deterministic))layer.append(sj.layers.Activation(layer[-1], T.relu))layer.append(sj.layers.Pool2D(layer[-1], (2, 2)))layer.append(sj.layers.Dense(layer[-1], 128))layer.append(sj.layers.BatchNormalization(layer[-1], [0],deterministic))layer.append(sj.layers.Activation(layer[-1], T.relu))layer.append(sj.layers.Dense(layer[-1], 10)) for l in layer:print(l.shape) loss = sj.losses.sparse_crossentropy_logits(outputs, layer[-1]).mean()accuracy = sj.losses.accuracy(outputs, layer[-1])params = sum([lay.variables() for lay in layer], [])lr=sj.schedules.PiecewiseConstant(0.005, {50: 0.001, 75: 0.0005})opt = sj.optimizers.Adam(loss, params, lr) for l in layer:opt.updates.update(l.updates)test = sj.function(inputs, outputs, deterministic,outputs=[loss, accuracy])train = sj.function(inputs, outputs, deterministic,outputs=[loss, accuracy], updates=opt.updates) for epoch in range(100):L = list() for x, y in sj.utils.batchify(images_test, labels_test, batch_size=BATCH_SIZE, (continues on next page) (continued from previous page) option='continuous'):L.append(test(x, y, 1))print('Test Loss and Accu:', np.mean(L, 0))L = list() for x, y in sj.utils.batchify(images_train, labels_train,batch_size=BATCH_SIZE, option='random_see_all'):L.append(train(x, y, 0))print('Train Loss and Accu', np.mean(L, 0))lr.update() TWOAPI2.1 General symjax class function ( *classargs , outputs=[] , updates=None , device=None , backend=None , de-fault_value=None ) Generate a user function that compiles a computational graph.Based on given inputs, outputs and update policy of variables. This function internally jit compile the underlyingjax computational graph for performances and thus should be favored to the get method of tensors.
Parameters • classargs ( trailing tuple ) – the inputs to the function to be compiled. The tupleshould contain all the placeholders that are roots of any output given of the function andupdate values• outputs ( List (optional) ) – the outputs of the function, if a single element, it canbe given as a standalone and not a list• updates ( Dict (optional) ) – the dictionnary of updates as per {var:new_value} forany variable of the graph• device – ??• backend ( 'cpu' or 'gpu' ) – the backend to use to run the function on• default_value ( not implemented ) – not implemented Returns the user frontend function that takes the specified inputs, returns the specified outputs andperform internally the updates
Return type callable
Examples >>> import jaxonn>>> import jaxonn.tensor as T>>> x = T.ones((4, 4)) >>> xs = x.sum() + 1 >>> f = jaxonn.function(outputs=xs) >>> print(f()) >>> w = T.Variable(0., name='w') >>> increment = jaxonn.function(updates={w: w + 1}) >>> for i in range(10): >>> increment() >>> print(w.value) gradients ( scalar , variables ) Compute the gradients of a scalar w.r.t to a given list of variables.
Parameters • scalar ( symjax.tensor.base.Tensor ) – the variable to differentiate• variables ( List or Tuple ) – the variables used to compute the derivative.
Returns gradients – the sequency of gradients ordered as given in the input variables
Return type
Tuple jacobians ( tensor , variables , mode='forward' ) Compute the jacobians of a tensor w.r.t to a given list of variables.The tensor needs not to be a vector, but will be treated as such. For example if tensor.shape is (10, 3, 3) and avariable shape if (10, 10) the resulting jacobian has shape (10, 3, 3, 10, 10). It is possible to specify the modeforward or backward. For tall jacobians, forward is faster and vice-versa.
Parameters • vector ( Tensor ) – the variable to differentiate• variables ( List or Tuple ) – the variables used to compute the derivative.
Returns jacobians – the sequency of gradients ordered as given in the input variables
Return type
Tuple symjax.tensor
Implements the NumPy API, using the primitives in jax.lax . As SymJAX follows the JAX restrictions, not allNumPy functins are present.• Notably, since JAX arrays are immutable, NumPy APIs that mutate arrays in-place cannot be implemented inJAX. However, often JAX is able to provide a alternative API that is purely functional. For example, insteadof in-place array updates ( x[i] = y ), JAX provides an alternative pure indexed update function jax.ops.index_update() .• NumPy is very aggressive at promoting values to float64 type. JAX sometimes is less aggressive about typepromotion.Finally, since SymJAX uses jit-compilation, any function that returns data-dependent output shapes are incompatibleand thus not implemented. In fact, The XLA compiler requires that shapes of arrays be known at compile time. Whileit would be possible to provide. Thus an implementation of an API such as numpy.nonzero() , we would be unableto JIT-compile it because the shape of its output depends on the contents of the input data.Not every function in NumPy is implemented; contributions are welcome!
10 Chapter 2. APIymjax, Release 0.0.1Control Flow cond ( predicate , true_predicate , true_fun , false_predicate , false_fun ) predicate should be a boolean tensor with shape () true_input is the input passed to true_fn that will give theoutput if the predicate evaluates to True, and conversely for False. . .LAX-backend implementation of _cond() . ADDITIONOriginal docstring below. scan ( fn , init , xs , constants=() , length=None ) Scan a function over leading array axes while carrying along state.The type signature in brief is scan :: (c -> a -> (c, b)) -> c -> [a] -> (c, [b]) where we use [t] here to denote the type t with an additional leading axis. That is, if t is an array type then [t]represents the type with an additional leading axis, and if t is a pytree (container) type with array leaves then[t] represents the type with the same pytree structure and corresponding leaves each with an additional leadingaxis.When a is an array type or None, and b is an array type, the semantics of scan are given roughly by this Pythonimplementation: def scan(f, init, xs, length= None ): if xs is None :xs = [ None ] * lengthcarry = initys = [] for x in xs:carry, y = f(carry, x)ys.append(y) return carry, np.stack(ys) Unlike that Python version, both a and b may be arbitrary pytree types, and so multiple arrays can be scannedover at once and produce multiple output arrays. (None is actually an empty pytree.)Also unlike that Python version, scan is a JAX primitive and is lowered to a single XLA While HLO. Thatmakes it useful for reducing compilation times for jit-compiled functions, since native Python loop constructsin an @jit function are unrolled, leading to large XLA computations.Finally, the loop-carried value carry must hold a fixed shape and dtype across all iterations (and not just beconsistent up to NumPy rank/shape broadcasting and dtype promotion rules, for example). In other words, thetype c in the type signature above represents an array with a fixed shape and dtype (or a nested tuple/list/dictcontainer data structure with a fixed structure and arrays with fixed shape and dtype at the leaves). Parameters • f – a Python function to be scanned of type c -> a -> (c, b) , meaning that f acceptstwo arguments where the first is a value of the loop carry and the second is a slice of xs along its leading axis, and that f returns a pair where the first element represents a newvalue for the loop carry and the second represents a slice of the output.• init – an initial loop carry value of type c , which can be a scalar, array, or any pytree(nested Python tuple/list/dict) thereof, representing the initial loop carry value. This valuemust have the same structure as the first element of the pair returned by f .• xs – the value of type [a] over which to scan along the leading axis, where [a] can be anarray or any pytree (nested Python tuple/list/dict) thereof with consistent leading axis sizes. • length – optional integer specifying the number of loop iterations, which must agree withthe sizes of leading axes of the arrays in xs (but can be used to perform scans where noinput xs are needed). Returns
A pair of type (c, [b]) where the first element represents the final loop carry value andthe second element represents the stacked outputs of the second output of f when scanned overthe leading axis of the inputs. Index Operations index_update ( x , idx , y ) Pure equivalent of x[idx] = y .LAX-backend implementation of index_update() . ADDITIONOriginal docstring below.Returns the value of x that would result from the NumPy-style indexed assignment :: x[idx] = yNote the index_update operator is pure; x itself is not modified, instead the new value that x wouldhave taken is returned.Unlike NumPy’s x[idx] = y , if multiple indices refer to the same location it is undefined whichupdate is chosen; JAX may choose the order of updates arbitrarily and nondeterministically (e.g., dueto concurrent updates on some hardware platforms). Args: x: an array with the values to be updated. idx: a Numpy-style index, consisting of
None ,integers, slice objects,ellipses, ndarrays with integer dtypes, or a tuple of the above. A convenient syntacticsugar for forming indices is via the jax.ops.index object. y: the array of updates. y must be broadcastable to the shape of the array that would be re-turned by x[idx] . Returns:
An array. >>> x = jax.numpy.ones((5, 6)) >>> jax.ops.index_update(x, jax.ops.index[::2, 3:], 6.)array([[1., 1., 1., 6., 6., 6.],[1., 1., 1., 1., 1., 1.],[1., 1., 1., 6., 6., 6.],[1., 1., 1., 1., 1., 1.],[1., 1., 1., 6., 6., 6.]], dtype=float32) index_add ( x , idx , y ) Pure equivalent of x[idx] += y .LAX-backend implementation of index_add() . ADDITIONOriginal docstring below.Returns the value of x that would result from the NumPy-style indexed assignment :: x[idx] += yNote the index_add operator is pure; x itself is not modified, instead the new value that x would havetaken is returned.Unlike the NumPy code x[idx] += y , if multiple indices refer to the same location the updateswill be summed. (NumPy would only apply the last update, rather than summing the updates.) The
12 Chapter 2. APIymjax, Release 0.0.1 order in which conflicting updates are applied is implementation-defined and may be nondeterminis-tic (e.g., due to concurrency on some hardware platforms).
Args: x: an array with the values to be updated. idx: a Numpy-style index, consisting of
None ,integers, slice objects,ellipses, ndarrays with integer dtypes, or a tuple of the above. A convenient syntacticsugar for forming indices is via the jax.ops.index object. y: the array of updates. y must be broadcastable to the shape of the array that would be re-turned by x[idx] . Returns:
An array. >>> x = jax.numpy.ones((5, 6)) >>> jax.ops.index_add(x, jax.ops.index[2:4, 3:], 6.)array([[1., 1., 1., 1., 1., 1.],[1., 1., 1., 1., 1., 1.],[1., 1., 1., 7., 7., 7.],[1., 1., 1., 7., 7., 7.],[1., 1., 1., 1., 1., 1.]], dtype=float32) index_max ( x , idx , y ) Pure equivalent of x[idx] = maximum(x[idx], y) .LAX-backend implementation of index_max() . ADDITIONOriginal docstring below.Returns the value of x that would result from the NumPy-style indexed assignment :: x[idx] = maximum(x[idx], y)Note the index_max operator is pure; x itself is not modified, instead the new value that x would havetaken is returned.Unlike the NumPy code x[idx] = maximum(x[idx], y) , if multiple indices refer to thesame location the final value will be the overall max. (NumPy would only look at the last update,rather than all of the updates.) Args: x: an array with the values to be updated. idx: a Numpy-style index, consisting of
None ,integers, slice objects,ellipses, ndarrays with integer dtypes, or a tuple of the above. A convenient syntacticsugar for forming indices is via the jax.ops.index object. y: the array of updates. y must be broadcastable to the shape of the array that would be re-turned by x[idx] . Returns:
An array. >>> x = jax.numpy.ones((5, 6)) >>> jax.ops.index_max(x, jax.ops.index[2:4, 3:], 6.)array([[1., 1., 1., 1., 1., 1.],[1., 1., 1., 1., 1., 1.],[1., 1., 1., 6., 6., 6.],[1., 1., 1., 6., 6., 6.],[1., 1., 1., 1., 1., 1.]], dtype=float32) index_min ( x , idx , y ) Pure equivalent of x[idx] = minimum(x[idx], y) . LAX-backend implementation of index_min() . ADDITIONOriginal docstring below.Returns the value of x that would result from the NumPy-style indexed assignment :: x[idx] = minimum(x[idx], y)Note the index_min operator is pure; x itself is not modified, instead the new value that x would havetaken is returned.Unlike the NumPy code x[idx] = minimum(x[idx], y) , if multiple indices refer to thesame location the final value will be the overall min. (NumPy would only look at the last update,rather than all of the updates.) Args: x: an array with the values to be updated. idx: a Numpy-style index, consisting of
None ,integers, slice objects,ellipses, ndarrays with integer dtypes, or a tuple of the above. A convenient syntacticsugar for forming indices is via the jax.ops.index object. y: the array of updates. y must be broadcastable to the shape of the array that would be re-turned by x[idx] . Returns:
An array. >>> x = jax.numpy.ones((5, 6)) >>> jax.ops.index_minimum(x, jax.ops.index[2:4, 3:], 0.)array([[1., 1., 1., 1., 1., 1.],[1., 1., 1., 1., 1., 1.],[1., 1., 1., 0., 0., 0.],[1., 1., 1., 0., 0., 0.],[1., 1., 1., 1., 1., 1.]], dtype=float32)
Numpy Like hat_1D ( x , t_left , t_center , t_right ) hat basis function in 1-DHat function, continuous piecewise linear Parameters • x ( array-like ) – the sampled input space• t_left ( scalar ) – the position of the left knot• t_center ( scalar ) – the position of the center knot• t_right ( scalar ) – the position of the right knot Returns output – same shape as x with applied hat function
Return type array one_hot ( i , N , dtype='float32' ) Create a one-hot encoding of x of size k.
14 Chapter 2. APIymjax, Release 0.0.1Other abs ( x ) Calculate the absolute value element-wise.LAX-backend implementation of absolute() . ADDITIONOriginal docstring below.LAX-backend implementation of absolute() . Original docstring below.absolute(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) np.abs is a shorthand for this function. Returns absolute – An ndarray containing the absolute value of each element in x . For complexinput, a + ib , the absolute value is √ 𝑎 + 𝑏 . This is a scalar if x is a scalar. Return type ndarray
Examples >>> x = np.array([-1.2, 1.2]) >>> np.absolute(x)array([ 1.2, 1.2]) >>> np.absolute(1.2 + 1j)1.5620499351813308
Plot the function over [-10, 10] : >>> import matplotlib.pyplot as plt>>> x = np.linspace(start=-10, stop=10, num=101) >>> plt.plot(x, np.absolute(x)) >>> plt.show() Plot the function over the complex plane: >>> xx = x + 1j * x[:, np.newaxis] >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray') >>> plt.show() absolute ( x ) Calculate the absolute value element-wise.LAX-backend implementation of absolute() . ADDITIONOriginal docstring below.LAX-backend implementation of absolute() . Original docstring below.absolute(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) np.abs is a shorthand for this function. Returns absolute – An ndarray containing the absolute value of each element in x . For complexinput, a + ib , the absolute value is √ 𝑎 + 𝑏 . This is a scalar if x is a scalar. Return type ndarray >>> x = np.array([-1.2, 1.2]) >>> np.absolute(x)array([ 1.2, 1.2]) >>> np.absolute(1.2 + 1j)1.5620499351813308
Plot the function over [-10, 10] : >>> import matplotlib.pyplot as plt>>> x = np.linspace(start=-10, stop=10, num=101) >>> plt.plot(x, np.absolute(x)) >>> plt.show() Plot the function over the complex plane: >>> xx = x + 1j * x[:, np.newaxis] >>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray') >>> plt.show() add ( x1 , x2 ) Add arguments element-wise.LAX-backend implementation of add() . ADDITIONOriginal docstring below.LAX-backend implementation of add() . Original docstring below.add(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns add – The sum of x1 and x2 , element-wise. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
Notes
Equivalent to x1 + x2 in terms of array broadcasting. Examples >>> np.add(1.0, 4.0)5.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.add(x1, x2)array([[ 0., 2., 4.],[ 3., 5., 7.],[ 6., 8., 10.]]) all ( a , axis=None , dtype=None , out=None , keepdims=False ) Test whether all array elements along a given axis evaluate to True.LAX-backend implementation of all() . ADDITIONOriginal docstring below.LAX-backend implementation of all() . Original docstring below.
16 Chapter 2. APIymjax, Release 0.0.1
Returns all – A new boolean or array is returned unless out is specified, in which case a referenceto out is returned.
Return type ndarray, bool
See also: ndarray.all() equivalent method any()
Test whether any element along a given axis evaluates to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to
True because these are not equal to zero.
Examples >>> np.all([[
True , False ],[
True , True ]])False >>> np.all([[
True , False ],[
True , True ]], axis=0)array([ True, False]) >>> np.all([-1, 4, 5])True >>> np.all([1.0, np.nan])True >>> o=np.array(
False ) >>> z=np.all([-1, 4, 5], out=o) >>> id(z), id(o), z(28293632, 28293632, array(True)) allclose ( a , b , rtol=1e-05 , atol=1e-08 ) Returns True if two arrays are element-wise equal within a tolerance.LAX-backend implementation of allclose() . ADDITIONOriginal docstring below.LAX-backend implementation of allclose() . Original docstring below.The tolerance values are positive, typically very small numbers. The relative difference ( rtol * abs( b )) and theabsolute difference atol are added together to compare against the absolute difference between a and b .NaNs are treated as equal if they are in the same place and if equal_nan=True . Infs are treated as equal ifthey are in the same place and of the same sign in both arrays. Returns allclose – Returns True if the two arrays are equal within the given tolerance; False other-wise.
Return type bool
See also: isclose() , all() , any() , equal() If the following equation is element-wise True, then allclose returns True.absolute( a - b ) <= ( atol + rtol * absolute( b ))The above equation is not symmetric in a and b , so that allclose(a, b) might be different from allclose(b, a) in some rare cases.The comparison of a and b uses standard broadcasting, which means that a and b need not have the same shapein order for allclose(a, b) to evaluate to True. The same is true for equal but not array_equal . Examples >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])False >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])True >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])False >>> np.allclose([1.0, np.nan], [1.0, np.nan])False >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=
True )True alltrue ( a , axis=None , dtype=None , out=None , keepdims=False ) Test whether all array elements along a given axis evaluate to True.LAX-backend implementation of all() . ADDITIONOriginal docstring below.LAX-backend implementation of all() . Original docstring below.
Returns all – A new boolean or array is returned unless out is specified, in which case a referenceto out is returned.
Return type ndarray, bool
See also: ndarray.all() equivalent method any()
Test whether any element along a given axis evaluates to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to
True because these are not equal to zero.
Examples >>> np.all([[
True , False ],[
True , True ]])False >>> np.all([[
True , False ],[
True , True ]], axis=0)array([ True, False])
18 Chapter 2. APIymjax, Release 0.0.1 >>> np.all([-1, 4, 5])True >>> np.all([1.0, np.nan])True >>> o=np.array(
False ) >>> z=np.all([-1, 4, 5], out=o) >>> id(z), id(o), z(28293632, 28293632, array(True)) amax ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the maximum of an array or maximum along an axis.LAX-backend implementation of amax() . ADDITIONOriginal docstring below.LAX-backend implementation of amax() . Original docstring below.
Returns amax – Maximum of a . If axis is None, the result is a scalar value. If axis is given, theresult is an array of dimension a.ndim - 1 . Return type ndarray or scalar
See also: amin()
The minimum value of an array along a given axis, propagating any NaNs. nanmax()
The maximum value of an array along a given axis, ignoring any NaNs. maximum()
Element-wise maximum of two arrays, propagating any NaNs. fmax()
Element-wise maximum of two arrays, ignoring any NaNs. argmax()
Return the indices of the maximum values. nanmin() , minimum() , fmin() Notes
NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well.To ignore NaN values (MATLAB behavior), please use nanmax.Don’t use amax for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0],a[1]) is faster than amax(a, axis=0) . Examples >>> a = np.arange(4).reshape((2,2)) >>> aarray([[0, 1],[2, 3]]) >>> np.amax(a) >>> np.amax(a, axis=0) array([2, 3]) >>> np.amax(a, axis=1) array([1, 3]) (continues on next page) (continued from previous page) >>> np.amax(a, where=[ False , True ], initial=-1, axis=0)array([-1, 3]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amax(b)nan >>> np.amax(b, where=~np.isnan(b), initial=-1)4.0 >>> np.nanmax(b)4.0
You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value: >>> np.max([[-50], [10]], axis=-1, initial=0)array([ 0, 10])
Notice that the initial value is used as one of the elements for which the maximum is determined, unlike for thedefault argument Python’s max function, which is only used for empty iterables. >>> np.max([5], initial=6)6 >>> max([5], default=6)5 amin ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the minimum of an array or minimum along an axis.LAX-backend implementation of amin() . ADDITIONOriginal docstring below.LAX-backend implementation of amin() . Original docstring below.
Returns amin – Minimum of a . If axis is None, the result is a scalar value. If axis is given, theresult is an array of dimension a.ndim - 1 . Return type ndarray or scalar
See also: amax()
The maximum value of an array along a given axis, propagating any NaNs. nanmin()
The minimum value of an array along a given axis, ignoring any NaNs. minimum()
Element-wise minimum of two arrays, propagating any NaNs. fmin()
Element-wise minimum of two arrays, ignoring any NaNs. argmin()
Return the indices of the minimum values. nanmax() , maximum() , fmax()
20 Chapter 2. APIymjax, Release 0.0.1Notes
NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well.To ignore NaN values (MATLAB behavior), please use nanmin.Don’t use amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0) . Examples >>> a = np.arange(4).reshape((2,2)) >>> aarray([[0, 1],[2, 3]]) >>> np.amin(a) >>> np.amin(a, axis=0) array([0, 1]) >>> np.amin(a, axis=1) array([0, 2]) >>> np.amin(a, where=[ False , True ], initial=10, axis=0)array([10, 1]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amin(b)nan >>> np.amin(b, where=~np.isnan(b), initial=10)0.0 >>> np.nanmin(b)0.0 >>> np.min([[-50], [10]], axis=-1, initial=0)array([-50, 0])
Notice that the initial value is used as one of the elements for which the minimum is determined, unlike for thedefault argument Python’s max function, which is only used for empty iterables.Notice that this isn’t the same as Python’s default argument. >>> np.min([6], initial=5)5 >>> min([6], default=5)6 angle ( z ) Return the angle of the complex argument.LAX-backend implementation of angle() . ADDITIONOriginal docstring below.LAX-backend implementation of angle() . Original docstring below.
Returnsangle – The counterclockwise angle from the positive real axis on the complex plane in the range (-pi, pi] , with dtype as numpy.float64. ..versionchanged:: 1.16.0
This function works on subclasses of ndarray like ma.array . Return type ndarray or scalar
See also: arctan2() , absolute() Examples >>> np.angle([1.0, 1.0j, 1+1j]) array([ 0. , 1.57079633, 0.78539816]) >>> np.angle(1+1j, deg=
True ) any ( a , axis=None , dtype=None , out=None , keepdims=False ) Test whether any array element along a given axis evaluates to True.LAX-backend implementation of any() . ADDITIONOriginal docstring below.LAX-backend implementation of any() . Original docstring below.Returns single boolean unless axis is not
None
Returns any – A new boolean or ndarray is returned unless out is specified, in which case a refer-ence to out is returned.
Return type bool or ndarray
See also: ndarray.any() equivalent method all()
Test whether all elements along a given axis evaluate to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to
True because these are not equal to zero.
Examples >>> np.any([[
True , False ], [
True , True ]])True >>> np.any([[
True , False ], [
False , False ]], axis=0)array([ True, False]) >>> np.any([-1, 0, 5])True >>> np.any(np.nan)True >>> o=np.array(
False ) >>> z=np.any([-1, 4, 5], out=o) >>> z, o(array(True), array(True)) (continues on next page)
22 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) >>> >>> z is oTrue >>> id(z), id(o) (191614240, 191614240) append ( arr , values , axis=None ) Append values to the end of an array.LAX-backend implementation of append() . ADDITIONOriginal docstring below.LAX-backend implementation of append() . Original docstring below.
Returns append – A copy of arr with values appended to axis . Note that append does not occurin-place: a new array is allocated and filled. If axis is None, out is a flattened array.
Return type ndarray
See also: insert()
Insert elements into an array. delete()
Delete elements from an array.
Examples >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])array([1, 2, 3, ..., 7, 8, 9])
When axis is specified, values must have the correct shape. >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)Traceback (most recent call last):...ValueError: all the input arrays must have same number of dimensions arange ( start , stop=None , step=None , dtype=None ) Return evenly spaced values within a given interval.LAX-backend implementation of arange() . ADDITIONOriginal docstring below.LAX-backend implementation of arange() . Original docstring below.arange([start,] stop[, step,], dtype=None)Values are generated within the half-open interval [start, stop) (in other words, theinterval including start but excluding stop ). For integer arguments the function is equivalentto the Python built-in range function, but returns an ndarray rather than a list.When using a non-integer step, such as 0.1, the results will often not be consistent. It isbetter to use numpy.linspace for these cases.
Returns arange [ndarray] Array of evenly spaced values.For floating point arguments, the length of the result is ceil((stop - start)/step) . Because of floating point overflow, this rule may result in the last element of out being greater than stop .numpy.linspace : Evenly spaced numbers with careful handling of endpoints. numpy.ogrid:Arrays of evenly spaced numbers in N-dimensions. numpy.mgrid: Grid-shaped arrays of evenlyspaced numbers in N-dimensions. >>> np.arange(3)array([0, 1, 2]) >>> np.arange(3.0)array([ 0., 1., 2.]) >>> np.arange(3,7)array([3, 4, 5, 6]) >>> np.arange(3,7,2)array([3, 5]) arccos ( x ) Trigonometric inverse cosine, element-wise.LAX-backend implementation of arccos() . ADDITIONOriginal docstring below.LAX-backend implementation of arccos() . Original docstring below.arccos(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])The inverse of cos so that, if y = cos(x) , then x = arccos(y) . Returns angle – The angle of the ray intersecting the unit circle at the given x -coordinate in radians[0, pi]. This is a scalar if x is a scalar. Return type ndarray
See also: cos() , arctan() , arcsin() , emath.arccos() Notes arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x . Theconvention is to return the angle z whose real part lies in [0, pi] .For real-valued input data types, arccos always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, arccos is a complex analytic function that has branch cuts [-inf, -1] and [1, inf] andis continuous from above on the former and from below on the latter.The inverse cos is also known as acos or cos^-1.
24 Chapter 2. APIymjax, Release 0.0.1References
Examples
We expect the arccos of 1 to be 0, and of -1 to be pi: >>> np.arccos([1, -1])array([ 0. , 3.14159265])
Plot arccos: >>> import matplotlib.pyplot as plt>>> x = np.linspace(-1, 1, num=100) >>> plt.plot(x, np.arccos(x)) >>> plt.axis('tight') >>> plt.show() arccosh ( x ) Inverse hyperbolic cosine, element-wise.LAX-backend implementation of arccosh() . ADDITIONOriginal docstring below.LAX-backend implementation of arccosh() . Original docstring below.arccosh(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns arccosh – Array of the same shape as x . This is a scalar if x is a scalar. Return type ndarray
See also: cosh() , arcsinh() , sinh() , arctanh() , tanh() Notes arccosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x . Theconvention is to return the z whose imaginary part lies in [-pi, pi] and the real part in [0, inf] .For real-valued input data types, arccosh always returns real output. For each value that cannot be expressed asa real number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, arccosh is a complex analytical function that has a branch cut [-inf, 1] and is contin-uous from above on it. >>> np.arccosh([np.e, 10.0])array([ 1.65745445, 2.99322285]) >>> np.arccosh(1)0.0 arcsin ( x ) Inverse sine, element-wise.LAX-backend implementation of arcsin() . ADDITIONOriginal docstring below.LAX-backend implementation of arcsin() . Original docstring below.arcsin(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns angle – The inverse sine of each element in x , in radians and in the closed interval [-pi/2, pi/2] . This is a scalar if x is a scalar. Return type ndarray
See also: sin() , cos() , arccos() , tan() , arctan() , arctan2() , emath.arcsin() Notes arcsin is a multivalued function: for each x there are infinitely many numbers z such that 𝑠𝑖𝑛 ( 𝑧 ) = 𝑥 . Theconvention is to return the angle z whose real part lies in [-pi/2, pi/2].For real-valued input data types, arcsin always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, arcsin is a complex analytic function that has, by convention, the branch cuts [-inf,-1] and [1, inf] and is continuous from above on the former and from below on the latter.The inverse sine is also known as asin or sin^{-1}. References
Abramowitz, M. and Stegun, I. A.,
Handbook of Mathematical Functions
Examples >>> np.arcsin(1) >>> np.arcsin(-1) -1.5707963267948966 >>> np.arcsin(0)0.0
26 Chapter 2. APIymjax, Release 0.0.1 arcsinh ( x ) Inverse hyperbolic sine element-wise.LAX-backend implementation of arcsinh() . ADDITIONOriginal docstring below.LAX-backend implementation of arcsinh() . Original docstring below.arcsinh(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Array of the same shape as x . This is a scalar if x is a scalar. Return type ndarray or scalar
Notes arcsinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x . Theconvention is to return the z whose imaginary part lies in [-pi/2, pi/2] .For real-valued input data types, arcsinh always returns real output. For each value that cannot be expressed asa real number or infinity, it returns nan and sets the invalid floating point error flag.For complex-valued input, arccos is a complex analytical function that has branch cuts [1j, infj] and [-1j, -infj] and is continuous from the right on the former and from the left on the latter.The inverse hyperbolic sine is also known as asinh or sinh^-1 . ReferencesExamples >>> np.arcsinh(np.array([np.e, 10.0]))array([ 1.72538256, 2.99822295]) arctan ( x ) Trigonometric inverse tangent, element-wise.LAX-backend implementation of arctan() . ADDITIONOriginal docstring below.LAX-backend implementation of arctan() . Original docstring below.arctan(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])The inverse of tan, so that if y = tan(x) then x = arctan(y) . Returns out – Out has the same shape as x . Its real part is in [-pi/2, pi/2] ( arctan(+/-inf) returns +/-pi/2 ). This is a scalar if x is a scalar. Return type ndarray or scalar
See also: arctan2()
The “four quadrant” arctan of the angle formed by ( x , y ) and the positive x -axis. angle() Argument of complex values. arctan is a multi-valued function: for each x there are infinitely many numbers z such that tan( z ) = x . Theconvention is to return the angle z whose real part lies in [-pi/2, pi/2].For real-valued input data types, arctan always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, arctan is a complex analytic function that has [ ] and [ -1j, -infj ] as branch cuts,and is continuous from the left on the former and from the right on the latter.The inverse tangent is also known as atan or tan^{-1}. References
Abramowitz, M. and Stegun, I. A.,
Handbook of Mathematical Functions
Examples
We expect the arctan of 0 to be 0, and of 1 to be pi/4: >>> np.arctan([0, 1])array([ 0. , 0.78539816]) >>> np.pi/40.78539816339744828
Plot arctan: >>> import matplotlib.pyplot as plt>>> x = np.linspace(-10, 10) >>> plt.plot(x, np.arctan(x)) >>> plt.axis('tight') >>> plt.show() arctan2 ( x1 , x2 ) Element-wise arc tangent of x1/x2 choosing the quadrant correctly.LAX-backend implementation of arctan2() . ADDITIONOriginal docstring below.LAX-backend implementation of arctan2() . Original docstring below.arctan2(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, sig-nature, extobj])The quadrant (i.e., branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between theray ending at the origin and passing through the point (1,0), and the ray ending at the origin and passing throughthe point ( x2 , x1 ). (Note the role reversal: the “ y -coordinate” is the first function parameter, the “ x -coordinate”is the second.) By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 =+/-inf (see Notes for specific values).This function is not defined for complex-valued arguments; for the so-called argument of complex values, use angle . Returns angle – Array of angles in radians, in the range [-pi, pi] . This is a scalar if both x1 and x2 are scalars.
28 Chapter 2. APIymjax, Release 0.0.1
Return type ndarray
See also: arctan() , tan() , angle() Notes arctan2 is identical to the atan2 function of the underlying C library. The following special values are definedin the C standard: [1]_ x1 x2 arctan2(x1,x2) +/- 0 +0 +/- 0+/- 0 -0 +/- pi> 0 +/-inf +0 / +pi< 0 +/-inf -0 / -pi+/-inf +inf +/- (pi/4)+/-inf -inf +/- (3*pi/4)Note that +0 and -0 are distinct floating point numbers, as are +inf and -inf.
ReferencesExamples
Consider four points in different quadrants: >>> x = np.array([-1, +1, +1, -1]) >>> y = np.array([-1, -1, +1, +1]) >>> np.arctan2(y, x) * 180 / np.piarray([-135., -45., 45., 135.])
Note the order of the parameters. arctan2 is defined also when x2 = 0 and at several other special points,obtaining values in the range [-pi, pi] : >>> np.arctan2([1., -1.], [0., 0.])array([ 1.57079633, -1.57079633]) >>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])array([ 0. , 3.14159265, 0.78539816]) arctanh ( x ) Inverse hyperbolic tangent element-wise.LAX-backend implementation of arctanh() . ADDITIONOriginal docstring below.LAX-backend implementation of arctanh() . Original docstring below.arctanh(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Array of the same shape as x . This is a scalar if x is a scalar. Return type ndarray or scalar
See also: emath.arctanh() arctanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x . Theconvention is to return the z whose imaginary part lies in [-pi/2, pi/2] .For real-valued input data types, arctanh always returns real output. For each value that cannot be expressed asa real number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, arctanh is a complex analytical function that has branch cuts [-1, -inf] and [1, inf] and is continuous from above on the former and from below on the latter.The inverse hyperbolic tangent is also known as atanh or tanh^-1 . ReferencesExamples >>> np.arctanh([0, -0.5])array([ 0. , -0.54930614]) argmax ( a , axis=None ) Returns the indices of the maximum values along an axis.LAX-backend implementation of argmax() . ADDITIONOriginal docstring below.LAX-backend implementation of argmax() . Original docstring below.
Returns index_array – Array of indices into the array. It has the same shape as a.shape with thedimension along axis removed.
Return type ndarray of ints
See also: ndarray.argmax() , argmin() amax() The maximum value along a given axis. unravel_index()
Convert a flat index into an index tuple. take_along_axis()
Apply np.expand_dims(index_array, axis) from argmax to an array asif by calling max.
Notes
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence arereturned.
Examples >>> a = np.arange(6).reshape(2,3) + 10 >>> aarray([[10, 11, 12],[13, 14, 15]]) >>> np.argmax(a)5 >>> np.argmax(a, axis=0) (continues on next page)
30 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) array([1, 1, 1]) >>> np.argmax(a, axis=1)array([2, 2])
Indexes of the maximal elements of a N-dimensional array: >>> ind = np.unravel_index(np.argmax(a, axis=
None ), a.shape) >>> ind(1, 2) >>> a[ind]15 >>> b = np.arange(6) >>> b[1] = 5 >>> barray([0, 5, 2, 3, 4, 5]) >>> np.argmax(b) >>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmax(x, axis=-1) >>> >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)array([[4],[3]]) >>> >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1). ˓ → squeeze(axis=-1)array([4, 3]) argmin ( a , axis=None ) Returns the indices of the minimum values along an axis.LAX-backend implementation of argmin() . ADDITIONOriginal docstring below.LAX-backend implementation of argmin() . Original docstring below.
Returns index_array – Array of indices into the array. It has the same shape as a.shape with thedimension along axis removed.
Return type ndarray of ints
See also: ndarray.argmin() , argmax() amin() The minimum value along a given axis. unravel_index()
Convert a flat index into an index tuple. take_along_axis()
Apply np.expand_dims(index_array, axis) from argmin to an array asif by calling min.
In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence arereturned.
Examples >>> a = np.arange(6).reshape(2,3) + 10 >>> aarray([[10, 11, 12],[13, 14, 15]]) >>> np.argmin(a)0 >>> np.argmin(a, axis=0)array([0, 0, 0]) >>> np.argmin(a, axis=1)array([0, 0])
Indices of the minimum elements of a N-dimensional array: >>> ind = np.unravel_index(np.argmin(a, axis=
None ), a.shape) >>> ind(0, 0) >>> a[ind]10 >>> b = np.arange(6) + 10 >>> b[4] = 10 >>> barray([10, 11, 12, 13, 10, 15]) >>> np.argmin(b) >>> x = np.array([[4,2,3], [1,0,3]]) >>> index_array = np.argmin(x, axis=-1) >>> >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)array([[2],[0]]) >>> >>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1). ˓ → squeeze(axis=-1)array([2, 0]) argsort ( a , axis=- 1 , kind='quicksort' , order=None ) Returns the indices that would sort an array.LAX-backend implementation of argsort() . ADDITIONOriginal docstring below.LAX-backend implementation of argsort() . Original docstring below.Perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns anarray of indices of the same shape as a that index data along the given axis in sorted order. Returns index_array – Array of indices that sort a along the specified axis . If a is one-dimensional, a[index_array] yields a sorted a . More generally, np.take_along_axis(a,index_array, axis=axis) always yields the sorted a , irrespective of dimensionality.
32 Chapter 2. APIymjax, Release 0.0.1
Return type ndarray, int
See also: sort()
Describes sorting algorithms used. lexsort()
Indirect stable sort with multiple keys. ndarray.sort()
Inplace sort. argpartition()
Indirect partial sort. take_along_axis()
Apply index_array from argsort to an array as if by calling sort.
Notes
See sort for notes on the different sorting algorithms.As of NumPy 1.4.0 argsort works with real/complex arrays containing nan values. The enhanced sort order isdocumented in sort . Examples
One dimensional array: >>> x = np.array([3, 1, 2]) >>> np.argsort(x)array([1, 2, 0])
Two-dimensional array: >>> x = np.array([[0, 3], [2, 2]]) >>> xarray([[0, 3],[2, 2]]) >>> ind = np.argsort(x, axis=0) >>> indarray([[0, 1],[1, 0]]) >>> np.take_along_axis(x, ind, axis=0) array([[0, 2],[2, 3]]) >>> ind = np.argsort(x, axis=1) >>> indarray([[0, 1],[0, 1]]) >>> np.take_along_axis(x, ind, axis=1) array([[0, 3],[2, 2]])
Indices of the sorted elements of a N-dimensional array: >>> ind = np.unravel_index(np.argsort(x, axis=
None ), x.shape) >>> ind(array([0, 1, 1, 0]), array([0, 0, 1, 1])) (continues on next page) (continued from previous page) >>> x[ind] array([0, 2, 2, 3])
Sorting with keys: >>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '
Parameters dtype ( data-type, optional ) – By default, the data-type is inferred from theinput data. Returns out – Array interpretation of a . No copy is performed if the input is already an ndarraywith matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned. Return type ndarray
See also: asanyarray()
Similar function which passes through subclasses. ascontiguousarray()
Convert input to a contiguous array. asfarray()
Convert input to a floating point ndarray. asfortranarray()
Convert input to an ndarray with column-major memory order. asarray_chkfinite()
Similar function which checks input for NaNs and Infs. fromiter()
Create an array from an iterator. fromfunction()
Construct an array by executing a function on grid positions.
34 Chapter 2. APIymjax, Release 0.0.1Examples
Convert a list into an array: >>> a = [1, 2] >>> np.asarray(a)array([1, 2])
Existing arrays are not copied: >>> a = np.array([1, 2]) >>> np.asarray(a) is aTrue If dtype is set, array is copied only if dtype does not match: >>> a = np.array([1, 2], dtype=np.float32) >>> np.asarray(a, dtype=np.float32) is aTrue >>> np.asarray(a, dtype=np.float64) is aFalse Contrary to asanyarray , ndarray subclasses are not passed through: >>> issubclass(np.recarray, np.ndarray)True >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) >>> np.asarray(a) is aFalse >>> np.asanyarray(a) is aTrue atleast_1d ( *arys ) Convert inputs to arrays with at least one dimension.LAX-backend implementation of atleast_1d() . ADDITIONOriginal docstring below.LAX-backend implementation of atleast_1d() . Original docstring below.Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs arepreserved.
Returnsret [ndarray] An array, or list of arrays, each with a.ndim >= 1 . Copies are made only ifnecessary.atleast_2d, atleast_3d >>> np.atleast_1d(1.0)array([1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x)array([[0., 1., 2.],[3., 4., 5.],[6., 7., 8.]]) >>> np.atleast_1d(x) is xTrue >>> np.atleast_1d(1, [3, 4])[array([1]), array([3, 4])] atleast_2d ( *arys ) View inputs as arrays with at least two dimensions.LAX-backend implementation of atleast_2d() . ADDITIONOriginal docstring below.LAX-backend implementation of atleast_2d() . Original docstring below.
Returnsres, res2, . . . [ndarray] An array, or list of arrays, each with a.ndim >= 2 . Copies areavoided where possible, and views with two or more dimensions are returned.atleast_1d, atleast_3d >>> np.atleast_2d(3.0)array([[3.]]) >>> x = np.arange(3.0) >>> np.atleast_2d(x)array([[0., 1., 2.]]) >>> np.atleast_2d(x).base is xTrue >>> np.atleast_2d(1, [1, 2], [[1, 2]])[array([[1]]), array([[1, 2]]), array([[1, 2]])] atleast_3d ( *arys ) View inputs as arrays with at least three dimensions.LAX-backend implementation of atleast_3d() . ADDITIONOriginal docstring below.LAX-backend implementation of atleast_3d() . Original docstring below.
Returnsres1, res2, . . . [ndarray] An array, or list of arrays, each with a.ndim >= 3 . Copies areavoided where possible, and views with three or more dimensions are returned. For example,a 1-D array of shape (N,) becomes a view of shape (1, N, 1) , and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1) .atleast_1d, atleast_2d >>> np.atleast_3d(3.0)array([[[3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape(1, 3, 1)
36 Chapter 2. APIymjax, Release 0.0.1 >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape(4, 3, 1) >>> np.atleast_3d(x).base is x.base ˓ → itself True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print(arr, arr.shape) ... [[[1][2]]] (1, 2, 1)[[[1][2]]] (1, 2, 1)[[[1 2]]] (1, 1, 2) bitwise_and ( x1 , x2 ) Compute the bit-wise AND of two arrays element-wise.LAX-backend implementation of bitwise_and() . ADDITIONOriginal docstring below.LAX-backend implementation of bitwise_and() . Original docstring below.bitwise_and(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. Thisufunc implements the C/Python operator & . Returns out – Result. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
See also: logical_and() , bitwise_or() , bitwise_xor() binary_repr() Return the binary representation of the input number as a string.
Examples
The number 13 is represented by . Likewise, 17 is represented by . The bit-wise ANDof 13 and 17 is therefore , or 1: >>> np.bitwise_and(13, 17)1 >>> np.bitwise_and(14, 13)12 >>> np.binary_repr(12)'1100' >>> np.bitwise_and([14,3], 13)array([12, 1]) >>> np.bitwise_and([11,7], [4,25])array([0, 1]) >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16])) (continues on next page) (continued from previous page) array([ 2, 4, 16]) >>> np.bitwise_and([
True , True ], [
False , True ])array([False, True]) bitwise_not ( x ) Compute bit-wise inversion, or bit-wise NOT, element-wise.LAX-backend implementation of invert() . ADDITIONOriginal docstring below.LAX-backend implementation of invert() . Original docstring below.invert(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. Thisufunc implements the C/Python operator ~ .For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbersare represented by the two’s complement of the absolute value. This is the most common method of representingsigned integers on computers [1]_ . A N-bit two’s-complement system can represent every integer in the range − 𝑁 − to +2 𝑁 − − . Returns out – Result. This is a scalar if x is a scalar. Return type ndarray or scalar
See also: bitwise_and() , bitwise_or() , bitwise_xor() , logical_not() binary_repr() Return the binary representation of the input number as a string.
Notes bitwise_not is an alias for invert : >>> np.bitwise_not is np.invertTrue ReferencesExamples
We’ve seen that 13 is represented by . The invert or bit-wise NOT of 13 is then: >>> x = np.invert(np.array(13, dtype=np.uint8)) >>> x242 >>> np.binary_repr(x, width=8)'11110010'
The result depends on the bit-width: >>> x = np.invert(np.array(13, dtype=np.uint16)) >>> x65522 (continues on next page)
38 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) >>> np.binary_repr(x, width=16)'1111111111110010'
When using signed integer types the result is the two’s complement of the result for the unsigned type: >>> np.invert(np.array([13], dtype=np.int8))array([-14], dtype=int8) >>> np.binary_repr(-14, width=8)'11110010'
Booleans are accepted as well: >>> np.invert(np.array([
True , False ]))array([False, True]) bitwise_or ( x1 , x2 ) Compute the bit-wise OR of two arrays element-wise.LAX-backend implementation of bitwise_or() . ADDITIONOriginal docstring below.LAX-backend implementation of bitwise_or() . Original docstring below.bitwise_or(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufuncimplements the C/Python operator | . Returns out – Result. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
See also: logical_or() , bitwise_and() , bitwise_xor() binary_repr() Return the binary representation of the input number as a string.
Examples
The number 13 has the binaray representation . Likewise, 16 is represented by . Thebit-wise OR of 13 and 16 is then , or 29: >>> np.bitwise_or(13, 16)29 >>> np.binary_repr(29)'11101' >>> np.bitwise_or(32, 2)34 >>> np.bitwise_or([33, 4], 1)array([33, 5]) >>> np.bitwise_or([33, 4], [1, 2])array([33, 6]) >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))array([ 6, 5, 255]) (continues on next page) (continued from previous page) >>> np.array([2, 5, 255]) | np.array([4, 4, 4])array([ 6, 5, 255]) >>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32), ... np.array([4, 4, 4, 2147483647], dtype=np.int32))array([ 6, 5, 255, 2147483647]) >>> np.bitwise_or([
True , True ], [
False , True ])array([ True, True]) bitwise_xor ( x1 , x2 ) Compute the bit-wise XOR of two arrays element-wise.LAX-backend implementation of bitwise_xor() . ADDITIONOriginal docstring below.LAX-backend implementation of bitwise_xor() . Original docstring below.bitwise_xor(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. Thisufunc implements the C/Python operator ^ . Returns out – Result. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
See also: logical_xor() , bitwise_and() , bitwise_or() binary_repr() Return the binary representation of the input number as a string.
Examples
The number 13 is represented by . Likewise, 17 is represented by . The bit-wise XORof 13 and 17 is therefore , or 28: >>> np.bitwise_xor(13, 17)28 >>> np.binary_repr(28)'11100' >>> np.bitwise_xor(31, 5)26 >>> np.bitwise_xor([31,3], 5)array([26, 6]) >>> np.bitwise_xor([31,3], [5,6])array([26, 5]) >>> np.bitwise_xor([
True , True ], [
False , True ])array([ True, False]) block ( arrays ) Assemble an nd-array from nested lists of blocks.LAX-backend implementation of block() . ADDITIONOriginal docstring below.LAX-backend implementation of block() . Original docstring below.
40 Chapter 2. APIymjax, Release 0.0.1
Blocks in the innermost lists are concatenated (see concatenate ) along the last dimension (-1), then these areconcatenated along the second-last dimension (-2), and so on until the outermost list is reached.Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes ofsize 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working withscalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1 .When the nested list is two levels deep, this allows block matrices to be constructed from their components.New in version 1.13.0.
Returnsblock_array – The array assembled from the given blocks.The dimensionality of the output is equal to the greatest of: * the dimensionality of all the inputs* the depth to which the input list is nested
Return type ndarray
Raises
ValueError –• If list depths are mismatched - for instance, [[a, b], c] is illegal, and should be spelt [[a, b], [c]] * If lists are empty - for instance, [[a, b], []]
See also: concatenate()
Join a sequence of arrays together. stack()
Stack arrays in sequence along a new dimension. hstack()
Stack arrays in sequence horizontally (column wise). vstack()
Stack arrays in sequence vertically (row wise). dstack()
Stack arrays in sequence depth wise (along third dimension). vsplit()
Split array into a list of multiple sub-arrays vertically.
Notes
When called with only scalars, np.block is equivalent to an ndarray call. So np.block([[1, 2], [3,4]]) is equivalent to np.array([[1, 2], [3, 4]]) .This function does not enforce that the blocks lie on a fixed grid. np.block([[a, b], [c, d]]) is notrestricted to arrays of the form:
AAAbbAAAbbcccDD
But is also allowed to produce, for some a, b, c, d : AAAbbAAAbbcDDDD
Since concatenation happens along the last axis first, block is _not_ capable of producing the following directly:
AAAbbcccbbcccDD
Matlab’s “square bracket stacking”, [A, B, ...; p, q, ...] , is equivalent to np.block([[A, B,...], [p, q, ...]]) . Examples
The most common use of this function is to build a block matrix >>>
A = np.eye(2) * 2 >>>
B = np.eye(3) * 3 >>> np.block([ ... [A, np.zeros((2, 3))], ... [np.ones((3, 2)), B ] ... ])array([[2., 0., 0., 0., 0.],[0., 2., 0., 0., 0.],[1., 1., 3., 0., 0.],[1., 1., 0., 3., 0.],[1., 1., 0., 0., 3.]])
With a list of depth 1, block can be used as hstack >>> np.block([1, 2, 3]) array([1, 2, 3]) >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.block([a, b, 10]) array([ 1, 2, 3, 2, 3, 4, 10]) >>>
A = np.ones((2, 2), int) >>>
B = 2 * A >>> np.block([A, B]) array([[1, 1, 2, 2],[1, 1, 2, 2]])
With a list of depth 2, block can be used in place of vstack : >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.block([[a], [b]]) array([[1, 2, 3],[2, 3, 4]]) >>> A = np.ones((2, 2), int) >>>
B = 2 * A >>> np.block([[A], [B]]) array([[1, 1],[1, 1],[2, 2],[2, 2]])
It can also be used in places of atleast_1d and atleast_2d >>> a = np.array(0) >>> b = np.array([1]) (continues on next page)
42 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) >>> np.block([a]) array([0]) >>> np.block([b]) array([1]) >>> np.block([[a]]) array([[0]]) >>> np.block([[b]]) array([[1]]) can_cast () Returns True if cast between data types can occur according to the casting rule. If from is a scalar or arrayscalar, also returns True if the scalar value can be cast without overflow or truncation to an integer.LAX-backend implementation of can_cast() . ADDITIONOriginal docstring below.can_cast( from_ , to, casting=’safe’)
Returnsout [bool] True if cast can occur according to the casting rule.Changed in version 1.17.0: Casting between a simple data type and a structured one is possibleonly for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fieldsis not.Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requiresthat the string dtype length is long enough to store the maximum integer/float value converted.dtype, result_typeBasic examples >>> np.can_cast(np.int32, np.int64)True >>> np.can_cast(np.float64, complex)True >>> np.can_cast(complex, float)False >>> np.can_cast('i8', 'f8')True >>> np.can_cast('i8', 'f4')False >>> np.can_cast('i4', 'S4')False
Casting scalars >>> np.can_cast(100, 'i1')True >>> np.can_cast(150, 'i1')False >>> np.can_cast(150, 'u1')True >>> np.can_cast(3.5e100, np.float32)False >>> np.can_cast(1000.0, np.float32)True
Array scalar checks the value, array does not >>> np.can_cast(np.array(1000.0), np.float32)True >>> np.can_cast(np.array([1000.0]), np.float32)False
Using the casting rules >>> np.can_cast('i8', 'i8', 'no')True >>> np.can_cast('
See also: floor() , trunc() , rint()
44 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.ceil(a)array([-1., -1., -0., 1., 2., 2., 2.]) clip ( a , a_min=None , a_max=None ) Clip (limit) the values in an array.LAX-backend implementation of clip() . ADDITIONOriginal docstring below.LAX-backend implementation of clip() . Original docstring below.Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.Equivalent to but faster than np.maximum(a_min, np.minimum(a, a_max)) . No check is performedto ensure a_min < a_max . Returns clipped_array – An array with the elements of a , but where values < a_min are replacedwith a_min , and those > a_max with a_max . Return type ndarray
See also: ufuncs-output-type()
Examples >>> a = np.arange(10) >>> np.clip(a, 1, 8)array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8]) >>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, 3, 6, out=a)array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) >>> a = np.arange(10) >>> aarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8]) column_stack ( tup ) Stack 1-D arrays as columns into a 2-D array.LAX-backend implementation of column_stack() . ADDITIONOriginal docstring below.LAX-backend implementation of column_stack() . Original docstring below.Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stackedas-is, just like with hstack . 1-D arrays are turned into 2-D columns first.
Returns stacked – The array formed by stacking the given arrays.
Return type
See also: stack() , hstack() , vstack() , concatenate() >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.column_stack((a,b))array([[1, 2],[2, 3],[3, 4]]) concatenate ( arrays , axis=0 ) Join a sequence of arrays along an existing axis.LAX-backend implementation of concatenate() . ADDITIONOriginal docstring below.LAX-backend implementation of concatenate() . Original docstring below.concatenate((a1, a2, . . . ), axis=0, out=None)
Returnsres [ndarray] The concatenated array.ma.concatenate : Concatenate function that preserves input masks. array_split : Split an arrayinto multiple sub-arrays of equal ornear-equal size.split : Split array into a list of multiple sub-arrays of equal size. hsplit : Split array into multiplesub-arrays horizontally (column wise) vsplit : Split array into multiple sub-arrays vertically(row wise) dsplit : Split array into multiple sub-arrays along the 3rd axis (depth). stack : Stacka sequence of arrays along a new axis. hstack : Stack arrays in sequence horizontally (columnwise) vstack : Stack arrays in sequence vertically (row wise) dstack : Stack arrays in sequencedepth wise (along third dimension) block : Assemble arrays from blocks.When one or more of the arrays to be concatenated is a MaskedArray, this function will returna MaskedArray object instead of an ndarray, but the input masks are not preserved. In caseswhere a MaskedArray is expected as input, use the ma.concatenate function from the maskedarray module instead. >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0)array([[1, 2],[3, 4],[5, 6]]) >>> np.concatenate((a, b.T), axis=1)array([[1, 2, 5],[3, 4, 6]]) >>> np.concatenate((a, b), axis=
None )array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs. >>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> amasked_array(data=[0, --, 2],mask=[False, True, False], (continues on next page)
46 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) fill_value=999999) >>> barray([2, 3, 4]) >>> np.concatenate([a, b])masked_array(data=[0, 1, 2, 2, 3, 4],mask=False,fill_value=999999) >>> np.ma.concatenate([a, b])masked_array(data=[0, --, 2, 2, 3, 4],mask=[False, True, False, False, False, False],fill_value=999999) conj ( x ) Return the complex conjugate, element-wise.LAX-backend implementation of conjugate() . ADDITIONOriginal docstring below.LAX-backend implementation of conjugate() . Original docstring below.conjugate(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj])The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Returns y – The complex conjugate of x , with same dtype as y . This is a scalar if x is a scalar. Return type ndarray
Notes conj is an alias for conjugate : >>> np.conj is np.conjugateTrue Examples >>> np.conjugate(1+2j)(1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x)array([[ 1.-1.j, 0.-0.j],[ 0.-0.j, 1.-1.j]]) conjugate ( x ) Return the complex conjugate, element-wise.LAX-backend implementation of conjugate() . ADDITIONOriginal docstring below.LAX-backend implementation of conjugate() . Original docstring below.conjugate(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj])The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Returns y – The complex conjugate of x , with same dtype as y . This is a scalar if x is a scalar. Return type ndarray
Notes conj is an alias for conjugate : >>> np.conj is np.conjugateTrue Examples >>> np.conjugate(1+2j)(1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x)array([[ 1.-1.j, 0.-0.j],[ 0.-0.j, 1.-1.j]]) corrcoef ( x , y=None , rowvar=True ) Return Pearson product-moment correlation coefficients.LAX-backend implementation of corrcoef() . ADDITIONOriginal docstring below.LAX-backend implementation of corrcoef() . Original docstring below.Please refer to the documentation for cov for more detail. The relationship between the correlation coefficientmatrix, R , and the covariance matrix, C , is 𝑅 𝑖𝑗 = 𝐶 𝑖𝑗 √︀ 𝐶 𝑖𝑖 * 𝐶 𝑗𝑗 The values of R are between -1 and 1, inclusive. Returns R – The correlation coefficient matrix of the variables.
Return type ndarray
See also: cov()
Covariance matrix
Notes
Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1,and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to theinterval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case.This function accepts but discards arguments bias and ddof . This is for backwards compatibility with previousversions of this function. These arguments had no effect on the return values of the function and can be safelyignored in this and previous versions of numpy.
48 Chapter 2. APIymjax, Release 0.0.1 cos ( x ) Cosine element-wise.LAX-backend implementation of cos() . ADDITIONOriginal docstring below.LAX-backend implementation of cos() . Original docstring below.cos(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, ex-tobj]) Returns y – The corresponding cosine values. This is a scalar if x is a scalar. Return type ndarray
Notes If out is provided, the function writes the result into it, and returns a reference to out . (See Examples) References
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972.
Examples >>> np.cos(np.array([0, np.pi/2, np.pi]))array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])>>> >>> >>> out1 = np.array([0], dtype='d') >>> out2 = np.cos([0.1], out1) >>> out2 is out1True>>> >>> >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))Traceback (most recent call last):File "
The hyperbolic cosine describes the shape of a hanging cable: >>> import matplotlib.pyplot as plt>>> x = np.linspace(-4, 4, 1000) >>> plt.plot(x, np.cosh(x)) >>> plt.show() count_nonzero ( a , axis=None ) Counts the number of non-zero values in the array a .LAX-backend implementation of count_nonzero() . ADDITIONOriginal docstring below.LAX-backend implementation of count_nonzero() . Original docstring below.The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any num-ber is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the emptystring. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True . Returns count – Number of non-zero values in the array along a given axis. Otherwise, the totalnumber of non-zero values in the array is returned.
Return type int or array of int
See also: nonzero()
Return the coordinates of all the non-zero values.
Examples >>> np.count_nonzero(np.eye(4))4 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])5 >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=0)array([1, 1, 1, 1, 1]) >>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]], axis=1)array([2, 3]) cov ( m , y=None , rowvar=True , bias=False , ddof=None , fweights=None , aweights=None ) Estimate a covariance matrix, given data and weights.LAX-backend implementation of cov() . ADDITIONOriginal docstring below.LAX-backend implementation of cov() . Original docstring below.Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, 𝑋 = [ 𝑥 , 𝑥 , ...𝑥 𝑁 ] 𝑇 , then the covariance matrix element 𝐶 𝑖𝑗 is the covariance of 𝑥 𝑖 and 𝑥 𝑗 . The element 𝐶 𝑖𝑖 is the variance of 𝑥 𝑖 .See the notes for an outline of the algorithm. Returns out – The covariance matrix of the variables.
50 Chapter 2. APIymjax, Release 0.0.1
Return type ndarray
See also: corrcoef()
Normalized covariance matrix
Notes
Assume that the observations are in the columns of the observation array m and let f = fweights and a =aweights for brevity. The steps to compute the weighted covariance are as follows: >>> m = np.arange(10, dtype=np.float64) >>> f = np.arange(10) * 2 >>> a = np.arange(10) ** 2. >>> ddof = 1 >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis= None , keepdims=
True ) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when a == 1 , the normalization factor v1 / (v1**2 - ddof * v2) goes over to as it should.
Examples
Consider two variables, 𝑥 and 𝑥 , which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> xarray([[0, 1, 2],[2, 1, 0]]) Note how 𝑥 increases while 𝑥 decreases. The covariance matrix shows this clearly: >>> np.cov(x)array([[ 1., -1.],[-1., 1.]]) Note that element 𝐶 , , which shows the correlation between 𝑥 and 𝑥 , is negative.Further, note how x and y are combined: >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.stack((x, y), axis=0) >>> np.cov(X)array([[11.71 , -4.286 ], >>> np.cov(x, y)array([[11.71 , -4.286 ], >>> np.cov(x)array(11.71) cross ( a , b , axisa=- 1 , axisb=- 1 , axisc=- 1 , axis=None ) Return the cross product of two (arrays of) vectors.
LAX-backend implementation of cross() . ADDITIONOriginal docstring below.LAX-backend implementation of cross() . Original docstring below.The cross product of a and b in 𝑅 is a vector perpendicular to both a and b . If a and b are arrays of vectors,the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Wherethe dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the crossproduct calculated accordingly. In cases where both input vectors have dimension 2, the z-component of thecross product is returned. Returns c – Vector cross product(s).
Return type ndarray
Raises
ValueError – When the dimension of the vector(s) in a and/or b does not equal 2 or 3. See also: inner()
Inner product outer()
Outer product. ix_()
Construct index arrays.
Notes
New in version 1.9.0.Supports full broadcasting of the inputs.
Examples
Vector cross-product. >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> np.cross(x, y)array([-3, 6, -3])
One vector with dimension 2. >>> x = [1, 2] >>> y = [4, 5, 6] >>> np.cross(x, y)array([12, -6, -3])
Equivalently: >>> x = [1, 2, 0] >>> y = [4, 5, 6] >>> np.cross(x, y)array([12, -6, -3])
Both vectors with dimension 2. >>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y)array(-3)
52 Chapter 2. APIymjax, Release 0.0.1
Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-handrule . >>> x = np.array([[1,2,3], [4,5,6]]) >>> y = np.array([[4,5,6], [1,2,3]]) >>> np.cross(x, y)array([[-3, 6, -3],[ 3, -6, 3]]) The orientation of c can be changed using the axisc keyword. >>> np.cross(x, y, axisc=0)array([[-3, 3],[ 6, -6],[-3, 3]]) Change the vector definition of x and y using axisa and axisb . >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) >>> np.cross(x, y)array([[ -6, 12, -6],[ 0, 0, 0],[ 6, -12, 6]]) >>> np.cross(x, y, axisa=0, axisb=0)array([[-24, 48, -24],[-30, 60, -30],[-36, 72, -36]]) cumsum ( a , axis=None , dtype=None ) Return the cumulative sum of the elements along a given axis.LAX-backend implementation of cumsum() . ADDITIONOriginal docstring below.LAX-backend implementation of cumsum() . Original docstring below.
Parameters dtype ( dtype, optional ) – Type of the returned array and of the accumulator inwhich the elements are summed. If dtype is not specified, it defaults to the dtype of a , unless a has an integer dtype with a precision less than that of the default platform integer. In that case,the default platform integer is used. Returns cumsum_along_axis – A new array holding the result is returned unless out is specified, inwhich case a reference to out is returned. The result has the same size as a , and the same shapeas a if axis is not None or a is a 1-d array. Return type ndarray.
See also: sum()
Sum array elements. trapz()
Integration of array values using the composite trapezoidal rule. diff()
Calculate the n-th discrete difference along given axis.
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples >>> a = np.array([[1,2,3], [4,5,6]]) >>> aarray([[1, 2, 3],[4, 5, 6]]) >>> np.cumsum(a)array([ 1, 3, 6, 10, 15, 21]) >>> np.cumsum(a, dtype=float) array([ 1., 3., 6., 10., 15., 21.]) >>> np.cumsum(a,axis=0) array([[1, 2, 3],[5, 7, 9]]) >>> np.cumsum(a,axis=1) array([[ 1, 3, 6],[ 4, 9, 15]]) cumprod ( a , axis=None , dtype=None ) Return the cumulative product of elements along a given axis.LAX-backend implementation of cumprod() . ADDITIONOriginal docstring below.LAX-backend implementation of cumprod() . Original docstring below.
Parameters dtype ( dtype, optional ) – Type of the returned array, as well as of the accumu-lator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a ,unless a has an integer dtype with a precision less than that of the default platform integer. Inthat case, the default platform integer is used instead. Returns cumprod – A new array holding the result is returned unless out is specified, in which casea reference to out is returned.
Return type ndarray
See also: ufuncs-output-type()
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
54 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.array([1,2,3]) >>> np.cumprod(a) ... array([1, 2, 6]) >>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.cumprod(a, dtype=float) array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows) of a : >>> np.cumprod(a, axis=0)array([[ 1, 2, 3],[ 4, 10, 18]]) The cumulative product for each row (i.e. over the columns) of a : >>> np.cumprod(a,axis=1)array([[ 1, 2, 6],[ 4, 20, 120]]) cumproduct ( a , axis=None , dtype=None ) Return the cumulative product of elements along a given axis.LAX-backend implementation of cumprod() . ADDITIONOriginal docstring below.LAX-backend implementation of cumprod() . Original docstring below.
Parameters dtype ( dtype, optional ) – Type of the returned array, as well as of the accumu-lator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a ,unless a has an integer dtype with a precision less than that of the default platform integer. Inthat case, the default platform integer is used instead. Returns cumprod – A new array holding the result is returned unless out is specified, in which casea reference to out is returned.
Return type ndarray
See also: ufuncs-output-type()
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples >>> a = np.array([1,2,3]) >>> np.cumprod(a) ... array([1, 2, 6]) >>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.cumprod(a, dtype=float) array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows) of a : >>> np.cumprod(a, axis=0)array([[ 1, 2, 3],[ 4, 10, 18]]) The cumulative product for each row (i.e. over the columns) of a : >>> np.cumprod(a,axis=1)array([[ 1, 2, 6],[ 4, 20, 120]]) deg2rad ( x ) Convert angles from degrees to radians.LAX-backend implementation of deg2rad() . ADDITIONOriginal docstring below.LAX-backend implementation of deg2rad() . Original docstring below.deg2rad(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The corresponding angle in radians. This is a scalar if x is a scalar. Return type ndarray
See also: rad2deg()
Convert angles from radians to degrees. unwrap()
Remove large jumps in angle by wrapping.
Notes
New in version 1.3.0. deg2rad(x) is x * pi / 180 . Examples >>> np.deg2rad(180)3.1415926535897931 degrees ( x ) Convert angles from radians to degrees.LAX-backend implementation of rad2deg() . ADDITIONOriginal docstring below.LAX-backend implementation of rad2deg() . Original docstring below.rad2deg(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The corresponding angle in degrees. This is a scalar if x is a scalar. Return type ndarray
See also: deg2rad()
Convert angles from degrees to radians. unwrap()
Remove large jumps in angle by wrapping.
56 Chapter 2. APIymjax, Release 0.0.1Notes
New in version 1.3.0.rad2deg(x) is
180 * x / pi . Examples >>> np.rad2deg(np.pi/2)90.0 diag ( v , k=0 ) Extract a diagonal or construct a diagonal array.LAX-backend implementation of diag() . ADDITIONOriginal docstring below.LAX-backend implementation of diag() . Original docstring below.See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal andwish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy youare using.
Returns out – The extracted diagonal or constructed diagonal array.
Return type ndarray
See also: diagonal()
Return specified diagonals. diagflat()
Create a 2-D array with the flattened input as a diagonal. trace()
Sum along diagonals. triu()
Upper triangle of an array. tril()
Lower triangle of an array.
Examples >>> x = np.arange(9).reshape((3,3)) >>> xarray([[0, 1, 2],[3, 4, 5],[6, 7, 8]]) >>> np.diag(x)array([0, 4, 8]) >>> np.diag(x, k=1)array([1, 5]) >>> np.diag(x, k=-1)array([3, 7]) >>> np.diag(np.diag(x))array([[0, 0, 0],[0, 4, 0],[0, 0, 8]]) diag_indices ( n , ndim=2 ) Return the indices to access the main diagonal of an array.LAX-backend implementation of diag_indices() . ADDITIONOriginal docstring below.LAX-backend implementation of diag_indices() . Original docstring below.This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, . . . , n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is theset of indices to access a[i, i, ..., i] for i = [0..n-1] . Parameters ) – diagonal ( a , offset=0 , axis1=0 , axis2=1 ) Return specified diagonals.LAX-backend implementation of diagonal() . ADDITIONOriginal docstring below.LAX-backend implementation of diagonal() . Original docstring below.If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i,i+offset] . If a has more than two dimensions, then the axes specified by axis1 and axis2 are used todetermine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined byremoving axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy ofthe values in the diagonal.In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated.Writing to the resulting array continues to work as it used to, but a FutureWarning is issued.Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resultingarray will produce an error.In some future release, it will return a read/write view and writing to the returned array will alter your originalarray. The returned array will have the same type as the input array.If you don’t write to the array returned by this function, then you can just ignore all of the above.If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a) . This will work with both past and future ver-sions of NumPy. Returnsarray_of_diagonals – If a is 2-D, then a 1-D array containing the diagonal and of the same typeas a is returned unless a is a matrix , in which case a 1-D array rather than a (2-D) matrix isreturned in order to maintain backward compatibility.If a.ndim > 2 , then the dimensions specified by axis1 and axis2 are removed, and a new axisinserted at the end corresponding to the diagonal. Return type ndarray
Raises
ValueError – If the dimension of a is less than 2. See also: diag()
MATLAB work-a-like for 1-D and 2-D arrays. diagflat()
Create diagonal arrays. trace()
Sum along diagonals.
58 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.arange(4).reshape(2,2) >>> aarray([[0, 1],[2, 3]]) >>> a.diagonal()array([0, 3]) >>> a.diagonal(1)array([1])
A 3-D example: >>> a = np.arange(8).reshape(2,2,2); aarray([[[0, 1],[2, 3]],[[4, 5],[6, 7]]]) >>> a.diagonal(0, ... ... array([[0, 6],[1, 7]]) The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most(column) axis, and that the diagonals are “packed” in rows. >>> a[:,:,0] array([[0, 2],[4, 6]]) >>> a[:,:,1] array([[1, 3],[5, 7]])
The anti-diagonal can be obtained by reversing the order of elements using either numpy.flipud or numpy.fliplr . >>> a = np.arange(9).reshape(3, 3) >>> aarray([[0, 1, 2],[3, 4, 5],[6, 7, 8]]) >>> np.fliplr(a).diagonal() array([2, 4, 6]) >>> np.flipud(a).diagonal() array([6, 4, 2]) Note that the order in which the diagonal is retrieved varies depending on the flip function. divide ( x1 , x2 ) Returns a true division of the inputs, element-wise.LAX-backend implementation of true_divide() . ADDITIONOriginal docstring below.LAX-backend implementation of true_divide() . Original docstring below.true_divide(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Instead of the Python traditional ‘floor division’, this returns a true division. True division adjusts the outputtype to present the best answer, regardless of input types. Returns out – This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
Notes
The floor division operator // was added in Python 2.2 making // and / equivalent operators. The default floordivision operation of / can be replaced by true division with from __future__ import division .In Python 3.0, // is the floor division operator and / the true division operator. The true_divide(x1,x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5) >>> np.true_divide(x, 4)array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4array([0, 0, 0, 0, 1]) >>> from __future__ import division >>> x/4array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4array([0, 0, 0, 0, 1]) divmod ( x1 , x2 ) Return element-wise quotient and remainder simultaneously.LAX-backend implementation of divmod() . ADDITIONOriginal docstring below.LAX-backend implementation of divmod() . Original docstring below.divmod(x1, x2[, out1, out2], / [, out=(None, None)], * , where=True, casting=’same_kind’, order=’K’,dtype=None, subok=True[, signature, extobj])New in version 1.13.0. np.divmod(x, y) is equivalent to (x // y, x % y) , but faster because it avoids redundant work. It isused to implement the Python built-in function divmod on NumPy arrays. Returns • out1 ( ndarray ) – Element-wise quotient resulting from floor division. This is a scalar if both x1 and x2 are scalars.• out2 ( ndarray ) – Element-wise remainder from floor division. This is a scalar if both x1 and x2 are scalars. See also: floor_divide()
Equivalent to Python’s // operator. remainder() Equivalent to Python’s % operator. modf() Equivalent to divmod(x, 1) for positive x with the return values switched.
60 Chapter 2. APIymjax, Release 0.0.1Examples >>> np.divmod(np.arange(5), 3)(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1])) dot ( a , b , precision=None ) Dot product of two arrays. Specifically,LAX-backend implementation of dot() . ADDITIONOriginal docstring below.LAX-backend implementation of dot() . In addition to the original NumPy arguments listed below, alsosupports precision for extra control over matrix-multiplication precision on supported devices. See jax.lax.dot() for details.Original docstring below.dot(a, b, out=None)• If both a and b are 1-D arrays, it is inner product of vectors (without complex conjuga-tion).• If both a and b are 2-D arrays, it is matrix multiplication, but using matmul() or a @b is preferred.• If either a or b is 0-D (scalar), it is equivalent to multiply() and using numpy.multiply(a, b) or a * b is preferred.• If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b .• If a is an N-D array and b is an M-D array (where M>=2 ), it is a sum product over thelast axis of a and the second-to-last axis of b : dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) Returnsoutput [ndarray] Returns the dot product of a and b . If a and b are both scalars or both 1-Darrays then a scalar is returned; otherwise an array is returned. If out is given, then it isreturned. ValueError
If the last dimension of a is not the same size as the second-to-last dimension of b .vdot : Complex-conjugating dot product. tensordot : Sum products over arbitrary axes. einsum: Einstein summation convention. matmul : ‘@’ operator as method with out parameter. >>> np.dot(3, 4)12 Neither argument is complex-conjugated: >>> np.dot([2j, 3j], [2j, 3j])(-13+0j)
For 2-D arrays it is the matrix product: >>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.dot(a, b) (continues on next page) (continued from previous page) array([[4, 1],[2, 2]]) >>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) >>> np.dot(a, b)[2,3,2,1,2,2]499128 >>> sum(a[2,3,2,:] * b[1,2,:,2])499128 dsplit ( ary , indices_or_sections ) Split array into multiple sub-arrays along the 3rd axis (depth).LAX-backend implementation of dsplit() . ADDITIONOriginal docstring below.LA dstack ( tup ) Stack arrays in sequence depth wise (along third axis).LAX-backend implementation of dstack() . ADDITIONOriginal docstring below.LAX-backend implementation of dstack() . Original docstring below.This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1) . Rebuilds arrays divided by dsplit .This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height(first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate , stack and block provide more general stacking and concatenation operations. Returns stacked – The array formed by stacking the given arrays, will be at least 3-D.
Return type ndarray
See also: stack()
Join a sequence of arrays along a new axis. vstack()
Stack along first axis. hstack()
Stack along second axis. concatenate()
Join a sequence of arrays along an existing axis. dsplit()
Split array along third axis.
Examples >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.dstack((a,b))array([[[1, 2],[2, 3],[3, 4]]])
62 Chapter 2. APIymjax, Release 0.0.1 >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.dstack((a,b))array([[[1, 2]],[[2, 3]],[[3, 4]]]) einsum ( *operands , **kwargs ) Evaluates the Einstein summation convention on the operands.LAX-backend implementation of einsum() . ADDITIONOriginal docstring below.LAX-backend implementation of einsum() . In addition to the original NumPy arguments listed below, alsosupports precision for extra control over matrix-multiplication precision on supported devices. See jax.lax.dot() for details.Original docstring below. einsum(subscripts, *operands, out=None, dtype=None, order=’K’, casting=’safe’, op-timize=False)Using the Einstein summation convention, many common multi-dimensional, linear alge-braic array operations can be represented in a simple fashion. In implicit mode einsum computes these values.In explicit mode, einsum provides further flexibility to compute other array operations thatmight not be considered classical Einstein summation operations, by disabling, or forcingsummation over specified subscript labels.See the notes and examples for clarification.
Returnsoutput [ndarray] The calculation based on the Einstein summation convention.einsum_path, dot, inner, outer, tensordot, linalg.multi_dotNew in version 1.6.0.The Einstein summation convention can be used to compute many multi-dimensional, linearalgebraic array operations. einsum provides a succinct way of representing these.A non-exhaustive list of these operations, which can be computed by einsum , is shown belowalong with examples:• Trace of an array, numpy.trace() .• Return a diagonal, numpy.diag() .• Array axis summations, numpy.sum() .• Transpositions and permutations, numpy.transpose() .• Matrix multiplication and dot product, numpy.matmul() numpy.dot() .• Vector inner and outer products, numpy.inner() numpy.outer() .• Broadcasting, element-wise and scalar multiplication, numpy.multiply() .• Tensor contractions, numpy.tensordot() .• Chained array operations, in efficient calculation order, numpy.einsum_path() . The subscripts string is a comma-separated list of subscript labels, where each label refers to adimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b) . If a label appears only once,it is not summed, so np.einsum('i', a) produces a view of a with no changes. A furtherexample np.einsum('ij,jk', a, b) describes traditional matrix multiplication and isequivalent to np.matmul(a,b) . Repeated subscript labels in one operand take the diagonal.For example, np.einsum('ii', a) is equivalent to np.trace(a) .In implicit mode , the chosen subscripts are important since the axes of the output are reorderedalphabetically. This means that np.einsum('ij', a) doesn’t affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) re-turns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transposeof the multiplication since subscript ‘h’ precedes subscript ‘i’.In explicit mode the output can be directly controlled by specifying output subscript labels. Thisrequires the identifier ‘->’ as well as the list of output subscript labels. This feature increasesthe flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1) , and np.einsum('ii->i',a) is like np.diag(a) . The difference is that einsum does not allow broadcasting by default.Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the outputsubscript labels and therefore returns matrix multiplication, unlike the example above in implicitmode.To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is doneby adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a) . Totake the trace along the first and last axes, you can do np.einsum('i...i', a) , or todo a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b) .When there is only one operand, no axes are summed, and no output parameter is provided,a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view (changed in version 1.10.0). einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]) . If the out-put shape is not provided in this format einsum will be calculated in implicit mode, otherwise itwill be performed explicitly. The examples below have corresponding einsum calls with the twoparameter methods.New in version 1.10.0.Views returned from einsum are now writeable whenever the input array is writeable. Forexample, np.einsum('ijk...->kji...', a) will now have the same effect as np.swapaxes(a, 0, 2) and np.einsum('ii->i', a) will return a writeable view ofthe diagonal of a 2D array.New in version 1.12.0.Added the optimize argument which will optimize the contraction order of an einsum expres-sion. For a contraction with three or more operands this can greatly increase the computationalefficiency at the cost of a larger memory footprint during computation.Typically a ‘greedy’ algorithm is applied which empirical tests have shown returns the optimalpath in the majority of cases. In some cases ‘optimal’ will return the superlative path througha more expensive, exhaustive search. For iterative calculations it may be advisable to calculatethe optimal path once and reuse that path by supplying it as an argument. An example is givenbelow.See numpy.einsum_path() for more details.
64 Chapter 2. APIymjax, Release 0.0.1 >>> a = np.arange(25).reshape(5,5) >>> b = np.arange(5) >>> c = np.arange(6).reshape(2,3)
Trace of a matrix: >>> np.einsum('ii', a)60 >>> np.einsum(a, [0,0])60 >>> np.trace(a)60
Extract the diagonal (requires explicit form): >>> np.einsum('ii->i', a)array([ 0, 6, 12, 18, 24]) >>> np.einsum(a, [0,0], [0])array([ 0, 6, 12, 18, 24]) >>> np.diag(a)array([ 0, 6, 12, 18, 24])
Sum over an axis (requires explicit form): >>> np.einsum('ij->i', a)array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [0,1], [0])array([ 10, 35, 60, 85, 110]) >>> np.sum(a, axis=1)array([ 10, 35, 60, 85, 110])
For higher dimensional arrays summing a single axis can be done with ellipsis: >>> np.einsum('...j->...', a)array([ 10, 35, 60, 85, 110]) >>> np.einsum(a, [Ellipsis,1], [Ellipsis])array([ 10, 35, 60, 85, 110])
Compute a matrix transpose, or reorder any number of axes: >>> np.einsum('ji', c)array([[0, 3],[1, 4],[2, 5]]) >>> np.einsum('ij->ji', c)array([[0, 3],[1, 4],[2, 5]]) >>> np.einsum(c, [1,0])array([[0, 3],[1, 4],[2, 5]]) >>> np.transpose(c)array([[0, 3],[1, 4],[2, 5]])
Vector inner products: >>> np.einsum('i,i', b, b)30 >>> np.einsum(b, [0], b, [0])30 >>> np.inner(b,b)30
Matrix vector multiplication: >>> np.einsum('ij,j', a, b)array([ 30, 80, 130, 180, 230]) >>> np.einsum(a, [0,1], b, [1])array([ 30, 80, 130, 180, 230]) >>> np.dot(a, b)array([ 30, 80, 130, 180, 230]) >>> np.einsum('...j,j', a, b)array([ 30, 80, 130, 180, 230])
Broadcasting and scalar multiplication: >>> np.einsum('..., ...', 3, c)array([[ 0, 3, 6],[ 9, 12, 15]]) >>> np.einsum(',ij', 3, c)array([[ 0, 3, 6],[ 9, 12, 15]]) >>> np.einsum(3, [Ellipsis], c, [Ellipsis])array([[ 0, 3, 6],[ 9, 12, 15]]) >>> np.multiply(3, c)array([[ 0, 3, 6],[ 9, 12, 15]])
Vector outer product: >>> np.einsum('i,j', np.arange(2)+1, b)array([[0, 1, 2, 3, 4],[0, 2, 4, 6, 8]]) >>> np.einsum(np.arange(2)+1, [0], b, [1])array([[0, 1, 2, 3, 4],[0, 2, 4, 6, 8]]) >>> np.outer(np.arange(2)+1, b)array([[0, 1, 2, 3, 4],[0, 2, 4, 6, 8]])
Tensor contraction: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> np.einsum('ijk,jil->kl', a, b)array([[4400., 4730.],[4532., 4874.],[4664., 5018.],[4796., 5162.],[4928., 5306.]]) >>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])array([[4400., 4730.], (continues on next page)
66 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) [4532., 4874.],[4664., 5018.],[4796., 5162.],[4928., 5306.]]) >>> np.tensordot(a,b, axes=([1,0],[0,1]))array([[4400., 4730.],[4532., 4874.],[4664., 5018.],[4796., 5162.],[4928., 5306.]])
Writeable returned arrays (since version 1.10.0): >>> a = np.zeros((3, 3)) >>> np.einsum('ii->i', a)[:] = 1 >>> aarray([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]])
Example of ellipsis use: >>> a = np.arange(6).reshape((3,2)) >>> b = np.arange(12).reshape((4,3)) >>> np.einsum('ki,jk->ij', a, b)array([[10, 28, 46, 64],[13, 40, 67, 94]]) >>> np.einsum('ki,...k->i...', a, b)array([[10, 28, 46, 64],[13, 40, 67, 94]]) >>> np.einsum('k...,jk', a, b)array([[10, 28, 46, 64],[13, 40, 67, 94]])
Chained array operations. For more complicated contractions, speed ups might be achievedby repeatedly computing a ‘greedy’ path or pre-computing the ‘optimal’ path and repeatedlyapplying it, using an einsum_path insertion (since version 1.12.0). Performance improvementscan be particularly significant with larger arrays: >>> a = np.ones(64).reshape(2,4,8)
Basic einsum : ~1520ms (benchmarked on 3.1GHz Intel i5.) >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a) Sub-optimal einsum (due to repeated path calculation time): ~330ms >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize= ˓ → 'optimal') Greedy einsum (faster optimal path approximation): ~160ms >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize= ˓ → 'greedy') Optimal einsum (best usage pattern in some use cases): ~110ms >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize= ˓ → 'optimal')[0] >>> for iteration in range(500): ... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, ˓ → optimize=path) equal ( x1 , x2 ) Return (x1 == x2) element-wise.LAX-backend implementation of equal() . ADDITIONOriginal docstring below.LAX-backend implementation of equal() . Original docstring below.equal(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj]) Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar
See also: not_equal() , greater_equal() , less_equal() , greater() , less() Examples >>> np.equal([0, 1, 3], np.arange(3))array([ True, True, False])
What is compared are values, not types. So an int (1) and an array of length one can evaluate as True: >>> np.equal(1, np.ones(1))array([ True]) empty ( shape , dtype=None ) Return a new array of given shape and type, filled with zeros.LAX-backend implementation of zeros() . ADDITIONOriginal docstring below.LAX-backend implementation of zeros() . Original docstring below.zeros(shape, dtype=float, order=’C’)
Returnsout [ndarray] Array of zeros with the given shape, dtype, and order.zeros_like : Return an array of zeros with shape and type of input. empty : Return a newuninitialized array. ones : Return a new array setting values to one. full : Return a new array ofgiven shape filled with value. >>> np.zeros(5)array([ 0., 0., 0., 0., 0.])
68 Chapter 2. APIymjax, Release 0.0.1 >>> np.zeros((5,), dtype=int)array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1))array([[ 0.],[ 0.]]) >>> s = (2,2) >>> np.zeros(s)array([[ 0., 0.],[ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) array([(0, 0), (0, 0)],dtype=[('x', ' Parameters dtype ( data-type, optional ) – Overrides the data type of the result. Returns out – Array of zeros with the same shape and type as a . Return type ndarray See also: empty_like() Return an empty array with shape and type of input. ones_like() Return an array of ones with shape and type of input. full_like() Return a new array with shape of input filled with value. zeros() Return a new array setting values to zero. Examples >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> xarray([[0, 1, 2],[3, 4, 5]]) >>> np.zeros_like(x)array([[0, 0, 0],[0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> yarray([0., 1., 2.]) >>> np.zeros_like(y)array([0., 0., 0.]) exp ( x ) Calculate the exponential of all elements in the input array.LAX-backend implementation of exp() . ADDITIONOriginal docstring below.LAX-backend implementation of exp() . Original docstring below.exp(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, ex-tobj]) Returns out – Output array, element-wise exponential of x . This is a scalar if x is a scalar. Return type ndarray or scalar See also: expm1() Calculate exp(x) - 1 for all elements in the array. exp2() Calculate for all elements in the array. Notes The irrational number e is also known as Euler’s number. It is approximately 2.718281, and is the base of thenatural logarithm, ln (this means that, if 𝑥 = ln 𝑦 = log 𝑒 𝑦 , then 𝑒 𝑥 = 𝑦 . For real input, exp(x) is alwayspositive.For complex arguments, x = a + ib , we can write 𝑒 𝑥 = 𝑒 𝑎 𝑒 𝑖𝑏 . The first term, 𝑒 𝑎 , is already known (it isthe real argument, described above). The second term, 𝑒 𝑖𝑏 , is cos 𝑏 + 𝑖 sin 𝑏 , a function with magnitude 1 and aperiodic phase. ReferencesExamples Plot the magnitude and phase of exp(x) in the complex plane: >>> import matplotlib.pyplot as plt>>> x = np.linspace(-2*np.pi, 2*np.pi, 100) >>> xx = x + 1j * x[:, np.newaxis] >>> out = np.exp(xx) >>> plt.subplot(121) >>> plt.imshow(np.abs(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='gray') >>> plt.title('Magnitude of exp(x)') >>> plt.subplot(122) >>> plt.imshow(np.angle(out), ... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='hsv') >>> plt.title('Phase (angle) of exp(x)') >>> plt.show() exp2 ( x ) Calculate for all p in the input array.LAX-backend implementation of exp2() . ADDITIONOriginal docstring below. 70 Chapter 2. APIymjax, Release 0.0.1 LAX-backend implementation of exp2() . Original docstring below.exp2(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Element-wise 2 to the power x . This is a scalar if x is a scalar. Return type ndarray or scalar See also: power() Notes New in version 1.3.0. Examples >>> np.exp2([2, 3])array([ 4., 8.]) expand_dims ( a , axis ) Expand the shape of an array.LAX-backend implementation of expand_dims() . ADDITIONOriginal docstring below.LAX-backend implementation of expand_dims() . Original docstring below.Insert a new axis that will appear at the axis position in the expanded array shape. Returns result – View of a with the number of dimensions increased. Return type ndarray See also: squeeze() The inverse operation, removing singleton dimensions reshape() Insert, remove, and combine dimensions, and resize existing ones doc.indexing() , atleast_1d() , atleast_2d() , atleast_3d() Examples >>> x = np.array([1, 2]) >>> x.shape(2,) The following is equivalent to x[np.newaxis, :] or x[np.newaxis] : >>> y = np.expand_dims(x, axis=0) >>> yarray([[1, 2]]) >>> y.shape(1, 2) The following is equivalent to x[:, np.newaxis] : >>> y = np.expand_dims(x, axis=1) >>> yarray([[1],[2]]) >>> y.shape(2, 1) axis may also be a tuple: >>> y = np.expand_dims(x, axis=(0, 1)) >>> yarray([[[1, 2]]]) >>> y = np.expand_dims(x, axis=(2, 0)) >>> yarray([[[1],[2]]]) Note that some examples may use None instead of np.newaxis . These are the same objects: >>> np.newaxis is None True expm1 ( x ) Calculate exp(x) - 1 for all elements in the array.LAX-backend implementation of expm1() . ADDITIONOriginal docstring below.LAX-backend implementation of expm1() . Original docstring below.expm1(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Element-wise exponential minus one: out = exp(x) - 1 . This is a scalar if x isa scalar. Return type ndarray or scalar See also: log1p() log(1 + x) , the inverse of expm1. Notes This function provides greater precision than exp(x) - 1 for small values of x . Examples The true value of exp(1e-10) - 1 is to about 32 significant digits. This exampleshows the superiority of expm1 in this case. >>> np.expm1(1e-10)1.00000000005e-10 >>> np.exp(1e-10) - 11.000000082740371e-10 72 Chapter 2. APIymjax, Release 0.0.1 eye ( N , M=None , k=0 , dtype=None ) Return a 2-D array with ones on the diagonal and zeros elsewhere.LAX-backend implementation of eye() . ADDITIONOriginal docstring below.LAX-backend implementation of eye() . Original docstring below. Parameters dtype ( data-type, optional ) – Returns I – An array where all elements are equal to zero, except for the k -th diagonal, whose valuesare equal to one. Return type ndarray of shape (N,M) See also: identity() (almost) equivalent function diag() diagonal 2-D array from a 1-D array specified by the user. Examples >>> np.eye(2, dtype=int)array([[1, 0],[0, 1]]) >>> np.eye(3, k=1)array([[0., 1., 0.],[0., 0., 1.],[0., 0., 0.]]) fabs ( x ) Compute the absolute values element-wise.LAX-backend implementation of fabs() . ADDITIONOriginal docstring below.LAX-backend implementation of fabs() . Original docstring below.fabs(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])This function returns the absolute values (positive magnitude) of the data in x . Complex values are not handled,use absolute to find the absolute values of complex data. Returns y – The absolute values of x , the returned values are always floats. This is a scalar if x is ascalar. Return type ndarray or scalar See also: absolute() Absolute values including complex types. >>> np.fabs(-1)1.0 >>> np.fabs([-1.2, 1.2])array([ 1.2, 1.2]) flip ( m , axis=None ) Reverse the order of elements in an array along the given axis.LAX-backend implementation of flip() . ADDITIONOriginal docstring below.LAX-backend implementation of flip() . Original docstring below.The shape of the array is preserved, but the elements are reordered.New in version 1.12.0. Returns out – A view of m with the entries of axis reversed. Since a view is returned, this operationis done in constant time. Return type array_like See also: flipud() Flip an array vertically (axis=0). fliplr() Flip an array horizontally (axis=1). Notes flip(m, 0) is equivalent to flipud(m).flip(m, 1) is equivalent to fliplr(m).flip(m, n) corresponds to m[...,::-1,...] with ::-1 at position n.flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions.flip(m, (0, 1)) corresponds to m[::-1,::-1,...] with ::-1 at position 0 and position 1. Examples >>> A = np.arange(8).reshape((2,2,2)) >>> Aarray([[[0, 1],[2, 3]],[[4, 5],[6, 7]]]) >>> np.flip(A, 0)array([[[4, 5],[6, 7]],[[0, 1],[2, 3]]]) >>> np.flip(A, 1)array([[[2, 3],[0, 1]],[[6, 7],[4, 5]]]) (continues on next page) 74 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) >>> np.flip(A)array([[[7, 6],[5, 4]],[[3, 2],[1, 0]]]) >>> np.flip(A, (0, 2))array([[[5, 4],[7, 6]],[[1, 0],[3, 2]]]) >>> A = np.random.randn(3,4,5) >>> np.all(np.flip(A,2) == A[:,:,::-1,...])True fliplr ( m ) Flip array in the left/right direction.LAX-backend implementation of fliplr() . ADDITIONOriginal docstring below.LAX-backend implementation of fliplr() . Original docstring below.Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different orderthan before. Returns f – A view of m with the columns reversed. Since a view is returned, this operation is 𝒪 (1) . Return type ndarray See also: flipud() Flip array in the up/down direction. rot90() Rotate array counterclockwise. Notes Equivalent to m[:,::-1]. Requires the array to be at least 2-D. Examples >>> A = np.diag([1.,2.,3.]) >>> Aarray([[1., 0., 0.],[0., 2., 0.],[0., 0., 3.]]) >>> np.fliplr(A)array([[0., 0., 1.],[0., 2., 0.],[3., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.fliplr(A) == A[:,::-1,...])True flipud ( m ) Flip array in the up/down direction. LAX-backend implementation of flipud() . ADDITIONOriginal docstring below.LAX-backend implementation of flipud() . Original docstring below.Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different orderthan before. Returns out – A view of m with the rows reversed. Since a view is returned, this operation is 𝒪 (1) . Return type array_like See also: fliplr() Flip array in the left/right direction. rot90() Rotate array counterclockwise. Notes Equivalent to m[::-1,...] . Does not require the array to be two-dimensional. Examples >>> A = np.diag([1.0, 2, 3]) >>> Aarray([[1., 0., 0.],[0., 2., 0.],[0., 0., 3.]]) >>> np.flipud(A)array([[0., 0., 3.],[0., 2., 0.],[1., 0., 0.]]) >>> A = np.random.randn(2,3,5) >>> np.all(np.flipud(A) == A[::-1,...])True >>> np.flipud([1,2])array([2, 1]) float_power ( x1 , x2 ) First array elements raised to powers from second array, element-wise.LAX-backend implementation of float_power() . ADDITIONOriginal docstring below.LAX-backend implementation of float_power() . Original docstring below.float_power(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Raise each base in x1 to the positionally-corresponding power in x2 . x1 and x2 must be broadcastable to thesame shape. This differs from the power function in that integers, float16, and float32 are promoted to floatswith a minimum precision of float64 so that the result is always inexact. The intent is that the function willreturn a usable result for negative powers and seldom overflow for positive powers.New in version 1.12.0. Returns y – The bases in x1 raised to the exponents in x2 . This is a scalar if both x1 and x2 arescalars. 76 Chapter 2. APIymjax, Release 0.0.1 Return type ndarray See also: power() power function that preserves type Examples Cube each element in a list. >>> x1 = range(6) >>> x1[0, 1, 2, 3, 4, 5] >>> np.float_power(x1, 3)array([ 0., 1., 8., 27., 64., 125.]) Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.float_power(x1, x2)array([ 0., 1., 8., 27., 16., 5.]) The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2array([[1, 2, 3, 3, 2, 1],[1, 2, 3, 3, 2, 1]]) >>> np.float_power(x1, x2)array([[ 0., 1., 8., 27., 16., 5.],[ 0., 1., 8., 27., 16., 5.]]) floor ( x ) Return the floor of the input, element-wise.LAX-backend implementation of floor() . ADDITIONOriginal docstring below.LAX-backend implementation of floor() . Original docstring below.floor(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])The floor of the scalar x is the largest integer i , such that i <= x . It is often denoted as ⌊ 𝑥 ⌋ . Returns y – The floor of each element in x . This is a scalar if x is a scalar. Return type ndarray or scalar See also: ceil() , trunc() , rint() Some spreadsheet programs calculate the “floor-towards-zero”, in other words floor(-2.5) == -2 .NumPy instead uses the definition of floor where floor(-2.5) == -3 . Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.floor(a)array([-2., -2., -1., 0., 1., 1., 2.]) floor_divide ( x1 , x2 ) Return the largest integer smaller or equal to the division of the inputs. It is equivalent to the Python // operatorand pairs with the Python % ( remainder ), function so that a = a % b + b * (a // b) up to roundoff.LAX-backend implementation of floor_divide() . ADDITIONOriginal docstring below.LAX-backend implementation of floor_divide() . Original docstring below.floor_divide(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns y – y = floor( x1 / x2 ) This is a scalar if both x1 and x2 are scalars. Return type ndarray See also: remainder() Remainder complementary to floor_divide. divmod() Simultaneous floor division and remainder. divide() Standard division. floor() Round a number to the nearest integer toward minus infinity. ceil() Round a number to the nearest integer toward infinity. Examples >>> np.floor_divide(7,3)2 >>> np.floor_divide([1., 2., 3., 4.], 2.5)array([ 0., 0., 1., 1.]) fmod ( x1 , x2 ) Return the element-wise remainder of division.LAX-backend implementation of fmod() . ADDITIONOriginal docstring below.LAX-backend implementation of fmod() . Original docstring below.fmod(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj])This is the NumPy implementation of the C library function fmod, the remainder has the same sign as thedividend x1 . It is equivalent to the Matlab(TM) rem function and should not be confused with the Pythonmodulus operator x1 % x2 . Returns y – The remainder of the division of x1 by x2 . This is a scalar if both x1 and x2 are scalars. 78 Chapter 2. APIymjax, Release 0.0.1 Return type array_like See also: remainder() Equivalent to the Python % operator. divide() Notes The result of the modulo operation for negative dividend and divisors is bound by conventions. For fmod , thesign of result is the sign of the dividend, while for remainder the sign of the result is the sign of the divisor. The fmod function is equivalent to the Matlab(TM) rem function. Examples >>> np.fmod([-3, -2, -1, 1, 2, 3], 2)array([-1, 0, -1, 1, 0, 1]) >>> np.remainder([-3, -2, -1, 1, 2, 3], 2)array([1, 0, 1, 1, 0, 1]) >>> np.fmod([5, 3], [2, 2.])array([ 1., 1.]) >>> a = np.arange(-3, 3).reshape(3, 2) >>> aarray([[-3, -2],[-1, 0],[ 1, 2]]) >>> np.fmod(a, [2,2])array([[-1, 0],[-1, 0],[ 1, 0]]) full ( shape , fill_value , dtype=None ) Return a new array of given shape and type, filled with fill_value .LAX-backend implementation of full() . ADDITIONOriginal docstring below.LAX-backend implementation of full() . Original docstring below. Parameters • shape ( int or sequence of ints ) – Shape of the new array, e.g., (2, 3) or .• dtype ( data-type, optional ) – The desired data-type for the array The default, None, means np.array(fill_value).dtype . Returns out – Array of fill_value with the given shape, dtype, and order. Return type ndarray See also: full_like() Return a new array with shape of input filled with value. empty() Return a new uninitialized array. ones() Return a new array setting values to one. zeros() Return a new array setting values to zero. Examples >>> np.full((2, 2), np.inf)array([[inf, inf],[inf, inf]]) >>> np.full((2, 2), 10)array([[10, 10],[10, 10]]) full_like ( a , fill_value , dtype=None ) Return a full array with the same shape and type as a given array.LAX-backend implementation of full_like() . ADDITIONOriginal docstring below.LAX-backend implementation of full_like() . Original docstring below. Parameters dtype ( data-type, optional ) – Overrides the data type of the result. Returns out – Array of fill_value with the same shape and type as a . Return type ndarray See also: empty_like() Return an empty array with shape and type of input. ones_like() Return an array of ones with shape and type of input. zeros_like() Return an array of zeros with shape and type of input. full() Return a new array of given shape filled with value. Examples >>> x = np.arange(6, dtype=int) >>> np.full_like(x, 1)array([1, 1, 1, 1, 1, 1]) >>> np.full_like(x, 0.1)array([0, 0, 0, 0, 0, 0]) >>> np.full_like(x, 0.1, dtype=np.double)array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) >>> np.full_like(x, np.nan, dtype=np.double)array([nan, nan, nan, nan, nan, nan]) >>> y = np.arange(6, dtype=np.double) >>> np.full_like(y, 0.1)array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) gcd ( x1 , x2 ) Returns the greatest common divisor of |x1| and |x2| LAX-backend implementation of gcd() . ADDITIONOriginal docstring below.LAX-backend implementation of gcd() . Original docstring below. 80 Chapter 2. APIymjax, Release 0.0.1 gcd(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: lcm() The lowest common multiple Examples >>> np.gcd(12, 20)4 >>> np.gcd.reduce([15, 25, 35])5 >>> np.gcd(np.arange(6), 20)array([20, 1, 2, 1, 4, 5]) geomspace ( start , stop , num=50 , endpoint=True , dtype=None , axis=0 ) Return numbers spaced evenly on a log scale (a geometric progression).LAX-backend implementation of geomspace() . ADDITIONOriginal docstring below.LAX-backend implementation of geomspace() . Original docstring below.This is similar to logspace , but with endpoints specified directly. Each output sample is a constant multiple ofthe previous.Changed in version 1.16.0: Non-scalar start and stop are now supported. Parameters dtype ( dtype ) – The type of the output array. If dtype is not given, infer the datatype from the other input arguments. Returns samples – num samples, equally spaced on a log scale. Return type ndarray See also: logspace() Similar to geomspace, but with endpoints specified using log and base. linspace() Similar to geomspace, but with arithmetic instead of geometric progression. arange() Similar to linspace, with the step size specified instead of the number of samples. Notes If the inputs or dtype are complex, the output will follow a logarithmic spiral in the complex plane. (There arean infinite number of spirals passing through two points; the output will follow the shortest such path.) >>> np.geomspace(1, 1000, num=4)array([ 1., 10., 100., 1000.]) >>> np.geomspace(1, 1000, num=3, endpoint= False )array([ 1., 10., 100.]) >>> np.geomspace(1, 1000, num=4, endpoint= False )array([ 1. , 5.62341325, 31.6227766 , 177.827941 ]) >>> np.geomspace(1, 256, num=9)array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.]) Note that the above may not produce exact integers: >>> np.geomspace(1, 256, num=9, dtype=int)array([ 1, 2, 4, 7, 16, 32, 63, 127, 256]) >>> np.around(np.geomspace(1, 256, num=9)).astype(int)array([ 1, 2, 4, 8, 16, 32, 64, 128, 256]) Negative, decreasing, and complex inputs are allowed: >>> np.geomspace(1000, 1, num=4)array([1000., 100., 10., 1.]) >>> np.geomspace(-1000, -1, num=4)array([-1000., -100., -10., -1.]) >>> np.geomspace(1j, 1000j, num=4) array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j]) >>> np.geomspace(-1+0j, 1+0j, num=5) array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,1.00000000e+00+0.00000000e+00j]) Graphical illustration of endpoint parameter: >>> import matplotlib.pyplot as plt>>> N = 10 >>> y = np.zeros(N) >>> plt.semilogx(np.geomspace(1, 1000, N, endpoint= True ), y + 1, 'o')[ False ), y + 2, 'o')[ True , color='0.7', linestyle='-', which='both', axis='both') >>> plt.show() greater ( x1 , x2 ) Return the truth value of (x1 > x2) element-wise.LAX-backend implementation of greater() . ADDITIONOriginal docstring below.LAX-backend implementation of greater() . Original docstring below.greater(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, sig-nature, extobj]) Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar 82 Chapter 2. APIymjax, Release 0.0.1 See also: greater_equal() , less() , less_equal() , equal() , not_equal() Examples >>> np.greater([4,2],[2,2])array([ True, False]) If the inputs are ndarrays, then np.greater is equivalent to ‘>’. >>> a = np.array([4,2]) >>> b = np.array([2,2]) >>> a > barray([ True, False]) greater_equal ( x1 , x2 ) Return the truth value of (x1 >= x2) element-wise.LAX-backend implementation of greater_equal() . ADDITIONOriginal docstring below.LAX-backend implementation of greater_equal() . Original docstring below.greater_equal(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type bool or ndarray of bool See also: greater() , less() , less_equal() , equal() , not_equal() Examples >>> np.greater_equal([4, 2, 1], [2, 2, 2])array([ True, True, False]) heaviside ( x1 , x2 ) Compute the Heaviside step function.LAX-backend implementation of heaviside() . ADDITIONOriginal docstring below.LAX-backend implementation of heaviside() . Original docstring below.heaviside(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])The Heaviside step function is defined as: if x1 < 0heaviside(x1, x2) = x2 if x1 == 01 if x1 > 0 where x2 is often taken to be 0.5, but 0 and 1 are also sometimes used. Returns out – The output array, element-wise Heaviside step function of x1 . This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar Notes New in version 1.13.0. ReferencesExamples >>> np.heaviside([-1.5, 0, 2.0], 0.5)array([ 0. , 0.5, 1. ]) >>> np.heaviside([-1.5, 0, 2.0], 1)array([ 0., 1., 1.]) hsplit ( ary , indices_or_sections ) Split an array into multiple sub-arrays horizontally (column-wise).LAX-backend implementation of hsplit() . ADDITIONOriginal docstring below.LA hstack ( tup ) Stack arrays in sequence horizontally (column wise).LAX-backend implementation of hstack() . ADDITIONOriginal docstring below.LAX-backend implementation of hstack() . Original docstring below.This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along thefirst axis. Rebuilds arrays divided by hsplit .This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height(first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate , stack and block provide more general stacking and concatenation operations. Returns stacked – The array formed by stacking the given arrays. Return type ndarray See also: stack() Join a sequence of arrays along a new axis. vstack() Stack arrays in sequence vertically (row wise). dstack() Stack arrays in sequence depth wise (along third axis). concatenate() Join a sequence of arrays along an existing axis. hsplit() Split array along second axis. block() Assemble arrays from blocks. 84 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.hstack((a,b))array([1, 2, 3, 2, 3, 4]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[2],[3],[4]]) >>> np.hstack((a,b))array([[1, 2],[2, 3],[3, 4]]) identity ( n , dtype=None ) Return the identity array.LAX-backend implementation of identity() . ADDITIONOriginal docstring below.LAX-backend implementation of identity() . Original docstring below.The identity array is a square array with ones on the main diagonal. Parameters dtype ( data-type, optional ) – Data-type of the output. Defaults to float . Returns out – n x n array with its main diagonal set to one, and all other elements 0. Return type ndarray Examples >>> np.identity(3)array([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]]) imag ( val ) Return the imaginary part of the complex argument.LAX-backend implementation of imag() . ADDITIONOriginal docstring below.LAX-backend implementation of imag() . Original docstring below. Returns out – The imaginary component of the complex argument. If val is real, the type of val isused for the output. If val has complex elements, the returned type is float. Return type ndarray or scalar See also: real() , angle() , real_if_close() >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.imagarray([2., 4., 6.]) >>> a.imag = np.array([8, 10, 12]) >>> aarray([1. +8.j, 3.+10.j, 5.+12.j]) >>> np.imag(1 + 1j)1.0 inner ( a , b , precision=None ) Inner product of two arrays.LAX-backend implementation of inner() . ADDITIONOriginal docstring below.LAX-backend implementation of inner() . In addition to the original NumPy arguments listed below, alsosupports precision for extra control over matrix-multiplication precision on supported devices. See jax.lax.dot() for details.Original docstring below.inner(a, b)Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higherdimensions a sum product over the last axes. Returnsout [ndarray] out.shape = a.shape[:-1] + b.shape[:-1] ValueError If the last dimension of a and b has different size.tensordot : Sum products over arbitrary axes. dot : Generalised matrix product, using secondlast dimension of b . einsum : Einstein summation convention.For vectors (1-D arrays) it computes the ordinary inner-product: np.inner(a, b) = sum(a[:]*b[:]) More generally, if ndim(a) = r > 0 and ndim(b) = s > 0 : np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) or explicitly: np.inner(a, b)[i0,...,ir-1,j0,...,js-1]= sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:]) In addition a or b may be scalars, in which case: np.inner(a,b) = a*b Ordinary inner product for vectors: >>> a = np.array([1,2,3]) >>> b = np.array([0,1,0]) >>> np.inner(a, b)2 86 Chapter 2. APIymjax, Release 0.0.1 A multidimensional example: >>> a = np.arange(24).reshape((2,3,4)) >>> b = np.arange(4) >>> np.inner(a, b)array([[ 14, 38, 62],[ 86, 110, 134]]) An example where b is a scalar: >>> np.inner(np.eye(2), 7)array([[7., 0.],[0., 7.]]) isclose ( a , b , rtol=1e-05 , atol=1e-08 , equal_nan=False ) Returns a boolean array where two arrays are element-wise equal within a tolerance.LAX-backend implementation of isclose() . ADDITIONOriginal docstring below.LAX-backend implementation of isclose() . Original docstring below.The tolerance values are positive, typically very small numbers. The relative difference ( rtol * abs( b )) and theabsolute difference atol are added together to compare against the absolute difference between a and b . Warning: The default atol is not appropriate for comparing numbers that are much smaller than one (seeNotes). Returns y – Returns a boolean array of where a and b are equal within the given tolerance. If both a and b are scalars, returns a single boolean value. Return type array_like See also: allclose() Notes New in version 1.7.0.For finite values, isclose uses the following equation to test whether two floating point values are equivalent.absolute( a - b ) <= ( atol + rtol * absolute( b ))Unlike the built-in math.isclose , the above equation is not symmetric in a and b – it assumes b is the referencevalue – so that isclose(a, b) might be different from isclose(b, a) . Furthermore, the default value of atol isnot zero, and is used to determine what small values should be considered close to zero. The default value isappropriate for expected values of order unity: if the expected values are significantly smaller than one, it canresult in false positives. atol should be carefully selected for the use case at hand. A zero value for atol willresult in False if either a or b is zero. >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan])array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan= True )array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0])array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)array([False, True]) iscomplex ( x ) Returns a bool array, where True if input element is complex.LAX-backend implementation of iscomplex() . ADDITIONOriginal docstring below.LAX-backend implementation of iscomplex() . Original docstring below.What is tested is whether the input has a non-zero imaginary part, not if the input type is complex. Returns out – Output array. Return type ndarray of bools See also: isreal() iscomplexobj() Return True if x is a complex type or an array of complex numbers. Examples >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j])array([ True, False, False, False, False, True]) isfinite ( x ) Test element-wise for finiteness (not infinity or not Not a Number).LAX-backend implementation of isfinite() . ADDITIONOriginal docstring below.LAX-backend implementation of isfinite() . Original docstring below.isfinite(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])The result is returned as a boolean array. Returns y – True where x is not positive infinity, negative infinity, or NaN; false otherwise. This isa scalar if x is a scalar. Return type ndarray, bool 88 Chapter 2. APIymjax, Release 0.0.1 See also: isinf() , isneginf() , isposinf() , isnan() Notes Not a Number, positive infinity and negative infinity are considered to be non-finite.NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not aNumber is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinityis equivalent to positive infinity. Errors result if the second argument is also supplied when x is a scalar input,or if first and second arguments have different shapes. Examples >>> np.isfinite(1)True >>> np.isfinite(0)True >>> np.isfinite(np.nan)False >>> np.isfinite(np.inf)False >>> np.isfinite(np.NINF)False >>> np.isfinite([np.log(-1.),1.,np.log(0)])array([False, True, False]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isfinite(x, y)array([0, 1, 0]) >>> yarray([0, 1, 0]) isinf ( x ) Test element-wise for positive or negative infinity.LAX-backend implementation of isinf() . ADDITIONOriginal docstring below.LAX-backend implementation of isinf() . Original docstring below.isinf(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])Returns a boolean array of the same shape as x , True where x == +/-inf , otherwise False. Returns y – True where x is positive or negative infinity, false otherwise. This is a scalar if x is ascalar. Return type bool (scalar) or boolean ndarray See also: isneginf() , isposinf() , isnan() , isfinite() NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).Errors result if the second argument is supplied when the first argument is a scalar, or if the first and secondarguments have different shapes. Examples >>> np.isinf(np.inf)True >>> np.isinf(np.nan)False >>> np.isinf(np.NINF)True >>> np.isinf([np.inf, -np.inf, 1.0, np.nan])array([ True, True, False, False]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isinf(x, y)array([1, 0, 1]) >>> yarray([1, 0, 1]) isnan ( x ) Test element-wise for NaN and return result as a boolean array.LAX-backend implementation of isnan() . ADDITIONOriginal docstring below.LAX-backend implementation of isnan() . Original docstring below.isnan(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – True where x is NaN, false otherwise. This is a scalar if x is a scalar. Return type ndarray or bool See also: isinf() , isneginf() , isposinf() , isfinite() , isnat() Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not aNumber is not equivalent to infinity. 90 Chapter 2. APIymjax, Release 0.0.1Examples >>> np.isnan(np.nan)True >>> np.isnan(np.inf)False >>> np.isnan([np.log(-1.),1.,np.log(0)])array([ True, False, False]) isreal ( x ) Returns a bool array, where True if input element is real.LAX-backend implementation of isreal() . ADDITIONOriginal docstring below.LAX-backend implementation of isreal() . Original docstring below.If element has complex type with zero complex part, the return value for that element is True. Returns out – Boolean array of same shape as x . Return type ndarray, bool See also: iscomplex() isrealobj() Return True if x is not a complex type. Examples >>> np.isreal([1+1j, 1+0j, 4.5, 3, 2, 2j])array([False, True, True, True, True, False]) isscalar ( num ) Returns True if the type of element is a scalar type.LAX-backend implementation of isscalar() . ADDITIONOriginal docstring below.LAX-backend implementation of isscalar() . Original docstring below. Returns val – True if element is a scalar type, False if it is not. Return type bool See also: ndim() Get the number of dimensions of an array Notes If you need a stricter way to identify a numerical scalar, use isinstance(x, numbers.Number) , as thatreturns False for most non-numerical elements such as strings.In most cases np.ndim(x) == 0 should be used instead of this function, as that will also return true for0d arrays. This is how numpy overloads functions in the style of the dx arguments to gradient and the bins argument to histogram . Some key differences: x isscalar(x) np.ndim(x) ==0 PEP 3141 numeric objects (including builtins) True True builtin string and buffer objects True True other builtin objects, like pathlib.Path , Exception , the result of re.compile False True third-party objects like matplotlib.figure.Figure False True zero-dimensional numpy arrays False True other numpy arrays False False list , tuple , and other sequence objects False False Examples >>> np.isscalar(3.1)True >>> np.isscalar(np.array(3.1))False >>> np.isscalar([3.1])False >>> np.isscalar( False )True >>> np.isscalar('numpy')True NumPy supports PEP 3141 numbers: >>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17))True >>> from numbers import Number >>> np.isscalar(Number())True ix_ ( *args ) Construct an open mesh from multiple sequences.LAX-backend implementation of ix_() . ADDITIONOriginal docstring below.LAX-backend implementation of ix_() . Original docstring below.This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 inall but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]] . Parameters args ( ) – Each sequence should be of integer or boolean type.Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equiv-alent to passing in np.nonzero(boolean_sequence) ). Returns out – N arrays with N dimensions each, with N the number of input sequences. Togetherthese arrays form an open mesh. Return type tuple of ndarrays See also: ogrid() , mgrid() , meshgrid() 92 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.arange(10).reshape(2, 5) >>> aarray([[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid(array([[0],[1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape((2, 1), (1, 2)) >>> a[ixgrid]array([[2, 4],[7, 9]]) >>> ixgrid = np.ix_([ True , True ], [2, 4]) >>> a[ixgrid]array([[2, 4],[7, 9]]) >>> ixgrid = np.ix_([ True , True ], [ False , False , True , False , True ]) >>> a[ixgrid]array([[2, 4],[7, 9]]) kron ( a , b ) Kronecker product of two arrays.LAX-backend implementation of kron() . ADDITIONOriginal docstring below.LAX-backend implementation of kron() . Original docstring below.Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first. Returns outReturn type ndarray See also: outer() The outer product Notes The function assumes that the number of dimensions of a and b are the same, if necessary prepending thesmallest with ones. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,. . . ,sN) , the Kronecker product has shape (r0*s0, r1*s1, . . . , rN*SN) . The elements are products of elements from a and b , organized explicitly by: kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] where: kt = it * st + jt, t = 0,...,N In the common 2-D case (N=1), the block structure can be visualized: [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],[ ... ... ],[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] Examples >>> np.kron([1,10,100], [5,6,7])array([ 5, 6, 7, ..., 500, 600, 700]) >>> np.kron([5,6,7], [1,10,100])array([ 5, 50, 500, ..., 7, 70, 700]) >>> np.kron(np.eye(2), np.ones((2,2)))array([[1., 1., 0., 0.],[1., 1., 0., 0.],[0., 0., 1., 1.],[0., 0., 1., 1.]]) >>> a = np.arange(100).reshape((2,5,2,5)) >>> b = np.arange(24).reshape((2,3,4)) >>> c = np.kron(a,b) >>> c.shape(2, 10, 6, 20) >>> I = (1,3,0,2) >>> J = (0,2,1) >>> J1 = (0,) + J >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) >>> c[K] == a[I]*b[J]True lcm ( x1 , x2 ) Returns the lowest common multiple of |x1| and |x2| LAX-backend implementation of lcm() . ADDITIONOriginal docstring below.LAX-backend implementation of lcm() . Original docstring below.lcm(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: gcd() The greatest common divisor 94 Chapter 2. APIymjax, Release 0.0.1Examples >>> np.lcm(12, 20)60 >>> np.lcm.reduce([3, 12, 20])60 >>> np.lcm.reduce([40, 12, 20])120 >>> np.lcm(np.arange(6), 20)array([ 0, 20, 20, 60, 20, 20]) left_shift ( x1 , x2 ) Shift the bits of an integer to the left.LAX-backend implementation of left_shift() . ADDITIONOriginal docstring below.LAX-backend implementation of left_shift() . Original docstring below.left_shift(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Bits are shifted to the left by appending x2 0s at the right of x1 . Since the internal representation of numbers isin binary format, this operation is equivalent to multiplying x1 by . Returns out – Return x1 with bits shifted x2 times to the left. This is a scalar if both x1 and x2 arescalars. Return type array of integer type See also: right_shift() Shift the bits of an integer to the right. binary_repr() Return the binary representation of the input number as a string. Examples >>> np.binary_repr(5)'101' >>> np.left_shift(5, 2)20 >>> np.binary_repr(20)'10100' >>> np.left_shift(5, [1,2,3])array([10, 20, 40]) less ( x1 , x2 ) Return the truth value of (x1 < x2) element-wise.LAX-backend implementation of less() . ADDITIONOriginal docstring below.LAX-backend implementation of less() . Original docstring below.less(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: greater() , less_equal() , greater_equal() , equal() , not_equal() Examples >>> np.less([1, 2], [2, 2])array([ True, False]) less_equal ( x1 , x2 ) Return the truth value of (x1 =< x2) element-wise.LAX-backend implementation of less_equal() . ADDITIONOriginal docstring below.LAX-backend implementation of less_equal() . Original docstring below.less_equal(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: greater() , less() , greater_equal() , equal() , not_equal() Examples >>> np.less_equal([4, 2, 1], [2, 2, 2])array([False, True, True]) linspace ( start , stop , num=50 , endpoint=True , retstep=False , dtype=None , axis=0 ) Return evenly spaced numbers over a specified interval.LAX-backend implementation of linspace() . ADDITIONOriginal docstring below.LAX-backend implementation of linspace() . Original docstring below.Returns num evenly spaced samples, calculated over the interval [ start , stop ].The endpoint of the interval can optionally be excluded.Changed in version 1.16.0: Non-scalar start and stop are now supported. Parameters dtype ( dtype, optional ) – The type of the output array. If dtype is not given,infer the data type from the other input arguments. Returns • samples ( ndarray ) – There are num equally spaced samples in the closed interval [start,stop] or the half-open interval [start, stop) (depending on whether endpoint isTrue or False).• step ( float, optional ) – Only returned if retstep is TrueSize of spacing between samples. See also: 96 Chapter 2. APIymjax, Release 0.0.1 arange() Similar to linspace , but uses a step size (instead of the number of samples). geomspace() Similar to linspace , but with numbers spaced evenly on a log scale (a geometric progression). logspace() Similar to geomspace , but with the end points specified as logarithms. Examples >>> np.linspace(2.0, 3.0, num=5)array([2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint= False )array([2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep= True )(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) Graphical illustration: >>> import matplotlib.pyplot as plt>>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint= True ) >>> x2 = np.linspace(0, 10, N, endpoint= False ) >>> plt.plot(x1, y, 'o')[ See also: log10() , log2() , log1p() , emath.log() Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x . Theconvention is to return the z whose imaginary part lies in [-pi, pi] .For real-valued input data types, log always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is continuousfrom above on it. log handles the floating-point negative zero as an infinitesimal negative number, conformingto the C99 standard. ReferencesExamples >>> np.log([1, np.e, np.e**2, 0])array([ 0., 1., 2., -Inf]) log10 ( x ) Return the base 10 logarithm of the input array, element-wise.LAX-backend implementation of log10() . ADDITIONOriginal docstring below.LAX-backend implementation of log10() . Original docstring below.log10(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The logarithm to the base 10 of x , element-wise. NaNs are returned where x is negative.This is a scalar if x is a scalar. Return type ndarray See also: emath.log10() Notes Logarithm is a multivalued function: for each x there is an infinite number of z such that . Theconvention is to return the z whose imaginary part lies in [-pi, pi] .For real-valued input data types, log10 always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, log10 is a complex analytical function that has a branch cut [-inf, 0] and is continuousfrom above on it. log10 handles the floating-point negative zero as an infinitesimal negative number, conformingto the C99 standard. 98 Chapter 2. APIymjax, Release 0.0.1ReferencesExamples >>> np.log10([1e-15, -3.])array([-15., nan]) log1p ( x ) Return the natural logarithm of one plus the input array, element-wise.LAX-backend implementation of log1p() . ADDITIONOriginal docstring below.LAX-backend implementation of log1p() . Original docstring below.log1p(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])Calculates log(1 + x) . Returns y – Natural logarithm of , element-wise. This is a scalar if x is a scalar. Return type ndarray See also: expm1() exp(x) - 1 , the inverse of log1p . Notes For real-valued input, log1p is accurate also for x so small that in floating-point accuracy.Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x . Theconvention is to return the z whose imaginary part lies in [-pi, pi] .For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, log1p is a complex analytical function that has a branch cut [-inf, -1] and is con-tinuous from above on it. log1p handles the floating-point negative zero as an infinitesimal negative number,conforming to the C99 standard. ReferencesExamples >>> np.log1p(1e-99)1e-99 >>> np.log(1 + 1e-99)0.0 log2 ( x ) Base-2 logarithm of x .LAX-backend implementation of log2() . ADDITIONOriginal docstring below.LAX-backend implementation of log2() . Original docstring below.log2(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – Base-2 logarithm of x . This is a scalar if x is a scalar. Return type ndarray See also: log() , log10() , log1p() , emath.log2() Notes New in version 1.3.0.Logarithm is a multivalued function: for each x there is an infinite number of z such that . Theconvention is to return the z whose imaginary part lies in [-pi, pi] .For real-valued input data types, log2 always returns real output. For each value that cannot be expressed as areal number or infinity, it yields nan and sets the invalid floating point error flag.For complex-valued input, log2 is a complex analytical function that has a branch cut [-inf, 0] and is continuousfrom above on it. log2 handles the floating-point negative zero as an infinitesimal negative number, conformingto the C99 standard. Examples >>> x = np.array([0, 1, 2, 2**4]) >>> np.log2(x)array([-Inf, 0., 1., 4.]) >>> xi = np.array([0+1.j, 1, 2+0.j, 4.j]) >>> np.log2(xi)array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j]) logical_and ( *args ) Compute the truth value of x1 AND x2 element-wise.LAX-backend implementation of logical_and() . ADDITIONOriginal docstring below.LAX-backend implementation of logical_and() . Original docstring below.logical_and(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns y – Boolean result of the logical AND operation applied to the elements of x1 and x2 ; theshape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. Return type ndarray or bool See also: logical_or() , logical_not() , logical_xor() , bitwise_and() 100 Chapter 2. APIymjax, Release 0.0.1Examples >>> np.logical_and( True , False )False >>> np.logical_and([ True , False ], [ False , False ])array([False, False]) >>> x = np.arange(5) >>> np.logical_and(x>1, x<4)array([False, False, True, True, False]) logical_not ( *args ) Compute the truth value of NOT x element-wise.LAX-backend implementation of logical_not() . ADDITIONOriginal docstring below.LAX-backend implementation of logical_not() . Original docstring below.logical_not(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj]) Returns y – Boolean result with the same shape as x of the NOT operation on elements of x . This isa scalar if x is a scalar. Return type bool or ndarray of bool See also: logical_and() , logical_or() , logical_xor() Examples >>> np.logical_not(3)False >>> np.logical_not([ True , False , 0, 1])array([False, True, True, False]) >>> x = np.arange(5) >>> np.logical_not(x<3)array([False, False, False, True, True]) logical_or ( *args ) Compute the truth value of x1 OR x2 element-wise.LAX-backend implementation of logical_or() . ADDITIONOriginal docstring below.LAX-backend implementation of logical_or() . Original docstring below.logical_or(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns y – Boolean result of the logical OR operation applied to the elements of x1 and x2 ; theshape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. Return type ndarray or bool See also: logical_and() , logical_not() , logical_xor() , bitwise_or() >>> np.logical_or( True , False )True >>> np.logical_or([ True , False ], [ False , False ])array([ True, False]) >>> x = np.arange(5) >>> np.logical_or(x < 1, x > 3)array([ True, False, False, False, True]) logical_xor ( *args ) Compute the truth value of x1 XOR x2, element-wise.LAX-backend implementation of logical_xor() . ADDITIONOriginal docstring below.LAX-backend implementation of logical_xor() . Original docstring below.logical_xor(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Returns y – Boolean result of the logical XOR operation applied to the elements of x1 and x2 ; theshape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. Return type bool or ndarray of bool See also: logical_and() , logical_or() , logical_not() , bitwise_xor() Examples >>> np.logical_xor( True , False )True >>> np.logical_xor([ True , True , False , False ], [ True , False , True , False ])array([False, True, True, False]) >>> x = np.arange(5) >>> np.logical_xor(x < 1, x > 3)array([ True, False, False, False, True]) Simple example showing support of broadcasting >>> np.logical_xor(0, np.eye(2))array([[ True, False],[False, True]]) logspace ( start , stop , num=50 , endpoint=True , base=10.0 , dtype=None , axis=0 ) Return numbers spaced evenly on a log scale.LAX-backend implementation of logspace() . ADDITIONOriginal docstring below.LAX-backend implementation of logspace() . Original docstring below.In linear space, the sequence starts at base ** start ( base to the power of start ) and ends with base **stop (see endpoint below).Changed in version 1.16.0: Non-scalar start and stop are now supported. 102 Chapter 2. APIymjax, Release 0.0.1 Parameters dtype ( dtype ) – The type of the output array. If dtype is not given, infer the datatype from the other input arguments. Returns samples – num samples, equally spaced on a log scale. Return type ndarray See also: arange() Similar to linspace, with the step size specified instead of the number of samples. Note that, whenused with a float endpoint, the endpoint may or may not be included. linspace() Similar to logspace, but with the samples uniformly distributed in linear space, instead of logspace. geomspace() Similar to logspace, but with endpoints specified directly. Notes Logspace is equivalent to the code >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) ...>>> power(base, y).astype(dtype) ... Examples >>> np.logspace(2.0, 3.0, num=4)array([ 100. , 215.443469 , 464.15888336, 1000. ]) >>> np.logspace(2.0, 3.0, num=4, endpoint= False )array([100. , 177.827941 , 316.22776602, 562.34132519]) >>> np.logspace(2.0, 3.0, num=4, base=2.0)array([4. , 5.0396842 , 6.34960421, 8. ]) Graphical illustration: >>> import matplotlib.pyplot as plt>>> N = 10 >>> x1 = np.logspace(0.1, 1, N, endpoint= True ) >>> x2 = np.logspace(0.1, 1, N, endpoint= False ) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o')[ Original docstring below.matmul(x1, x2, /, out=None, * , casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) Returns y – The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors. Return type ndarray Raises ValueError – If the last dimension of a is not the same size as the second-to-last dimen-sion of b .If a scalar value is passed in. See also: vdot() Complex-conjugating dot product. tensordot() Sum products over arbitrary axes. einsum() Einstein summation convention. dot() alternative matrix product with different broadcasting rules. Notes The behavior depends on the arguments in the following way.• If both arguments are 2-D they are multiplied like conventional matrices.• If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes andbroadcast accordingly.• If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrixmultiplication the prepended 1 is removed.• If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrixmultiplication the appended 1 is removed. matmul differs from dot in two important ways:• Multiplication by scalars is not allowed, use * instead.• Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature (n,k),(k,m)->(n,m) : >>> a = np.ones([9, 5, 7, 4]) >>> c = np.ones([9, 5, 4, 3]) >>> np.dot(a, c).shape(9, 5, 7, 9, 5, 3) >>> np.matmul(a, c).shape(9, 5, 7, 3) >>> The matmul function implements the semantics of the @ operator introduced in Python 3.5 following PEP465. 104 Chapter 2. APIymjax, Release 0.0.1Examples For 2-D arrays it is the matrix product: >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([[4, 1], ... [2, 2]]) >>> np.matmul(a, b)array([[4, 1],[2, 2]]) For 2-D mixed with 1-D, the result is the usual. >>> a = np.array([[1, 0], ... [0, 1]]) >>> b = np.array([1, 2]) >>> np.matmul(a, b)array([1, 2]) >>> np.matmul(b, a)array([1, 2]) Broadcasting is conventional for stacks of arrays >>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4)) >>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2)) >>> np.matmul(a,b).shape(2, 2, 2) >>> np.matmul(a, b)[0, 1, 1]98 >>> sum(a[0, 1, :] * b[0 , :, 1])98 Vector, vector returns the scalar inner product, but neither argument is complex-conjugated: >>> np.matmul([2j, 3j], [2j, 3j])(-13+0j) Scalar multiplication raises an error. >>> np.matmul([1,2], 3)Traceback (most recent call last): ... ValueError: matmul: Input operand 1 does not have enough dimensions ... New in version 1.10.0. max ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the maximum of an array or maximum along an axis.LAX-backend implementation of amax() . ADDITIONOriginal docstring below.LAX-backend implementation of amax() . Original docstring below. Returns amax – Maximum of a . If axis is None, the result is a scalar value. If axis is given, theresult is an array of dimension a.ndim - 1 . Return type ndarray or scalar See also: amin() The minimum value of an array along a given axis, propagating any NaNs. nanmax() The maximum value of an array along a given axis, ignoring any NaNs. maximum() Element-wise maximum of two arrays, propagating any NaNs. fmax() Element-wise maximum of two arrays, ignoring any NaNs. argmax() Return the indices of the maximum values. nanmin() , minimum() , fmin() Notes NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well.To ignore NaN values (MATLAB behavior), please use nanmax.Don’t use amax for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0],a[1]) is faster than amax(a, axis=0) . Examples >>> a = np.arange(4).reshape((2,2)) >>> aarray([[0, 1],[2, 3]]) >>> np.amax(a) >>> np.amax(a, axis=0) array([2, 3]) >>> np.amax(a, axis=1) array([1, 3]) >>> np.amax(a, where=[ False , True ], initial=-1, axis=0)array([-1, 3]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amax(b)nan >>> np.amax(b, where=~np.isnan(b), initial=-1)4.0 >>> np.nanmax(b)4.0 You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value: >>> np.max([[-50], [10]], axis=-1, initial=0)array([ 0, 10]) Notice that the initial value is used as one of the elements for which the maximum is determined, unlike for thedefault argument Python’s max function, which is only used for empty iterables. >>> np.max([5], initial=6)6 >>> max([5], default=6)5 106 Chapter 2. APIymjax, Release 0.0.1 maximum ( x1 , x2 ) Element-wise maximum of array elements.LAX-backend implementation of maximum() . ADDITIONOriginal docstring below.LAX-backend implementation of maximum() . Original docstring below.maximum(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements beingcompared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latterdistinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts beinga NaN. The net effect is that NaNs are propagated. Returns y – The maximum of x1 and x2 , element-wise. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: minimum() Element-wise minimum of two arrays, propagates NaNs. fmax() Element-wise maximum of two arrays, ignores NaNs. amax() The maximum value of an array along a given axis, propagates NaNs. nanmax() The maximum value of an array along a given axis, ignores NaNs. fmin() , amin() , nanmin() Notes The maximum is equivalent to np.where(x1 >= x2, x1, x2) when neither x1 nor x2 are nans, but it isfaster and does proper broadcasting. Examples >>> np.maximum([2, 3, 4], [1, 5, 2])array([2, 5, 4]) >>> np.maximum(np.eye(2), [0.5, 2]) array([[ 1. , 2. ],[ 0.5, 2. ]]) >>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])array([nan, nan, nan]) >>> np.maximum(np.Inf, 1)inf mean ( a , axis=None , dtype=None , out=None , keepdims=False ) Compute the arithmetic mean along the specified axis.LAX-backend implementation of mean() . ADDITIONOriginal docstring below.LAX-backend implementation of mean() . Original docstring below.Returns the average of the array elements. The average is taken over the flattened array by default, otherwiseover the specified axis. float64 intermediate and return values are used for integer inputs. Parameters dtype ( data-type, optional ) – Type to use in computing the mean. For inte-ger inputs, the default is float64 ; for floating point inputs, it is the same as the input dtype. Returns m – If out=None , returns a new array containing the mean values, otherwise a reference tothe output array is returned. Return type ndarray, see dtype parameter above See also: average() Weighted average std() , var() , nanmean() , nanstd() , nanvar() Notes The arithmetic mean is the sum of the elements along the axis divided by the number of elements.Note that for floating-point input, the mean is computed using the same precision the input has. Depending onthe input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifyinga higher-precision accumulator using the dtype keyword can alleviate this issue.By default, float16 results are computed using float32 intermediates for extra precision. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> np.mean(a)2.5 >>> np.mean(a, axis=0)array([2., 3.]) >>> np.mean(a, axis=1)array([1.5, 3.5]) In single precision, mean can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.mean(a)0.54999924 Computing the mean in float64 is more accurate: >>> np.mean(a, dtype=np.float64)0.55000000074505806 median ( a , axis=None , out=None , overwrite_input=False , keepdims=False ) Compute the median along the specified axis.LAX-backend implementation of median() . ADDITIONOriginal docstring below.LAX-backend implementation of median() . Original docstring below.Returns the median of the array elements. 108 Chapter 2. APIymjax, Release 0.0.1 Returns median – A new array holding the result. If the input contains integers or floats smallerthan float64 , then the output data-type is np.float64 . Otherwise, the data-type of theoutput is the same as that of the input. If out is specified, that array is returned instead. Return type ndarray See also: mean() , percentile() Notes Given a vector V of length N , the median of V is the middle value of a sorted copy of V , V_sorted - i e., V_sorted[(N-1)/2] , when N is odd, and the average of the two middle values of V_sorted when N iseven. Examples >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> aarray([[10, 7, 4],[ 3, 2, 1]]) >>> np.median(a)3.5 >>> np.median(a, axis=0)array([6.5, 4.5, 2.5]) >>> np.median(a, axis=1)array([7., 2.]) >>> m = np.median(a, axis=0) >>> out = np.zeros_like(m) >>> np.median(a, axis=0, out=m)array([6.5, 4.5, 2.5]) >>> marray([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.median(b, axis=1, overwrite_input= True )array([7., 2.]) >>> assert not np.all(a==b) >>> b = a.copy() >>> np.median(b, axis= None , overwrite_input= True )3.5 >>> assert not np.all(a==b) meshgrid ( *args , **kwargs ) Return coordinate matrices from coordinate vectors.LAX-backend implementation of meshgrid() . ADDITIONOriginal docstring below.LAX-backend implementation of meshgrid() . Original docstring below.Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,. . . , xn.Changed in version 1.9: 1-D and 0-D cases are allowed. Returns X1, X2,. . . , XN – For vectors x1 , x2 ,. . . , ‘xn’ with lengths Ni=len(xi) , return (N1,N2, N3,...Nn) shaped arrays if indexing=’ij’ or (N2, N1, N3,...Nn) shaped arrays if indexing=’xy’ with the elements of xi repeated to fill the matrix along the first dimension for x1 , the second for x2 and so on. Return type ndarray Notes This function supports both indexing conventions through the indexing keyword argument. Giving the string ‘ij’returns a meshgrid with matrix indexing, while ‘xy’ returns a meshgrid with Cartesian indexing. In the 2-D casewith inputs of length M and N, the outputs are of shape (N, M) for ‘xy’ indexing and (M, N) for ‘ij’ indexing.In the 3-D case with inputs of length M, N and P, outputs are of shape (N, M, P) for ‘xy’ indexing and (M, N, P)for ‘ij’ indexing. The difference is illustrated by the following code snippet: xv, yv = np.meshgrid(x, y, sparse= False , indexing='ij') for i in range(nx): for j in range(ny): xv, yv = np.meshgrid(x, y, sparse= False , indexing='xy') for i in range(nx): for j in range(ny): In the 1-D and 0-D case, the indexing and sparse keywords have no effect. See also: index_tricks.mgrid() Construct a multi-dimensional “meshgrid” using indexing notation. index_tricks.ogrid() Construct an open multi-dimensional “meshgrid” using indexing notation. Examples >>> nx, ny = (3, 2) >>> x = np.linspace(0, 1, nx) >>> y = np.linspace(0, 1, ny) >>> xv, yv = np.meshgrid(x, y) >>> xvarray([[0. , 0.5, 1. ],[0. , 0.5, 1. ]]) >>> yvarray([[0., 0., 0.],[1., 1., 1.]]) >>> xv, yv = np.meshgrid(x, y, sparse= True ) >>> xvarray([[0. , 0.5, 1. ]]) >>> yvarray([[0.],[1.]]) meshgrid is very useful to evaluate functions on a grid. >>> import matplotlib.pyplot as plt>>> x = np.arange(-5, 5, 0.1) >>> y = np.arange(-5, 5, 0.1) >>> xx, yy = np.meshgrid(x, y, sparse= True ) (continues on next page) 110 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) >>> h = plt.contourf(x,y,z) >>> plt.show() min ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the minimum of an array or minimum along an axis.LAX-backend implementation of amin() . ADDITIONOriginal docstring below.LAX-backend implementation of amin() . Original docstring below. Returns amin – Minimum of a . If axis is None, the result is a scalar value. If axis is given, theresult is an array of dimension a.ndim - 1 . Return type ndarray or scalar See also: amax() The maximum value of an array along a given axis, propagating any NaNs. nanmin() The minimum value of an array along a given axis, ignoring any NaNs. minimum() Element-wise minimum of two arrays, propagating any NaNs. fmin() Element-wise minimum of two arrays, ignoring any NaNs. argmin() Return the indices of the minimum values. nanmax() , maximum() , fmax() Notes NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well.To ignore NaN values (MATLAB behavior), please use nanmin.Don’t use amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0) . Examples >>> a = np.arange(4).reshape((2,2)) >>> aarray([[0, 1],[2, 3]]) >>> np.amin(a) >>> np.amin(a, axis=0) array([0, 1]) >>> np.amin(a, axis=1) array([0, 2]) >>> np.amin(a, where=[ False , True ], initial=10, axis=0)array([10, 1]) >>> b = np.arange(5, dtype=float) >>> b[2] = np.NaN >>> np.amin(b) (continues on next page) (continued from previous page) nan >>> np.amin(b, where=~np.isnan(b), initial=10)0.0 >>> np.nanmin(b)0.0 >>> np.min([[-50], [10]], axis=-1, initial=0)array([-50, 0]) Notice that the initial value is used as one of the elements for which the minimum is determined, unlike for thedefault argument Python’s max function, which is only used for empty iterables.Notice that this isn’t the same as Python’s default argument. >>> np.min([6], initial=5)5 >>> min([6], default=5)6 minimum ( x1 , x2 ) Element-wise minimum of array elements.LAX-backend implementation of minimum() . ADDITIONOriginal docstring below.LAX-backend implementation of minimum() . Original docstring below.minimum(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Compare two arrays and returns a new array containing the element-wise minima. If one of the elements beingcompared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latterdistinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts beinga NaN. The net effect is that NaNs are propagated. Returns y – The minimum of x1 and x2 , element-wise. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: maximum() Element-wise maximum of two arrays, propagates NaNs. fmin() Element-wise minimum of two arrays, ignores NaNs. amin() The minimum value of an array along a given axis, propagates NaNs. nanmin() The minimum value of an array along a given axis, ignores NaNs. fmax() , amax() , nanmax() 112 Chapter 2. APIymjax, Release 0.0.1Notes The minimum is equivalent to np.where(x1 <= x2, x1, x2) when neither x1 nor x2 are NaNs, but itis faster and does proper broadcasting. Examples >>> np.minimum([2, 3, 4], [1, 5, 2])array([1, 3, 2]) >>> np.minimum(np.eye(2), [0.5, 2]) array([[ 0.5, 0. ],[ 0. , 1. ]]) >>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])array([nan, nan, nan]) >>> np.minimum(-np.Inf, 1)-inf mod ( x1 , x2 ) Return element-wise remainder of division.LAX-backend implementation of remainder() . ADDITIONOriginal docstring below.LAX-backend implementation of remainder() . Original docstring below.remainder(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modu-lus operator``x1 % x2`` and has the same sign as the divisor x2 . The MATLAB function equivalent to np.remainder is mod . Warning: This should not be confused with:• Python 3.7’s math.remainder and C’s remainder , which computes the IEEE remainder, which arethe complement to round(x1 / x2) .• The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2) . Returns y – The element-wise remainder of the quotient floor_divide(x1, x2) . This is ascalar if both x1 and x2 are scalars. Return type ndarray See also: floor_divide() Equivalent of Python // operator. divmod() Simultaneous floor division and remainder. fmod() Equivalent of the MATLAB rem function. divide() , floor() Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder . Examples >>> np.remainder([4, 7], [2, 3])array([0, 1]) >>> np.remainder(np.arange(7), 5)array([0, 1, 2, 3, 4, 0, 1]) moveaxis ( a , source , destination ) Move axes of an array to new positions.LAX-backend implementation of moveaxis() . ADDITIONOriginal docstring below.LAX-backend implementation of moveaxis() . Original docstring below.Other axes remain in their original order.New in version 1.11.0. Returns result – Array with moved axes. This array is a view of the input array. Return type np.ndarray See also: transpose() Permute the dimensions of an array. swapaxes() Interchange two axes of an array. Examples >>> x = np.zeros((3, 4, 5)) >>> np.moveaxis(x, 0, -1).shape(4, 5, 3) >>> np.moveaxis(x, -1, 0).shape(5, 3, 4) These all achieve the same result: >>> np.transpose(x).shape(5, 4, 3) >>> np.swapaxes(x, 0, -1).shape(5, 4, 3) >>> np.moveaxis(x, [0, 1], [-1, -2]).shape(5, 4, 3) >>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape(5, 4, 3) multiply ( x1 , x2 ) Multiply arguments element-wise.LAX-backend implementation of multiply() . ADDITIONOriginal docstring below.LAX-backend implementation of multiply() . Original docstring below. 114 Chapter 2. APIymjax, Release 0.0.1 multiply(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, sig-nature, extobj]) Returns y – The product of x1 and x2 , element-wise. This is a scalar if both x1 and x2 are scalars. Return type ndarray Notes Equivalent to x1 * x2 in terms of array broadcasting. Examples >>> np.multiply(2.0, 4.0)8.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.multiply(x1, x2)array([[ 0., 1., 4.],[ 0., 4., 10.],[ 0., 7., 16.]]) nan_to_num ( x , copy=True ) Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the numbers de-fined by the user using the nan , posinf and/or neginf keywords.LAX-backend implementation of nan_to_num() . ADDITIONOriginal docstring below.LAX-backend implementation of nan_to_num() . Original docstring below.If x is inexact, NaN is replaced by zero or by the user defined value in nan keyword, infinity is replaced by thelargest finite floating point values representable by x.dtype or by the user defined value in posinf keywordand -infinity is replaced by the most negative finite floating point values representable by x.dtype or by theuser defined value in neginf keyword.For complex dtypes, the above is applied to each of the real and imaginary components of x separately.If x is not inexact, then no replacements are made. Returns out – x , with the non-finite values replaced. If copy is False, this may be x itself. Return type ndarray See also: isinf() Shows which elements are positive or negative infinity. isneginf() Shows which elements are negative infinity. isposinf() Shows which elements are positive infinity. isnan() Shows which elements are Not a Number (NaN). isfinite() Shows which elements are finite (not NaN, not infinity) NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not aNumber is not equivalent to infinity. Examples >>> np.nan_to_num(np.inf)1.7976931348623157e+308 >>> np.nan_to_num(-np.inf)-1.7976931348623157e+308 >>> np.nan_to_num(np.nan)0.0 >>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) >>> np.nan_to_num(x)array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333)array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03,-1.2800000e+02, 1.2800000e+02]) >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)])array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, >>> np.nan_to_num(y)array([ 1.79769313e+308 +0.00000000e+000j, >>> np.nan_to_num(y, nan=111111, posinf=222222)array([222222.+111111.j, 111111. +0.j, 111111.+222222.j]) nancumprod ( a , axis=None , dtype=None ) Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) asone. The cumulative product does not change when NaNs are encountered and leading NaNs are replacedby ones.LAX-backend implementation of nancumprod() . ADDITIONOriginal docstring below.LAX-backend implementation of nancumprod() . Original docstring below.Ones are returned for slices that are all-NaN or empty.New in version 1.12.0. Parameters dtype ( dtype, optional ) – Type of the returned array, as well as of the accumu-lator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a ,unless a has an integer dtype with a precision less than that of the default platform integer. Inthat case, the default platform integer is used instead. Returns nancumprod – A new array holding the result is returned unless out is specified, in whichcase it is returned. Return type ndarray See also: numpy.cumprod() Cumulative product across array propagating NaNs. isnan() Show which elements are NaN. 116 Chapter 2. APIymjax, Release 0.0.1Examples >>> np.nancumprod(1)array([1]) >>> np.nancumprod([1])array([1]) >>> np.nancumprod([1, np.nan])array([1., 1.]) >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nancumprod(a)array([1., 2., 6., 6.]) >>> np.nancumprod(a, axis=0)array([[1., 2.],[3., 2.]]) >>> np.nancumprod(a, axis=1)array([[1., 2.],[3., 3.]]) nancumsum ( a , axis=None , dtype=None ) Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced byzeros.LAX-backend implementation of nancumsum() . ADDITIONOriginal docstring below.LAX-backend implementation of nancumsum() . Original docstring below.Zeros are returned for slices that are all-NaN or empty.New in version 1.12.0. Parameters dtype ( dtype, optional ) – Type of the returned array and of the accumulator inwhich the elements are summed. If dtype is not specified, it defaults to the dtype of a , unless a has an integer dtype with a precision less than that of the default platform integer. In that case,the default platform integer is used. Returns nancumsum – A new array holding the result is returned unless out is specified, in whichit is returned. The result has the same size as a , and the same shape as a if axis is not None or a is a 1-d array. Return type ndarray. See also: numpy.cumsum() Cumulative sum across array propagating NaNs. isnan() Show which elements are NaN. Examples >>> np.nancumsum(1)array([1]) >>> np.nancumsum([1])array([1]) >>> np.nancumsum([1, np.nan])array([1., 1.]) >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nancumsum(a) (continues on next page) (continued from previous page) array([1., 3., 6., 6.]) >>> np.nancumsum(a, axis=0)array([[1., 2.],[4., 2.]]) >>> np.nancumsum(a, axis=1)array([[1., 3.],[3., 3.]]) nanmax ( a , axis=None , out=None , keepdims=False , **kwargs ) Return the maximum of an array or maximum along an axis, ignoring any NaNs. When all-NaN slicesare encountered a RuntimeWarning is raised and NaN is returned for that slice.LAX-backend implementation of nanmax() . ADDITIONOriginal docstring below.LAX-backend implementation of nanmax() . Original docstring below. Returns nanmax – An array with the same shape as a , with the specified axis removed. If a is a 0-darray, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned. Return type ndarray See also: nanmin() The minimum value of an array along a given axis, ignoring any NaNs. amax() The maximum value of an array along a given axis, propagating any NaNs. fmax() Element-wise maximum of two arrays, ignoring any NaNs. maximum() Element-wise maximum of two arrays, propagating any NaNs. isnan() Shows which elements are Not a Number (NaN). isfinite() Shows which elements are neither NaN nor infinity. amin() , fmin() , minimum() Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not aNumber is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity istreated as a very small (i.e. negative) number.If the input has a integer type the function is equivalent to np.max. Examples >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmax(a)3.0 >>> np.nanmax(a, axis=0)array([3., 2.]) >>> np.nanmax(a, axis=1)array([2., 3.]) When positive infinity and negative infinity are present: 118 Chapter 2. APIymjax, Release 0.0.1 >>> np.nanmax([1, 2, np.nan, np.NINF])2.0 >>> np.nanmax([1, 2, np.nan, np.inf])inf nanmin ( a , axis=None , out=None , keepdims=False , **kwargs ) Return minimum of an array or minimum along an axis, ignoring any NaNs. When all-NaN slices are en-countered a RuntimeWarning is raised and Nan is returned for that slice.LAX-backend implementation of nanmin() . ADDITIONOriginal docstring below.LAX-backend implementation of nanmin() . Original docstring below. Returns nanmin – An array with the same shape as a , with the specified axis removed. If a is a 0-darray, or if axis is None, an ndarray scalar is returned. The same dtype as a is returned. Return type ndarray See also: nanmax() The maximum value of an array along a given axis, ignoring any NaNs. amin() The minimum value of an array along a given axis, propagating any NaNs. fmin() Element-wise minimum of two arrays, ignoring any NaNs. minimum() Element-wise minimum of two arrays, propagating any NaNs. isnan() Shows which elements are Not a Number (NaN). isfinite() Shows which elements are neither NaN nor infinity. amax() , fmax() , maximum() Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not aNumber is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity istreated as a very small (i.e. negative) number.If the input has a integer type the function is equivalent to np.min. Examples >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanmin(a)1.0 >>> np.nanmin(a, axis=0)array([1., 2.]) >>> np.nanmin(a, axis=1)array([1., 3.]) When positive infinity and negative infinity are present: >>> np.nanmin([1, 2, np.nan, np.inf])1.0 >>> np.nanmin([1, 2, np.nan, np.NINF])-inf nanprod ( a , axis=None , out=None , keepdims=False , **kwargs ) Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.LAX-backend implementation of nanprod() . ADDITIONOriginal docstring below.LAX-backend implementation of nanprod() . Original docstring below.One is returned for slices that are all-NaN or empty.New in version 1.10.0. Returns nanprod – A new array holding the result is returned unless out is specified, in which caseit is returned. Return type ndarray See also: numpy.prod() Product across array propagating NaNs. isnan() Show which elements are NaN. Examples >>> np.nanprod(1)1 >>> np.nanprod([1])1 >>> np.nanprod([1, np.nan])1.0 >>> a = np.array([[1, 2], [3, np.nan]]) >>> np.nanprod(a)6.0 >>> np.nanprod(a, axis=0)array([3., 2.]) nansum ( a , axis=None , out=None , keepdims=False , **kwargs ) Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.LAX-backend implementation of nansum() . ADDITIONOriginal docstring below.LAX-backend implementation of nansum() . Original docstring below.In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or empty. In later versions zero isreturned. Returns nansum – A new array holding the result is returned unless out is specified, in which it isreturned. The result has the same size as a , and the same shape as a if axis is not None or a is a1-d array. Return type ndarray. See also: numpy.sum() Sum across array propagating NaNs. isnan() Show which elements are NaN. isfinite() Show which elements are not NaN or +/-inf. 120 Chapter 2. APIymjax, Release 0.0.1Notes If both positive and negative infinity are present, the sum will be Not A Number (NaN). Examples >>> np.nansum(1)1 >>> np.nansum([1])1 >>> np.nansum([1, np.nan])1.0 >>> a = np.array([[1, 1], [1, np.nan]]) >>> np.nansum(a)3.0 >>> np.nansum(a, axis=0)array([2., 1.]) >>> np.nansum([1, np.nan, np.inf])inf >>> np.nansum([1, np.nan, np.NINF])-inf >>> from numpy.testing import suppress_warnings >>> with suppress_warnings() as sup: ... sup.filter(RuntimeWarning) ... np.nansum([1, np.nan, np.inf, -np.inf]) nan nonzero ( a ) Return the indices of the elements that are non-zero.LAX-backend implementation of nonzero() . ADDITIONOriginal docstring below.LAX-backend implementation of nonzero() . At present, JAX does not support JIT-compilation of jax.numpy.nonzero() because its output shape is data-dependent.Original docstring below.Returns a tuple of arrays, one for each dimension of a , containing the indices of the non-zero elements in thatdimension. The values in a are always tested and returned in row-major, C-style order.To group the indices by element, rather than dimension, use argwhere , which returns a row for each non-zeroelement. Note: When called on a zero-d array or scalar, nonzero(a) is treated as nonzero(atleast1d(a)) .Deprecated since version 1.17.0: Use atleast1d explicitly if this behavior is deliberate. Returns tuple_of_arrays – Indices of elements that are non-zero. Return type tuple See also: flatnonzero() Return indices that are non-zero in the flattened version of the input array. ndarray.nonzero() Equivalent ndarray method. count_nonzero() Counts the number of non-zero elements in the input array. While the nonzero values can be obtained with a[nonzero(a)] , it is recommended to use x[x.astype(bool)] or x[x != 0] instead, which will correctly handle 0-d arrays. Examples >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) >>> xarray([[3, 0, 0],[0, 4, 0],[5, 6, 0]]) >>> np.nonzero(x)(array([0, 1, 2, 2]), array([0, 1, 0, 1])) >>> x[np.nonzero(x)]array([3, 4, 5, 6]) >>> np.transpose(np.nonzero(x))array([[0, 0],[1, 1],[2, 0],[2, 1]]) A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a , thecondition a > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the a where the condition is true. >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a > 3array([[False, False, False],[ True, True, True],[ True, True, True]]) >>> np.nonzero(a > 3)(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) Using this result to index a is equivalent to using the mask directly: >>> a[np.nonzero(a > 3)]array([4, 5, 6, 7, 8, 9]) >>> a[a > 3] array([4, 5, 6, 7, 8, 9]) nonzero can also be called as a method of the array. >>> (a > 3).nonzero()(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) not_equal ( x1 , x2 ) Return (x1 != x2) element-wise.LAX-backend implementation of not_equal() . ADDITIONOriginal docstring below.LAX-backend implementation of not_equal() . Original docstring below.not_equal(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) 122 Chapter 2. APIymjax, Release 0.0.1 Returns out – Output array, element-wise comparison of x1 and x2 . Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar See also: equal() , greater() , greater_equal() , less() , less_equal() Examples >>> np.not_equal([1.,2.], [1., 3.])array([False, True]) >>> np.not_equal([1, 2], [[1, 3],[1, 4]])array([[False, True],[False, True]]) ones ( shape , dtype=None ) Return a new array of given shape and type, filled with ones.LAX-backend implementation of ones() . ADDITIONOriginal docstring below.LAX-backend implementation of ones() . Original docstring below. Parameters • shape ( int or sequence of ints ) – Shape of the new array, e.g., (2, 3) or .• dtype ( data-type, optional ) – The desired data-type for the array, e.g., numpy.int8 . Default is numpy.float64 . Returns out – Array of ones with the given shape, dtype, and order. Return type ndarray See also: ones_like() Return an array of ones with shape and type of input. empty() Return a new uninitialized array. zeros() Return a new array setting values to zero. full() Return a new array of given shape filled with value. Examples >>> np.ones(5)array([1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=int)array([1, 1, 1, 1, 1]) >>> np.ones((2, 1))array([[1.],[1.]]) >>> s = (2,2) >>> np.ones(s)array([[1., 1.],[1., 1.]]) ones_like ( x , dtype=None ) Return an array of ones with the same shape and type as a given array.LAX-backend implementation of ones_like() . ADDITIONOriginal docstring below.LAX-backend implementation of ones_like() . Original docstring below. Parameters dtype ( data-type, optional ) – Overrides the data type of the result. Returns out – Array of ones with the same shape and type as a . Return type ndarray See also: empty_like() Return an empty array with shape and type of input. zeros_like() Return an array of zeros with shape and type of input. full_like() Return a new array with shape of input filled with value. ones() Return a new array setting values to one. Examples >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> xarray([[0, 1, 2],[3, 4, 5]]) >>> np.ones_like(x)array([[1, 1, 1],[1, 1, 1]]) >>> y = np.arange(3, dtype=float) >>> yarray([0., 1., 2.]) >>> np.ones_like(y)array([1., 1., 1.]) outer ( a , b , out=None ) Compute the outer product of two vectors.LAX-backend implementation of outer() . ADDITIONOriginal docstring below.LAX-backend implementation of outer() . Original docstring below.Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN] , the outer product [1]_ is: [[a0*b0 a0*b1 ... a0*bN ][a1*b0 .[ ... .[aM*b0 aM*bN ]] 124 Chapter 2. APIymjax, Release 0.0.1 Returns out – out[i, j] = a[i] * b[j] Return type (M, N) ndarray See also: inner() einsum() einsum('i,j->ij', a.ravel(), b.ravel()) is the equivalent. ufunc.outer() A generalization to N dimensions and other operations. np.multiply.outer(a.ravel(), b.ravel()) is the equivalent. ReferencesExamples Make a ( very coarse) grid for computing a Mandelbrot set: >>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5)) >>> rlarray([[-2., -1., 0., 1., 2.],[-2., -1., 0., 1., 2.],[-2., -1., 0., 1., 2.],[-2., -1., 0., 1., 2.],[-2., -1., 0., 1., 2.]]) >>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,))) >>> imarray([[0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],[0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],[0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],[0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]]) >>> grid = rl + im >>> gridarray([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],[-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],[-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],[-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],[-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]]) An example using a “vector” of letters: >>> x = np.array(['a', 'b', 'c'], dtype=object) >>> np.outer(x, [1, 2, 3])array([['a', 'aa', 'aaa'],['b', 'bb', 'bbb'],['c', 'cc', 'ccc']], dtype=object) pad ( array , pad_width , mode='constant' , constant_values=0 ) Pad an array.LAX-backend implementation of pad() . ADDITIONOriginal docstring below.LAX-backend implementation of pad() . Original docstring below. Returns pad – Padded array of rank equal to array with shape increased according to pad_width . Return type ndarray New in version 1.7.0.For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previousaxes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated byusing padded values from the first axis.The padding function, if used, should modify a rank 1 array in-place. It has the following signature: padding_func(vector, iaxis_pad_width, iaxis, kwargs) where vector [ndarray] A rank 1 array already padded with zeros. Padded values are vec-tor[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:]. iaxis_pad_width [tuple] A 2-tuple of ints, iaxis_pad_width[0] represents the number of valuespadded at the beginning of vector where iaxis_pad_width[1] represents the number of valuespadded at the end of vector. iaxis [int] The axis currently being calculated. kwargs [dict] Any keyword arguments the function requires. Examples >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))array([4, 4, 1, ..., 6, 6, 6]) >>> np.pad(a, (2, 3), 'edge')array([1, 1, 1, ..., 5, 5, 5]) >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) >>> np.pad(a, (2,), 'maximum')array([5, 5, 1, 2, 3, 4, 5, 5, 5]) >>> np.pad(a, (2,), 'mean')array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> np.pad(a, (2,), 'median')array([3, 3, 1, 2, 3, 4, 5, 3, 3]) >>> a = [[1, 2], [3, 4]] >>> np.pad(a, ((3, 2), (2, 3)), 'minimum')array([[1, 1, 1, 2, 1, 1, 1],[1, 1, 1, 2, 1, 1, 1],[1, 1, 1, 2, 1, 1, 1],[1, 1, 1, 2, 1, 1, 1],[3, 3, 3, 4, 3, 3, 3],[1, 1, 1, 2, 1, 1, 1],[1, 1, 1, 2, 1, 1, 1]]) 126 Chapter 2. APIymjax, Release 0.0.1 >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect')array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) >>> np.pad(a, (2, 3), 'symmetric')array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) >>> np.pad(a, (2, 3), 'wrap')array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) >>> def pad_with(vector, pad_width, iaxis, kwargs): ... pad_value = kwargs.get('padder', 10) ... vector[:pad_width[0]] = pad_value ... vector[-pad_width[1]:] = pad_value >>> a = np.arange(6) >>> a = a.reshape((2, 3)) >>> np.pad(a, 2, pad_with)array([[10, 10, 10, 10, 10, 10, 10],[10, 10, 10, 10, 10, 10, 10],[10, 10, 0, 1, 2, 10, 10],[10, 10, 3, 4, 5, 10, 10],[10, 10, 10, 10, 10, 10, 10],[10, 10, 10, 10, 10, 10, 10]]) >>> np.pad(a, 2, pad_with, padder=100)array([[100, 100, 100, 100, 100, 100, 100],[100, 100, 100, 100, 100, 100, 100],[100, 100, 0, 1, 2, 100, 100],[100, 100, 3, 4, 5, 100, 100],[100, 100, 100, 100, 100, 100, 100],[100, 100, 100, 100, 100, 100, 100]]) percentile ( a , q , axis=None , out=None , overwrite_input=False , interpolation='linear' , keepdims=False ) Compute the q-th percentile of the data along the specified axis.LAX-backend implementation of percentile() . ADDITIONOriginal docstring below.LAX-backend implementation of percentile() . Original docstring below.Returns the q-th percentile(s) of the array elements. Returns percentile – If q is a single percentile and axis=None , then the result is a scalar. If multiplepercentiles are given, first axis of the result corresponds to the percentiles. The other axes arethe axes that remain after the reduction of a . If the input contains integers or floats smaller than float64 , the output data-type is float64 . Otherwise, the output data-type is the same asthat of the input. If out is specified, that array is returned instead. Return type scalar or ndarray See also: mean() median() equivalent to percentile(..., 50) nanpercentile() quantile() equivalent to percentile, except with q in the range [0, 1]. Notes Given a vector V of length N , the q-th percentile of V is the value q/100 of the way from the minimum tothe maximum in a sorted copy of V . The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the percentile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=50 , the same as the minimum if q=0 and the same asthe maximum if q=100 . Examples >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> aarray([[10, 7, 4],[ 3, 2, 1]]) >>> np.percentile(a, 50)3.5 >>> np.percentile(a, 50, axis=0)array([6.5, 4.5, 2.5]) >>> np.percentile(a, 50, axis=1)array([7., 2.]) >>> np.percentile(a, 50, axis=1, keepdims= True )array([[7.],[2.]]) >>> m = np.percentile(a, 50, axis=0) >>> out = np.zeros_like(m) >>> np.percentile(a, 50, axis=0, out=out)array([6.5, 4.5, 2.5]) >>> marray([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.percentile(b, 50, axis=1, overwrite_input= True )array([7., 2.]) >>> assert not np.all(a == b) The different types of interpolation can be visualized graphically: polyval ( p , x ) Evaluate a polynomial at specific values.LAX-backend implementation of polyval() . ADDITIONOriginal docstring below.LAX-backend implementation of polyval() . Original docstring below.If p is of length N, this function returns the value: p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1] If x is a sequence, then p(x) is returned for each element of x . If x is another polynomial then the compositepolynomial p(x(t)) is returned. Returns values – If x is a poly1d instance, the result is the composition of the two polynomials, i.e., x is “substituted” in p and the simplified result is returned. In addition, the type of x - array_like 128 Chapter 2. APIymjax, Release 0.0.1 L i s t i t e m r e t u r n e d Interpolation methods for list: [0 1 2 3] linearhigherlowernearestmidpoint or poly1d - governs the type of the output: x array_like => values array_like, x a poly1d object=> values is also. Return type ndarray or poly1d See also: poly1d() A polynomial class. Notes Horner’s scheme [1]_ is used to evaluate the polynomial. Even so, for polynomials of high degree the valuesmay be inaccurate due to rounding errors. Use carefully.If x is a subtype of ndarray the return value will be of the same type. ReferencesExamples >>> np.polyval([3,0,1], 5) >>> np.polyval([3,0,1], np.poly1d(5))poly1d([76.]) >>> np.polyval(np.poly1d([3,0,1]), 5)76 >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))poly1d([76.]) power ( x1 , x2 ) First array elements raised to powers from second array, element-wise.LAX-backend implementation of power() . ADDITIONOriginal docstring below.LAX-backend implementation of power() . Original docstring below.power(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signa-ture, extobj])Raise each base in x1 to the positionally-corresponding power in x2 . x1 and x2 must be broadcastable to thesame shape. Note that an integer type raised to a negative integer power will raise a ValueError. Returns y – The bases in x1 raised to the exponents in x2 . This is a scalar if both x1 and x2 arescalars. Return type ndarray See also: float_power() power function that promotes integers to float 130 Chapter 2. APIymjax, Release 0.0.1Examples Cube each element in a list. >>> x1 = range(6) >>> x1[0, 1, 2, 3, 4, 5] >>> np.power(x1, 3)array([ 0, 1, 8, 27, 64, 125]) Raise the bases to different exponents. >>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0] >>> np.power(x1, x2)array([ 0., 1., 8., 27., 16., 5.]) The effect of broadcasting. >>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]]) >>> x2array([[1, 2, 3, 3, 2, 1],[1, 2, 3, 3, 2, 1]]) >>> np.power(x1, x2)array([[ 0, 1, 8, 27, 16, 5],[ 0, 1, 8, 27, 16, 5]]) positive ( x ) Numerical positive, element-wise.LAX-backend implementation of positive() . ADDITIONOriginal docstring below.LAX-backend implementation of positive() . Original docstring below.positive(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])New in version 1.13.0. Returns y – Returned array or scalar: y = +x . This is a scalar if x is a scalar. Return type ndarray or scalar Notes Equivalent to x.copy() , but only defined for types that support arithmetic. prod ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the product of array elements over a given axis.LAX-backend implementation of prod() . ADDITIONOriginal docstring below.LAX-backend implementation of prod() . Original docstring below. Parameters dtype ( dtype, optional ) – The type of the returned array, as well as of theaccumulator in which the elements are multiplied. The dtype of a is used by default unless a hasan integer dtype of less precision than the default platform integer. In that case, if a is signedthen the platform integer is used while if a is unsigned then an unsigned integer of the sameprecision as the platform integer is used. Returns product_along_axis – An array shaped as a but with the specified axis removed. Returnsa reference to out if specified. Return type ndarray, see dtype parameter above. See also: ndarray.prod() equivalent method ufuncs-output-type() Notes Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bitplatform: >>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x)16 The product of an empty array is the neutral element 1: >>> np.prod([])1.0 Examples By default, calculate the product of all elements: >>> np.prod([1.,2.])2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]])24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1)array([ 2., 12.]) Or select specific elements to include: >>> np.prod([1., np.nan, 3.], where=[ True , False , True ])3.0 If the type of x is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uintTrue If x is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == intTrue 132 Chapter 2. APIymjax, Release 0.0.1 You can also start the product with a value other than one: >>> np.prod([1, 2], initial=5)10 product ( a , axis=None , dtype=None , out=None , keepdims=False ) Return the product of array elements over a given axis.LAX-backend implementation of prod() . ADDITIONOriginal docstring below.LAX-backend implementation of prod() . Original docstring below. Parameters dtype ( dtype, optional ) – The type of the returned array, as well as of theaccumulator in which the elements are multiplied. The dtype of a is used by default unless a hasan integer dtype of less precision than the default platform integer. In that case, if a is signedthen the platform integer is used while if a is unsigned then an unsigned integer of the sameprecision as the platform integer is used. Returns product_along_axis – An array shaped as a but with the specified axis removed. Returnsa reference to out if specified. Return type ndarray, see dtype parameter above. See also: ndarray.prod() equivalent method ufuncs-output-type() Notes Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bitplatform: >>> x = np.array([536870910, 536870910, 536870910, 536870910]) >>> np.prod(x)16 The product of an empty array is the neutral element 1: >>> np.prod([])1.0 Examples By default, calculate the product of all elements: >>> np.prod([1.,2.])2.0 Even when the input array is two-dimensional: >>> np.prod([[1.,2.],[3.,4.]])24.0 But we can also specify the axis over which to multiply: >>> np.prod([[1.,2.],[3.,4.]], axis=1)array([ 2., 12.]) Or select specific elements to include: >>> np.prod([1., np.nan, 3.], where=[ True , False , True ])3.0 If the type of x is unsigned, then the output type is the unsigned platform integer: >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uintTrue If x is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == intTrue You can also start the product with a value other than one: >>> np.prod([1, 2], initial=5)10 promote_types ( a , b ) Returns the type to which a binary operation should cast its arguments.LAX-backend implementation of promote_types() . ADDITIONOriginal docstring below.Returns: A numpy.dtype object. quantile ( a , q , axis=None , out=None , overwrite_input=False , interpolation='linear' , keepdims=False ) Compute the q-th quantile of the data along the specified axis.New in version 1.15.0.LAX-backend implementation of quantile() . ADDITIONOriginal docstring below.LAX-backend implementation of quantile() . Original docstring below. Returns quantile – If q is a single quantile and axis=None , then the result is a scalar. If multiplequantiles are given, first axis of the result corresponds to the quantiles. The other axes are theaxes that remain after the reduction of a . If the input contains integers or floats smaller than float64 , the output data-type is float64 . Otherwise, the output data-type is the same asthat of the input. If out is specified, that array is returned instead. Return type scalar or ndarray See also: mean() percentile() equivalent to quantile, but with q in the range [0, 100]. median() equivalent to quantile(..., 0.5)nanquantile() 134 Chapter 2. APIymjax, Release 0.0.1Notes Given a vector V of length N , the q-th quantile of V is the value q of the way from the minimum to the maximumin a sorted copy of V . The values and distances of the two nearest neighbors as well as the interpolation parameterwill determine the quantile if the normalized ranking does not match the location of q exactly. This function isthe same as the median if q=0.5 , the same as the minimum if q=0.0 and the same as the maximum if q=1.0 . Examples >>> a = np.array([[10, 7, 4], [3, 2, 1]]) >>> aarray([[10, 7, 4],[ 3, 2, 1]]) >>> np.quantile(a, 0.5)3.5 >>> np.quantile(a, 0.5, axis=0)array([6.5, 4.5, 2.5]) >>> np.quantile(a, 0.5, axis=1)array([7., 2.]) >>> np.quantile(a, 0.5, axis=1, keepdims= True )array([[7.],[2.]]) >>> m = np.quantile(a, 0.5, axis=0) >>> out = np.zeros_like(m) >>> np.quantile(a, 0.5, axis=0, out=out)array([6.5, 4.5, 2.5]) >>> marray([6.5, 4.5, 2.5]) >>> b = a.copy() >>> np.quantile(b, 0.5, axis=1, overwrite_input= True )array([7., 2.]) >>> assert not np.all(a == b) rad2deg ( x ) Convert angles from radians to degrees.LAX-backend implementation of rad2deg() . ADDITIONOriginal docstring below.LAX-backend implementation of rad2deg() . Original docstring below.rad2deg(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The corresponding angle in degrees. This is a scalar if x is a scalar. Return type ndarray See also: deg2rad() Convert angles from degrees to radians. unwrap() Remove large jumps in angle by wrapping. New in version 1.3.0.rad2deg(x) is 180 * x / pi . Examples >>> np.rad2deg(np.pi/2)90.0 radians ( x ) Convert angles from degrees to radians.LAX-backend implementation of deg2rad() . ADDITIONOriginal docstring below.LAX-backend implementation of deg2rad() . Original docstring below.deg2rad(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – The corresponding angle in radians. This is a scalar if x is a scalar. Return type ndarray See also: rad2deg() Convert angles from radians to degrees. unwrap() Remove large jumps in angle by wrapping. Notes New in version 1.3.0. deg2rad(x) is x * pi / 180 . Examples >>> np.deg2rad(180)3.1415926535897931 ravel ( a , order='C' ) Return a contiguous flattened array.LAX-backend implementation of ravel() . ADDITIONOriginal docstring below.LAX-backend implementation of ravel() . Original docstring below.A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked arraywill be returned for a masked array input) Returns y – y is an array of the same subtype as a , with shape (a.size,) . Note that matrices arespecial cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray. Return type array_like See also: 136 Chapter 2. APIymjax, Release 0.0.1 ndarray.flat() ndarray.flatten() ndarray.reshape() Change the shape of an array without changing its data. Notes In row-major, C-style order, in two dimensions, the row index varies the slowest, and the column index thequickest. This can be generalized to multiple dimensions, where row-major order implies that the index alongthe first axis varies slowest, and the index along the last quickest. The opposite holds for column-major, Fortran-style index ordering.When a view is desired in as many cases as possible, arr.reshape(-1) may be preferable. Examples It is equivalent to reshape(-1, order=order) . >>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.ravel(x)array([1, 2, 3, 4, 5, 6]) >>> x.reshape(-1)array([1, 2, 3, 4, 5, 6]) >>> np.ravel(x, order='F')array([1, 4, 2, 5, 3, 6]) When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering: >>> np.ravel(x.T)array([1, 4, 2, 5, 3, 6]) >>> np.ravel(x.T, order='A')array([1, 2, 3, 4, 5, 6]) When order is ‘K’, it will preserve orderings that are neither ‘C’ nor ‘F’, but won’t reverse axes: >>> a = np.arange(3)[::-1]; aarray([2, 1, 0]) >>> a.ravel(order='C')array([2, 1, 0]) >>> a.ravel(order='K')array([2, 1, 0]) >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); aarray([[[ 0, 2, 4],[ 1, 3, 5]],[[ 6, 8, 10],[ 7, 9, 11]]]) >>> a.ravel(order='C')array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11]) >>> a.ravel(order='K')array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) real ( val ) Return the real part of the complex argument.LAX-backend implementation of real() . ADDITIONOriginal docstring below.LAX-backend implementation of real() . Original docstring below. Returns out – The real component of the complex argument. If val is real, the type of val is usedfor the output. If val has complex elements, the returned type is float. Return type ndarray or scalar See also: real_if_close() , imag() , angle() Examples >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.realarray([1., 3., 5.]) >>> a.real = 9 >>> aarray([9.+2.j, 9.+4.j, 9.+6.j]) >>> a.real = np.array([9, 8, 7]) >>> aarray([9.+2.j, 8.+4.j, 7.+6.j]) >>> np.real(1 + 1j)1.0 remainder ( x1 , x2 ) Return element-wise remainder of division.LAX-backend implementation of remainder() . ADDITIONOriginal docstring below.LAX-backend implementation of remainder() . Original docstring below.remainder(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj])Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modu-lus operator``x1 % x2`` and has the same sign as the divisor x2 . The MATLAB function equivalent to np.remainder is mod . Warning: This should not be confused with:• Python 3.7’s math.remainder and C’s remainder , which computes the IEEE remainder, which arethe complement to round(x1 / x2) .• The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2) . Returns y – The element-wise remainder of the quotient floor_divide(x1, x2) . This is ascalar if both x1 and x2 are scalars. Return type ndarray See also: floor_divide() Equivalent of Python // operator. 138 Chapter 2. APIymjax, Release 0.0.1 divmod() Simultaneous floor division and remainder. fmod() Equivalent of the MATLAB rem function. divide() , floor() Notes Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder . Examples >>> np.remainder([4, 7], [2, 3])array([0, 1]) >>> np.remainder(np.arange(7), 5)array([0, 1, 2, 3, 4, 0, 1]) repeat ( a , repeats , axis=None ) Repeat elements of an array.LAX-backend implementation of repeat() . ADDITIONOriginal docstring below.LAX-backend implementation of repeat() . Original docstring below. Returns repeated_array – Output array which has the same shape as a , except along the given axis. Return type ndarray See also: tile() Tile an array. Examples >>> np.repeat(3, 4)array([3, 3, 3, 3]) >>> x = np.array([[1,2],[3,4]]) >>> np.repeat(x, 2)array([1, 1, 2, 2, 3, 3, 4, 4]) >>> np.repeat(x, 3, axis=1)array([[1, 1, 1, 2, 2, 2],[3, 3, 3, 4, 4, 4]]) >>> np.repeat(x, [1, 2], axis=0)array([[1, 2],[3, 4],[3, 4]]) reshape ( a , newshape , order='C' ) Gives a new shape to an array without changing its data.LAX-backend implementation of reshape() . ADDITIONOriginal docstring below.LAX-backend implementation of reshape() . Original docstring below. Returns reshaped_array – This will be a new view object if possible; otherwise, it will be a copy.Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returnedarray. Return type ndarray See also: ndarray.reshape() Equivalent method. Notes It is not always possible to change the shape of an array without copying the data. If you want an error to beraised when the data is copied, you should assign the new shape to the shape attribute of the array: >>> a = np.zeros((10, 2)) >>> b = a.T >>> c = b.view() >>> c.shape = (20)Traceback (most recent call last): ... AttributeError: incompatible shape for a non-contiguous array The order keyword gives the index ordering both for fetching the values from a , and then placing the values intothe output array. For example, let’s say you have an array: >>> a = np.arange(6).reshape((3, 2)) >>> aarray([[0, 1],[2, 3],[4, 5]]) You can think of reshaping as first raveling the array (using the given index order), then inserting the elementsfrom the raveled array into the new array using the same kind of index ordering as was used for the raveling. >>> np.reshape(a, (2, 3)) array([[0, 1, 2],[3, 4, 5]]) >>> np.reshape(np.ravel(a), (2, 3)) array([[0, 1, 2],[3, 4, 5]]) >>> np.reshape(a, (2, 3), order='F') array([[0, 4, 3],[2, 1, 5]]) >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')array([[0, 4, 3],[2, 1, 5]]) 140 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, 6)array([1, 2, 3, 4, 5, 6]) >>> np.reshape(a, 6, order='F')array([1, 4, 2, 5, 3, 6]) >>> np.reshape(a, (3,-1)) array([[1, 2],[3, 4],[5, 6]]) roll ( a , shift , axis=None ) Roll array elements along a given axis.LAX-backend implementation of roll() . ADDITIONOriginal docstring below.LAX-backend implementation of roll() . Original docstring below.Elements that roll beyond the last position are re-introduced at the first. Returns res – Output array, with the same shape as a . Return type ndarray See also: rollaxis() Roll the specified axis backwards, until it lies in a given position. Notes New in version 1.12.0.Supports rolling over multiple dimensions simultaneously. Examples >>> x = np.arange(10) >>> np.roll(x, 2)array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2)array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) >>> x2 = np.reshape(x, (2,5)) >>> x2array([[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]]) >>> np.roll(x2, 1)array([[9, 0, 1, 2, 3],[4, 5, 6, 7, 8]]) >>> np.roll(x2, -1)array([[1, 2, 3, 4, 5],[6, 7, 8, 9, 0]]) >>> np.roll(x2, 1, axis=0)array([[5, 6, 7, 8, 9], (continues on next page) (continued from previous page) [0, 1, 2, 3, 4]]) >>> np.roll(x2, -1, axis=0)array([[5, 6, 7, 8, 9],[0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1)array([[4, 0, 1, 2, 3],[9, 5, 6, 7, 8]]) >>> np.roll(x2, -1, axis=1)array([[1, 2, 3, 4, 0],[6, 7, 8, 9, 5]]) rot90 ( m , k=1 , axes=0, 1 ) Rotate an array by 90 degrees in the plane specified by axes.LAX-backend implementation of rot90() . ADDITIONOriginal docstring below.LAX-backend implementation of rot90() . Original docstring below.Rotation direction is from the first towards the second axis. Returns y – A rotated view of m . Return type ndarray See also: flip() Reverse the order of elements in an array along the given axis. fliplr() Flip an array horizontally. flipud() Flip an array vertically. Notes rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1)) rot90(m, k=1, axes=(1,0)) is equivalent torot90(m, k=-1, axes=(0,1)) Examples >>> m = np.array([[1,2],[3,4]], int) >>> marray([[1, 2],[3, 4]]) >>> np.rot90(m)array([[2, 4],[1, 3]]) >>> np.rot90(m, 2)array([[4, 3],[2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2))array([[[1, 3],[0, 2]],[[5, 7],[4, 6]]]) 142 Chapter 2. APIymjax, Release 0.0.1 round ( a , decimals=0 ) Round an array to the given number of decimals.LAX-backend implementation of round_() . ADDITIONOriginal docstring below.LA row_stack ( tup ) Stack arrays in sequence vertically (row wise).LAX-backend implementation of vstack() . ADDITIONOriginal docstring below.LAX-backend implementation of vstack() . Original docstring below.This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N) .Rebuilds arrays divided by vsplit .This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height(first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate , stack and block provide more general stacking and concatenation operations. Returns stacked – The array formed by stacking the given arrays, will be at least 2-D. Return type ndarray See also: stack() Join a sequence of arrays along a new axis. hstack() Stack arrays in sequence horizontally (column wise). dstack() Stack arrays in sequence depth wise (along third dimension). concatenate() Join a sequence of arrays along an existing axis. vsplit() Split array into a list of multiple sub-arrays vertically. block() Assemble arrays from blocks. Examples >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a,b))array([[1, 2, 3],[2, 3, 4]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a,b))array([[1],[2],[3],[2],[3],[4]]) sign ( x ) Returns an element-wise indication of the sign of a number.LAX-backend implementation of sign() . ADDITIONOriginal docstring below. LAX-backend implementation of sign() . Original docstring below.sign(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj])The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0 . nan is returned for nan inputs.For complex inputs, the sign function returns sign(x.real) + 0j if x.real != 0 elsesign(x.imag) + 0j .complex(nan, 0) is returned for complex nan inputs. Returns y – The sign of x . This is a scalar if x is a scalar. Return type ndarray Notes There is more than one definition of sign in common use for complex numbers. The definition used here isequivalent to 𝑥/ √ 𝑥 * 𝑥 which is different from a common alternative, 𝑥/ | 𝑥 | . Examples >>> np.sign([-5., 4.5])array([-1., 1.]) >>> np.sign(0)0 >>> np.sign(5-2j)(1+0j) signbit ( x ) Returns element-wise True where signbit is set (less than zero).LAX-backend implementation of signbit() . ADDITIONOriginal docstring below.LAX-backend implementation of signbit() . Original docstring below.signbit(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns result – Output array, or reference to out if that was supplied. This is a scalar if x is a scalar. Return type ndarray of bool Examples >>> np.signbit(-1.2)True >>> np.signbit(np.array([1, -2.3, 2.1]))array([False, True, False]) sin ( x ) Trigonometric sine, element-wise.LAX-backend implementation of sin() . ADDITIONOriginal docstring below.LAX-backend implementation of sin() . Original docstring below. 144 Chapter 2. APIymjax, Release 0.0.1 sin(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, ex-tobj]) Returns y – The sine of each element of x. This is a scalar if x is a scalar. Return type array_like See also: arcsin() , sinh() , cos() Notes The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Considera circle of radius 1 centered on the origin. A ray comes in from the + 𝑥 axis, makes an angle at the origin(measured counter-clockwise from that axis), and departs from the origin. The 𝑦 coordinate of the outgoingray’s intersection with the unit circle is the sine of that angle. It ranges from -1 for 𝑥 = 3 𝜋/ to +1 for 𝜋/ . The function has zeroes where the angle is a multiple of 𝜋 . Sines of angles between 𝜋 and 𝜋 are negative. Thenumerous properties of the sine and related functions are included in any standard trigonometry text. Examples Print sine of one angle: >>> np.sin(np.pi/2.)1.0 Print sines of an array of angles given in degrees: >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ]) Plot the sine function: >>> import matplotlib.pylab as plt>>> x = np.linspace(-np.pi, np.pi, 201) >>> plt.plot(x, np.sin(x)) >>> plt.xlabel('Angle [rad]') >>> plt.ylabel('sin(x)') >>> plt.axis('tight') >>> plt.show() sinc ( x ) Return the sinc function.LAX-backend implementation of sinc() . ADDITIONOriginal docstring below.LAX-backend implementation of sinc() . Original docstring below.The sinc function is sin( 𝜋𝑥 ) / ( 𝜋𝑥 ) . Returnsout [ndarray] sinc(x) , which has the same shape as the input. sinc(0) is the limit value 1.The name sinc is short for “sine cardinal” or “sinus cardinalis”. The sinc function is used in various signal processing applications, including in anti-aliasing, inthe construction of a Lanczos resampling filter, and in interpolation.For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is propor-tional to the sinc function. >>> import matplotlib.pyplot as plt>>> x = np.linspace(-4, 4, 41) >>> np.sinc(x)array([-3.89804309e-17, -4.92362781e-02, -8.40918587e-02, ˓ → vary -8.90384387e-02, -5.84680802e-02, 3.89804309e-17,6.68206631e-02, 1.16434881e-01, 1.26137788e-01,8.50444803e-02, -3.89804309e-17, -1.03943254e-01,-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,3.89804309e-17, 2.33872321e-01, 5.04551152e-01,7.56826729e-01, 9.35489284e-01, 1.00000000e+00,9.35489284e-01, 7.56826729e-01, 5.04551152e-01,2.33872321e-01, 3.89804309e-17, -1.55914881e-01,-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,1.16434881e-01, 6.68206631e-02, 3.89804309e-17,-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,-4.92362781e-02, -3.89804309e-17]) >>> plt.plot(x, np.sinc(x))[ 146 Chapter 2. APIymjax, Release 0.0.1Notes If out is provided, the function writes the result into it, and returns a reference to out . (See Examples) References M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. Examples >>> np.sinh(0)0.0 >>> np.sinh(np.pi*1j/2)1j >>> np.sinh(np.pi*1j) >>> >>> >>> out1 = np.array([0], dtype='d') >>> out2 = np.sinh([0.1], out1) >>> out2 is out1True >>> >>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))Traceback (most recent call last):File " Returns sorted_array – Array of the same type and shape as a . Return type ndarray See also: ndarray.sort() Method to sort an array in-place. argsort() Indirect sort. lexsort() Indirect stable sort on multiple keys. searchsorted() Find elements in a sorted array. partition() Partial sort. The various sorting algorithms are characterized by their average speed, worst case performance, work spacesize, and whether they are stable. A stable sort keeps items with the same key in the same relative order. Thefour algorithms implemented in NumPy have the following properties: kind speed worst case work space stable ‘quicksort’ 1 O(n^2) 0 no‘heapsort’ 3 O(n*log(n)) 0 no‘mergesort’ 2 O(n*log(n)) ~n/2 yes‘timsort’ 2 O(n*log(n)) ~n/2 yes Note: The datatype determines which of ‘mergesort’ or ‘timsort’ is actually used, even if ‘mergesort’ is speci-fied. User selection at a finer scale is not currently available.All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently,sorting along the last axis is faster and uses less space than sorting along any other axis.The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then theorder is determined by the real parts except when they are equal, in which case the order is determined by theimaginary parts.Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. Innumpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:• Real: [R, nan]• Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]where R is a non-nan real value. Complex values with the same nan placements are sorted according to thenon-nan part if it exists. Non-nan values are sorted as before.New in version 1.12.0.quicksort has been changed to introsort. When sorting does not make enough progress it switches to heapsort.This implementation makes quicksort O(n*log(n)) in the worst case.‘stable’ automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with‘mergesort’ is currently mapped to timsort or radix sort depending on the data type. API forward compatibilitycurrently limits the ability to select the implementation and it is hardwired for the different data types.New in version 1.17.0.Timsort is added for better performance on already or nearly sorted data. On random data timsort is almostidentical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. Fortimsort details, refer to CPython listsort.txt. ‘mergesort’ and ‘stable’ are mapped to radix sort for integer datatypes. Radix sort is an O(n) sort instead of O(n log n).Changed in version 1.17.0.NaT now sorts to the end of arrays for consistency with NaN. 148 Chapter 2. APIymjax, Release 0.0.1Examples >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) array([[1, 4],[1, 3]]) >>> np.sort(a, axis= None ) array([1, 1, 3, 4]) >>> np.sort(a, axis=0) array([[1, 1],[3, 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) >>> np.sort(a, order='height')array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),('Lancelot', 1.8999999999999999, 38)],dtype=[('name', '|S10'), ('height', ' Sort by age, then height if ages are equal: >>> np.sort(a, order=['age', 'height'])array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),('Arthur', 1.8, 41)],dtype=[('name', '|S10'), ('height', ' Returns sub-arrays – A list of sub-arrays as views into ary . Return type list of ndarrays Raises ValueError – If indices_or_sections is given as an integer, but a split does not result inequal division. See also: array_split() Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an excep-tion if an equal division cannot be made. hsplit() Split array into multiple sub-arrays horizontally (column-wise). vsplit() Split array into multiple sub-arrays vertically (row wise). dsplit() Split array into multiple sub-arrays along the 3rd axis (depth). concatenate() Join a sequence of arrays along an existing axis. stack() Join a sequence of arrays along a new axis. hstack() Stack arrays in sequence horizontally (column wise). vstack() Stack arrays in sequence vertically (row wise). dstack() Stack arrays in sequence depth wise (along third dimension). Examples >>> x = np.arange(9.0) >>> np.split(x, 3)[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])] >>> x = np.arange(8.0) >>> np.split(x, [3, 5, 6, 10])[array([0., 1., 2.]),array([3., 4.]),array([5.]),array([6., 7.]),array([], dtype=float64)] sqrt ( x ) Return the non-negative square-root of an array, element-wise.LAX-backend implementation of sqrt() . ADDITIONOriginal docstring below.LAX-backend implementation of sqrt() . Original docstring below.sqrt(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns y – An array of the same shape as x , containing the positive square-root of each element in x . If any element in x is complex, a complex array is returned (and the square-roots of negativereals are calculated). If all of the elements in x are real, so is y , with negative elements returning nan . If out was provided, y is a reference to it. This is a scalar if x is a scalar. Return type ndarray See also: lib.scimath.sqrt() A version which returns complex numbers when given negative reals. Notes sqrt has–consistent with common convention–as its branch cut the real “interval” [ -inf , 0), and is continuousfrom above on it. A branch cut is a curve in the complex plane across which a given complex function fails tobe continuous. Examples >>> np.sqrt([1,4,9])array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J])array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, np.inf])array([ 2., nan, inf]) 150 Chapter 2. APIymjax, Release 0.0.1 square ( x ) Return the element-wise square of the input.LAX-backend implementation of square() . ADDITIONOriginal docstring below.LAX-backend implementation of square() . Original docstring below.square(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature,extobj]) Returns out – Element-wise x*x , of the same shape and dtype as x . This is a scalar if x is a scalar. Return type ndarray or scalar See also: numpy.linalg.matrix_power() , sqrt() , power() Examples >>> np.square([-1j, 1])array([-1.-0.j, 1.+0.j]) squeeze ( a , axis=None ) Remove single-dimensional entries from the shape of an array.LAX-backend implementation of squeeze() . ADDITIONOriginal docstring below.LAX-backend implementation of squeeze() . Original docstring below. Returns squeezed – The input array, but with all or a subset of the dimensions of length 1 removed.This is always a itself or a view into a . Return type ndarray Raises ValueError – If axis is not None, and an axis being squeezed is not of length 1 See also: expand_dims() The inverse operation, adding singleton dimensions reshape() Insert, remove, and combine dimensions, and resize existing ones Examples >>> x = np.array([[[0], [1], [2]]]) >>> x.shape(1, 3, 1) >>> np.squeeze(x).shape(3,) >>> np.squeeze(x, axis=0).shape(3, 1) >>> np.squeeze(x, axis=1).shapeTraceback (most recent call last): ... ValueError: cannot select an axis to squeeze out which has size not equal to one >>> np.squeeze(x, axis=2).shape(1, 3) stack ( arrays , axis=0 ) Join a sequence of arrays along a new axis.LAX-backend implementation of stack() . ADDITIONOriginal docstring below.LAX-backend implementation of stack() . Original docstring below.The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.New in version 1.10.0. Returns stacked – The stacked array has one more dimension than the input arrays. Return type ndarray See also: concatenate() Join a sequence of arrays along an existing axis. split() Split array into a list of multiple sub-arrays of equal size. block() Assemble arrays from blocks. Examples >>> arrays = [np.random.randn(3, 4) for _ in range(10)] >>> np.stack(arrays, axis=0).shape(10, 3, 4) >>> np.stack(arrays, axis=1).shape(3, 10, 4) >>> np.stack(arrays, axis=2).shape(3, 4, 10) >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.stack((a, b))array([[1, 2, 3],[2, 3, 4]]) >>> np.stack((a, b), axis=-1)array([[1, 2],[2, 3],[3, 4]]) std ( a , axis=None , dtype=None , out=None , ddof=0 , keepdims=False ) Compute the standard deviation along the specified axis.LAX-backend implementation of std() . ADDITIONOriginal docstring below.LAX-backend implementation of std() . Original docstring below.Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standarddeviation is computed for the flattened array by default, otherwise over the specified axis. Parameters dtype ( dtype, optional ) – Type to use in computing the standard deviation. Forarrays of integer type the default is float64, for arrays of float types it is the same as the arraytype. 152 Chapter 2. APIymjax, Release 0.0.1 Returns standard_deviation – If out is None, return a new array containing the standard deviation,otherwise return a reference to the output array. Return type ndarray, see dtype parameter above. See also: var() , mean() , nanmean() , nanstd() , nanvar() , ufuncs-output-type() Notes The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =sqrt(mean(abs(x - x.mean())**2)) .The average squared deviation is normally calculated as x.sum() / N , where N = len(x) . If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides anunbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimateof the variance for normally distributed variables. The standard deviation computed in this function is thesquare root of the estimated variance, so even with ddof=1 , it will not be an unbiased estimate of the standarddeviation per se.Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always realand nonnegative.For floating-point input, the std is computed using the same precision the input has. Depending on the inputdata, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a)1.1180339887498949 >>> np.std(a, axis=0)array([1., 1.]) >>> np.std(a, axis=1)array([0.5, 0.5]) In single precision, std() can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.std(a)0.45000005 Computing the standard deviation in float64 is more accurate: >>> np.std(a, dtype=np.float64)0.44999999925494177 subtract ( x1 , x2 ) Subtract arguments, element-wise.LAX-backend implementation of subtract() . ADDITIONOriginal docstring below.LAX-backend implementation of subtract() . Original docstring below. subtract(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, sig-nature, extobj]) Returns y – The difference of x1 and x2 , element-wise. This is a scalar if both x1 and x2 are scalars. Return type ndarray Notes Equivalent to x1 - x2 in terms of array broadcasting. Examples >>> np.subtract(1.0, 4.0)-3.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.subtract(x1, x2)array([[ 0., 0., 0.],[ 3., 3., 3.],[ 6., 6., 6.]]) sum ( a , axis=None , dtype=None , out=None , keepdims=False ) Sum of array elements over a given axis.LAX-backend implementation of sum() . ADDITIONOriginal docstring below.LAX-backend implementation of sum() . Original docstring below. Parameters dtype ( dtype, optional ) – The type of the returned array and of the accumulatorin which the elements are summed. The dtype of a is used by default unless a has an integerdtype of less precision than the default platform integer. In that case, if a is signed then theplatform integer is used while if a is unsigned then an unsigned integer of the same precision asthe platform integer is used. Returns sum_along_axis – An array with the same shape as a , with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a referenceto out is returned. Return type ndarray See also: ndarray.sum() Equivalent method. add.reduce() Equivalent functionality of add . cumsum() Cumulative sum of array elements. trapz() Integration of array values using the composite trapezoidal rule. mean() , average() 154 Chapter 2. APIymjax, Release 0.0.1Notes Arithmetic is modular when using integer types, and no error is raised on overflow.The sum of an empty array is the neutral element 0: >>> np.sum([])0.0 For floating point numbers the numerical precision of sum (and np.add.reduce ) is in general limited bydirectly adding each number individually to the result causing rounding errors in every step. However, oftennumpy will use a numerically better approach (partial pairwise summation) leading to improved precision inmany use-cases. This improved precision is always provided when no axis is given. When axis is given, itwill depend on which axis is summed. Technically, to provide the best speed possible, the improved precisionis only used when the summation is along the fast axis in memory. Note that the exact precision may varydepending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but moreprecise approach to summation. Especially when summing a large number of lower precision floating pointnumbers, such as float32 , numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output. Examples >>> np.sum([0.5, 1.5])2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)1 >>> np.sum([[0, 1], [0, 5]])6 >>> np.sum([[0, 1], [0, 5]], axis=0)array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1)array([1, 5]) >>> np.sum([[0, 1], [np.nan, 5]], where=[ False , True ], axis=1)array([1., 5.]) If the accumulator is too small, overflow occurs: >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)-128 You can also start the sum with a value other than zero: >>> np.sum([10], initial=5)15 swapaxes ( a , axis1 , axis2 ) Interchange two axes of an array.LAX-backend implementation of swapaxes() . ADDITIONOriginal docstring below.LAX-backend implementation of swapaxes() . Original docstring below. Returns a_swapped – For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; other-wise a new array is created. For earlier NumPy versions a view of a is returned only if the orderof the axes is changed, otherwise the input array is returned. Return type ndarray >>> x = np.array([[1,2,3]]) >>> np.swapaxes(x,0,1)array([[1],[2],[3]]) >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]]) >>> xarray([[[0, 1],[2, 3]],[[4, 5],[6, 7]]]) >>> np.swapaxes(x,0,2)array([[[0, 4],[2, 6]],[[1, 5],[3, 7]]]) take ( a , indices , axis=None , out=None , mode=None ) Take elements from an array along an axis.LAX-backend implementation of take() . ADDITIONOriginal docstring below.LAX-backend implementation of take() . Original docstring below.When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays);however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr,indices, axis=3) is equivalent to arr[:,:,:,indices,...] .Explained without fancy indexing, this is equivalent to the following use of ndindex , which sets each of ii , jj ,and kk to a tuple of indices: Ni, Nk = a.shape[:axis], a.shape[axis+1:]Nj = indices.shape for ii in ndindex(Ni): for jj in ndindex(Nj): for kk in ndindex(Nk):out[ii + jj + kk] = a[ii + (indices[jj],) + kk] Returns out – The returned array has the same type as a . Return type ndarray (Ni. . . , Nj. . . , Nk. . . ) See also: compress() Take elements using a boolean mask ndarray.take() equivalent method take_along_axis() Take elements by matching the array and the index arrays 156 Chapter 2. APIymjax, Release 0.0.1Notes By eliminating the inner loop in the description above, and using s_ to build simple slice objects, take can beexpressed in terms of applying fancy indexing to each 1-d slice: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nj):out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices] For this reason, it is equivalent to (but faster than) the following use of apply_along_axis : out = np.apply_along_axis( lambda a_1d: a_1d[indices], axis, a) Examples >>> a = [4, 3, 5, 7, 6, 8] >>> indices = [0, 1, 4] >>> np.take(a, indices)array([4, 3, 6]) In this example if a is an ndarray, “fancy” indexing can be used. >>> a = np.array(a) >>> a[indices]array([4, 3, 6]) If indices is not one dimensional, the output also has these dimensions. >>> np.take(a, [[0, 1], [2, 3]])array([[4, 3],[5, 7]]) take_along_axis ( arr , indices , axis ) Take values from the input array by matching 1d index and data slices.LAX-backend implementation of take_along_axis() . ADDITIONOriginal docstring below.LAX-backend implementation of take_along_axis() . Original docstring below.This iterates over matching 1d slices oriented along the specified axis in the index and dataarrays, and uses the former to look up values in the latter. These slices can be differentlengths.Functions returning an index along an axis, like argsort and argpartition , produce suitableindices for this function.New in version 1.15.0. Returnsout: ndarray (Ni. . . , J, Nk. . . ) The indexed result.This is equivalent to (but faster than) the following use of ndindex and s_ , which sets each of ii and kk to a tuple of indices: Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]J = indices.shape[axis] out = np.empty(Ni + (J,) + Nk) for ii in ndindex(Ni): for kk in ndindex(Nk):a_1d = a [ii + s_[:,] + kk]indices_1d = indices[ii + s_[:,] + kk]out_1d = out [ii + s_[:,] + kk] for j in range(J):out_1d[j] = a_1d[indices_1d[j]] Equivalently, eliminating the inner loop, the last two lines would be: out_1d[:] = a_1d[indices_1d] take : Take along an axis, using the same indices for every 1d slice put_along_axis :Put values into the destination array by matching 1d index and data slicesFor this sample array >>> a = np.array([[10, 30, 20], [60, 40, 50]]) We can sort either by using sort directly, or argsort and this function >>> np.sort(a, axis=1)array([[10, 20, 30],[40, 50, 60]]) >>> ai = np.argsort(a, axis=1); aiarray([[0, 2, 1],[1, 2, 0]]) >>> np.take_along_axis(a, ai, axis=1)array([[10, 20, 30],[40, 50, 60]]) The same works for max and min, if you expand the dimensions: >>> np.expand_dims(np.max(a, axis=1), axis=1)array([[30],[60]]) >>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1) >>> aiarray([[1],[0]]) >>> np.take_along_axis(a, ai, axis=1)array([[30],[60]]) If we want to get the max and min at the same time, we can stack the indices first >>> ai_min = np.expand_dims(np.argmin(a, axis=1), axis=1) >>> ai_max = np.expand_dims(np.argmax(a, axis=1), axis=1) >>> ai = np.concatenate([ai_min, ai_max], axis=1) >>> aiarray([[0, 1],[1, 0]]) >>> np.take_along_axis(a, ai, axis=1) (continues on next page) 158 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) array([[10, 30],[40, 60]]) tan ( x ) Compute tangent element-wise.LAX-backend implementation of tan() . ADDITIONOriginal docstring below.LAX-backend implementation of tan() . Original docstring below.tan(x, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, ex-tobj])Equivalent to np.sin(x)/np.cos(x) element-wise. Returns y – The corresponding tangent values. This is a scalar if x is a scalar. Return type ndarray Notes If out is provided, the function writes the result into it, and returns a reference to out . (See Examples) References M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi]))array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16])>>> >>> >>> >>> out1 = np.array([0], dtype='d') >>> out2 = np.cos([0.1], out1) >>> out2 is out1True>>> >>> >>> np.cos(np.zeros((3,3)),np.zeros((2,2)))Traceback (most recent call last):File " Notes If out is provided, the function writes the result into it, and returns a reference to out . (See Examples) ReferencesExamples >>> np.tanh((0, np.pi*1j, np.pi*1j/2))array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) >>> >>> >>> out1 = np.array([0], dtype='d') >>> out2 = np.tanh([0.1], out1) >>> out2 is out1True >>> >>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))Traceback (most recent call last):File " Return type ndarray See also: dot() , einsum() 160 Chapter 2. APIymjax, Release 0.0.1Notes Three common use cases are: • axes = 0 : tensor product 𝑎 ⊗ 𝑏 • axes = 1 : tensor dot product 𝑎 · 𝑏 • axes = 2 : (default) tensor double contraction 𝑎 : 𝑏 When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b , and the-1th axis in a and Nth axis in b last.When there is more than one axis to sum over - and they are not the last (first) axes of a ( b ) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences,the second axis second, and so forth.The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contractedaxes of the second. Examples A “traditional” example: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape(5, 2) >>> carray([[4400., 4730.],[4532., 4874.],[4664., 5018.],[4796., 5162.],[4928., 5306.]]) >>> >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == darray([[ True, True],[ True, True],[ True, True],[ True, True],[ True, True]]) An extended example taking advantage of the overloading of + and *: >>> a = np.array(range(1, 9)) >>> a.shape = (2, 2, 2) >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) >>> A.shape = (2, 2) >>> a; Aarray([[[1, 2],[3, 4]], (continues on next page) (continued from previous page) [[5, 6],[7, 8]]])array([['a', 'b'],['c', 'd']], dtype=object) >>> np.tensordot(a, A) array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, 1)array([[['acc', 'bdd'],['aaacccc', 'bbbdddd']],[['aaaaacccccc', 'bbbbbdddddd'],['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object) >>> np.tensordot(a, A, 0) array([[[[['a', 'b'],['c', 'd']],... >>> np.tensordot(a, A, (0, 1))array([[['abbbbb', 'cddddd'],['aabbbbbb', 'ccdddddd']],[['aaabbbbbbb', 'cccddddddd'],['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, (2, 1))array([[['abb', 'cdd'],['aaabbbb', 'cccdddd']],[['aaaaabbbbbb', 'cccccdddddd'],['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, ((0, 1), (0, 1)))array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, ((2, 1), (1, 0)))array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object) tile ( a , reps ) Construct an array by repeating A the number of times given by reps.LAX-backend implementation of tile() . ADDITIONOriginal docstring below.LAX-backend implementation of tile() . Original docstring below.If reps has length d , the result will have dimension of max(d, A.ndim) .If A.ndim < d , A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promotedto (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.If A.ndim > d , reps is promoted to A .ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcastingoperations and functions. Returns c – The tiled output array. 162 Chapter 2. APIymjax, Release 0.0.1 Return type ndarray See also: repeat() Repeat elements of an array. broadcast_to() Broadcast an array to a new shape Examples >>> a = np.array([0, 1, 2]) >>> np.tile(a, 2)array([0, 1, 2, 0, 1, 2]) >>> np.tile(a, (2, 2))array([[0, 1, 2, 0, 1, 2],[0, 1, 2, 0, 1, 2]]) >>> np.tile(a, (2, 1, 2))array([[[0, 1, 2, 0, 1, 2]],[[0, 1, 2, 0, 1, 2]]]) >>> b = np.array([[1, 2], [3, 4]]) >>> np.tile(b, 2)array([[1, 2, 1, 2],[3, 4, 3, 4]]) >>> np.tile(b, (2, 1))array([[1, 2],[3, 4],[1, 2],[3, 4]]) >>> c = np.array([1,2,3,4]) >>> np.tile(c,(4,1))array([[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]]) trace ( a , offset=0 , axis1=0 , axis2=1 , dtype=None , out=None ) Return the sum along diagonals of the array.LAX-backend implementation of trace() . ADDITIONOriginal docstring below.LAX-backend implementation of trace() . Original docstring below.If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i.If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-Dsub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed. Parameters dtype ( dtype, optional ) – Determines the data-type of the returned array andof the accumulator where the elements are summed. If dtype has the value None and a is ofinteger type of precision less than the default integer precision, then the default integer precisionis used. Otherwise, the precision is the same as that of a . Returns sum_along_diagonals – If a is 2-D, the sum along the diagonal is returned. If a has largerdimensions, then an array of sums along diagonals is returned. Return type ndarray See also: diag() , diagonal() , diagflat() Examples >>> np.trace(np.eye(3))3.0 >>> a = np.arange(8).reshape((2,2,2)) >>> np.trace(a)array([6, 8]) >>> a = np.arange(24).reshape((2,2,2,3)) >>> np.trace(a).shape(2, 3) transpose ( a , axes=None ) Permute the dimensions of an array.LAX-backend implementation of transpose() . ADDITIONOriginal docstring below.LAX-backend implementation of transpose() . Original docstring below. Returns p – a with its axes permuted. A view is returned whenever possible. Return type ndarray See also: moveaxis() , argsort() Notes Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument.Transposing a 1-D array returns an unchanged view of the original array. Examples >>> x = np.arange(4).reshape((2,2)) >>> xarray([[0, 1],[2, 3]]) >>> np.transpose(x)array([[0, 2],[1, 3]]) >>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape(2, 1, 3) 164 Chapter 2. APIymjax, Release 0.0.1 tri ( N , M=None , k=0 , dtype=None ) An array with ones at and below the given diagonal and zeros elsewhere.LAX-backend implementation of tri() . ADDITIONOriginal docstring below.LAX-backend implementation of tri() . Original docstring below. Parameters dtype ( dtype, optional ) – Data type of the returned array. The default is float. Returns tri – Array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for j <= i + k , 0 otherwise. Return type ndarray of shape (N, M) Examples >>> np.tri(3, 5, 2, dtype=int)array([[1, 1, 1, 0, 0],[1, 1, 1, 1, 0],[1, 1, 1, 1, 1]]) >>> np.tri(3, 5, -1)array([[0., 0., 0., 0., 0.],[1., 0., 0., 0., 0.],[1., 1., 0., 0., 0.]]) tril ( m , k=0 ) Lower triangle of an array.LAX-backend implementation of tril() . ADDITIONOriginal docstring below.LAX-backend implementation of tril() . Original docstring below.Return a copy of an array with elements above the k -th diagonal zeroed. Returns tril – Lower triangle of m , of same shape and data-type as m . Return type ndarray, shape (M, N) See also: triu() same thing, only for the upper triangle Examples >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)array([[ 0, 0, 0],[ 4, 0, 0],[ 7, 8, 0],[10, 11, 12]]) tril_indices ( *args , **kwargs ) Return the indices for the lower-triangle of an (n, m) array.LAX-backend implementation of tril_indices() . ADDITIONOriginal docstring below.LAX-backend implementation of tril_indices() . Original docstring below. Returnsinds [tuple of arrays] The indices for the triangle. The returned tuple contains two arrays, eachwith the indices along one dimension of the array.triu_indices : similar function, for upper-triangular. mask_indices : generic function acceptingan arbitrary mask function. tril, triuNew in version 1.4.0.Compute two different sets of indices to access 4x4 arrays, one for the lower triangular partstarting at the main diagonal, and one starting two diagonals further right: >>> il1 = np.tril_indices(4) >>> il2 = np.tril_indices(4, 2) Here is how they can be used with a sample array: >>> a = np.arange(16).reshape(4, 4) >>> aarray([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15]]) Both for indexing: >>> a[il1]array([ 0, 4, 5, ..., 13, 14, 15]) And for assigning values: >>> a[il1] = -1 >>> aarray([[-1, 1, 2, 3],[-1, -1, 6, 7],[-1, -1, -1, 11],[-1, -1, -1, -1]]) These cover almost the whole array (two diagonals right of the main one): >>> a[il2] = -10 >>> aarray([[-10, -10, -10, 3],[-10, -10, -10, -10],[-10, -10, -10, -10],[-10, -10, -10, -10]]) triu ( m , k=0 ) Upper triangle of an array.LAX-backend implementation of triu() . ADDITIONOriginal docstring below.LA triu_indices ( *args , **kwargs ) Return the indices for the upper-triangle of an (n, m) array.LAX-backend implementation of triu_indices() . ADDITIONOriginal docstring below.LAX-backend implementation of triu_indices() . Original docstring below. 166 Chapter 2. APIymjax, Release 0.0.1 Returnsinds [tuple, shape(2) of ndarrays, shape( n )] The indices for the triangle. The returned tuplecontains two arrays, each with the indices along one dimension of the array. Can be used toslice a ndarray of shape( n , n ).tril_indices : similar function, for lower-triangular. mask_indices : generic function acceptingan arbitrary mask function. triu, trilNew in version 1.4.0.Compute two different sets of indices to access 4x4 arrays, one for the upper triangular partstarting at the main diagonal, and one starting two diagonals further right: >>> iu1 = np.triu_indices(4) >>> iu2 = np.triu_indices(4, 2) Here is how they can be used with a sample array: >>> a = np.arange(16).reshape(4, 4) >>> aarray([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15]]) Both for indexing: >>> a[iu1]array([ 0, 1, 2, ..., 10, 11, 15]) And for assigning values: >>> a[iu1] = -1 >>> aarray([[-1, -1, -1, -1],[ 4, -1, -1, -1],[ 8, 9, -1, -1],[12, 13, 14, -1]]) These cover only a small part of the whole array (two diagonals right of the main one): >>> a[iu2] = -10 >>> aarray([[ -1, -1, -10, -10],[ 4, -1, -1, -10],[ 8, 9, -1, -1],[ 12, 13, 14, -1]]) true_divide ( x1 , x2 ) Returns a true division of the inputs, element-wise.LAX-backend implementation of true_divide() . ADDITIONOriginal docstring below.LAX-backend implementation of true_divide() . Original docstring below.true_divide(x1, x2, /, out=None, * , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[,signature, extobj]) Instead of the Python traditional ‘floor division’, this returns a true division. True division adjusts the outputtype to present the best answer, regardless of input types. Returns out – This is a scalar if both x1 and x2 are scalars. Return type ndarray or scalar Notes The floor division operator // was added in Python 2.2 making // and / equivalent operators. The default floordivision operation of / can be replaced by true division with from __future__ import division .In Python 3.0, // is the floor division operator and / the true division operator. The true_divide(x1,x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5) >>> np.true_divide(x, 4)array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4array([0, 0, 0, 0, 1]) >>> from __future__ import division >>> x/4array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4array([0, 0, 0, 0, 1]) var ( a , axis=None , dtype=None , out=None , ddof=0 , keepdims=False ) Compute the variance along the specified axis.LAX-backend implementation of var() . ADDITIONOriginal docstring below.LAX-backend implementation of var() . Original docstring below.Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computedfor the flattened array by default, otherwise over the specified axis. Parameters dtype ( data-type, optional ) – Type to use in computing the variance. Forarrays of integer type the default is float64 ; for arrays of float types it is the same as the arraytype. Returns variance – If out=None , returns a new array containing the variance; otherwise, a refer-ence to the output array is returned. Return type ndarray, see dtype parameter above See also: std() , mean() , nanmean() , nanstd() , nanvar() , ufuncs-output-type() 168 Chapter 2. APIymjax, Release 0.0.1Notes The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x - x.mean())**2) .The mean is normally calculated as x.sum() / N , where N = len(x) . If, however, ddof is specified, thedivisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimatorof the variance of a hypothetical infinite population. ddof=0 provides a maximum likelihood estimate of thevariance for normally distributed variables.Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real andnonnegative.For floating-point input, the variance is computed using the same precision the input has. Depending on theinput data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying ahigher-accuracy accumulator using the dtype keyword can alleviate this issue. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> np.var(a)1.25 >>> np.var(a, axis=0)array([1., 1.]) >>> np.var(a, axis=1)array([0.25, 0.25]) In single precision, var() can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.var(a)0.20250003 Computing the variance in float64 is more accurate: >>> np.var(a, dtype=np.float64)0.20249999932944759 >>> ((1-0.55)**2 + (0.1-0.55)**2)/20.2025 vdot ( a , b , precision=None ) Return the dot product of two vectors.LAX-backend implementation of vdot() . ADDITIONOriginal docstring below.LAX-backend implementation of vdot() . In addition to the original NumPy arguments listed below, alsosupports precision for extra control over matrix-multiplication precision on supported devices. See jax.lax.dot() for details.Original docstring below.vdot(a, b)The vdot( a , b ) function handles complex numbers differently than dot( a , b ). If the firstargument is complex the complex conjugate of the first argument is used for the calculationof the dot product. Note that vdot handles multidimensional arrays differently than dot : it does not perform amatrix product, but flattens input arguments to 1-D vectors first. Consequently, it shouldonly be used for vectors. Returnsoutput [ndarray] Dot product of a and b . Can be an int, float, or complex depending on thetypes of a and b . dot [Return the dot product without using the complex conjugate of the] first argument. >>> a = np.array([1+2j,3+4j]) >>> b = np.array([5+6j,7+8j]) >>> np.vdot(a, b)(70-8j) >>> np.vdot(b, a)(70+8j) Note that higher-dimensional arrays are flattened! >>> a = np.array([[1, 4], [5, 6]]) >>> b = np.array([[4, 1], [2, 2]]) >>> np.vdot(a, b)30 >>> np.vdot(b, a)30 >>> vsplit ( ary , indices_or_sections ) Split an array into multiple sub-arrays vertically (row-wise).LAX-backend implementation of vsplit() . ADDITIONOriginal docstring below.LA vstack ( tup ) Stack arrays in sequence vertically (row wise).LAX-backend implementation of vstack() . ADDITIONOriginal docstring below.LAX-backend implementation of vstack() . Original docstring below.This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N) .Rebuilds arrays divided by vsplit .This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height(first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate , stack and block provide more general stacking and concatenation operations. Returns stacked – The array formed by stacking the given arrays, will be at least 2-D. Return type ndarray See also: stack() Join a sequence of arrays along a new axis. hstack() Stack arrays in sequence horizontally (column wise). dstack() Stack arrays in sequence depth wise (along third dimension). 170 Chapter 2. APIymjax, Release 0.0.1 concatenate() Join a sequence of arrays along an existing axis. vsplit() Split array into a list of multiple sub-arrays vertically. block() Assemble arrays from blocks. Examples >>> a = np.array([1, 2, 3]) >>> b = np.array([2, 3, 4]) >>> np.vstack((a,b))array([[1, 2, 3],[2, 3, 4]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[2], [3], [4]]) >>> np.vstack((a,b))array([[1],[2],[3],[2],[3],[4]]) zeros ( shape , dtype=None ) Return a new array of given shape and type, filled with zeros.LAX-backend implementation of zeros() . ADDITIONOriginal docstring below.LAX-backend implementation of zeros() . Original docstring below.zeros(shape, dtype=float, order=’C’) Returnsout [ndarray] Array of zeros with the given shape, dtype, and order.zeros_like : Return an array of zeros with shape and type of input. empty : Return a newuninitialized array. ones : Return a new array setting values to one. full : Return a new array ofgiven shape filled with value. >>> np.zeros(5)array([ 0., 0., 0., 0., 0.]) >>> np.zeros((5,), dtype=int)array([0, 0, 0, 0, 0]) >>> np.zeros((2, 1))array([[ 0.],[ 0.]]) >>> s = (2,2) >>> np.zeros(s)array([[ 0., 0.],[ 0., 0.]]) >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) array([(0, 0), (0, 0)],dtype=[('x', ' Parameters dtype ( data-type, optional ) – Overrides the data type of the result. Returns out – Array of zeros with the same shape and type as a . Return type ndarray See also: empty_like() Return an empty array with shape and type of input. ones_like() Return an array of ones with shape and type of input. full_like() Return a new array with shape of input filled with value. zeros() Return a new array setting values to zero. Examples >>> x = np.arange(6) >>> x = x.reshape((2, 3)) >>> xarray([[0, 1, 2],[3, 4, 5]]) >>> np.zeros_like(x)array([[0, 0, 0],[0, 0, 0]]) >>> y = np.arange(3, dtype=float) >>> yarray([0., 1., 2.]) >>> np.zeros_like(y)array([0., 0., 0.]) symjax.tensor.pdfs Multivariate Normal class multivariate_normallogpdf ( mean , cov ) Log of the multivariate normal probability density function. Parameters x ( array_like ) – Returns pdf – Log of the probability density function evaluated at x 172 Chapter 2. APIymjax, Release 0.0.1 Return type ndarray pdf ( mean , cov ) Multivariate normal probability density function. :param x: Quantiles, with the last axis of x denoting thecomponents. :type x: array_like Returns pdf – Probability density function evaluated at x Return type ndarray symjax.tensor.signal Apodization Windows blackman (M) Return the Blackman window. bartlett (M) Return the Bartlett window. hamming (M) Return the Hamming window. hanning (M) Return the Hanning window. kaiser (M, beta) Return the Kaiser window. Fourier Transforms fft (a[, n, axis, norm]) Compute the one-dimensional discrete Fourier Trans-form. ifft (a[, n, axis, norm]) Compute the one-dimensional inverse discrete FourierTransform. fft2 (a[, s, axes, norm]) Compute the 2-dimensional discrete Fourier Transform ifft2 (a[, s, axes, norm]) Compute the 2-dimensional inverse discrete FourierTransform. fftn (a[, s, axes, norm]) Compute the N-dimensional discrete Fourier Trans-form. ifftn (a[, s, axes, norm]) Compute the N-dimensional inverse discrete FourierTransform. rfft (a[, n, axis, norm]) Compute the one-dimensional discrete Fourier Trans-form for real input. irfft (a[, n, axis, norm]) Compute the inverse of the n-point DFT for real input. rfft2 (a[, s, axes, norm]) Compute the 2-dimensional FFT of a real array. irfft2 (a[, s, axes, norm]) Compute the 2-dimensional inverse FFT of a real array. rfftn (a[, s, axes, norm]) Compute the N-dimensional discrete Fourier Transformfor real input. irfftn (a[, s, axes, norm]) Compute the inverse of the N-dimensional FFT of realinput. fftfreq (n[, d]) Return the Discrete Fourier Transform sample frequen-cies. rfftfreq (n[, d]) Return the Discrete Fourier Transform sample frequen-cies mfcc (signal, window, hop, n_filter, . . . [, . . . ]) https://librosa.github.io/librosa/_modules/librosa/feature/spectral.html dct (signal[, axes]) https://dsp.stackexchange.com/questions/2807/fast-cosine-transform-via-fft wvd (signal, window, hop, L[, apod, mode]) hilbert_transform (signal) the time should be the last dimension return the analyti-cal signal Detailed Descritpions blackman ( M ) Return the Blackman window.LAX-backend implementation of blackman() . ADDITIONOriginal docstring below.The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designedto have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Returns out – The window, with the maximum value normalized to one (the value one appears onlyif the number of samples is odd). Return type ndarray See also: bartlett() , hamming() , hanning() , kaiser() Notes The Blackman window is defined as 𝑤 ( 𝑛 ) = 0 . − . 𝜋𝑛/𝑀 ) + 0 . 08 cos(4 𝜋𝑛/𝑀 ) Most references to the Blackman window come from the signal processing literature, where it is used as one ofmany windowing functions for smoothing values. It is also known as an apodization (which means “removingthe foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. Itis known as a “near optimal” tapering function, almost as good (by some measures) as the kaiser window. References Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall,1999, pp. 468-471. 174 Chapter 2. APIymjax, Release 0.0.1Examples >>> import matplotlib.pyplot as plt>>> np.blackman(12)array([-1.38777878e-17, 3.26064346e-02, 1.59903635e-01, Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window)[ A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ...>>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response)[ Returns out – The triangular window, with the maximum value normalized to one (the value oneappears only if the number of samples is odd), with the first and last samples equal to zero. Return type array See also: blackman() , hamming() , hanning() , kaiser() The Bartlett window is defined as 𝑤 ( 𝑛 ) = 2 𝑀 − (︂ 𝑀 − − ⃒⃒⃒⃒ 𝑛 − 𝑀 − ⃒⃒⃒⃒)︂ Most references to the Bartlett window come from the signal processing literature, where it is used as one ofmany windowing functions for smoothing values. Note that convolution with this window produces linear in-terpolation. It is also known as an apodization (which means”removing the foot”, i.e. smoothing discontinuitiesat the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is theproduct of two sinc functions. Note the excellent discussion in Kanasewich. ReferencesExamples >>> import matplotlib.pyplot as plt>>> np.bartlett(12)array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, Plot the window and its frequency response (requires SciPy and matplotlib): >>> from numpy.fft import fft, fftshift >>> window = np.bartlett(51) >>> plt.plot(window)[ A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ...>>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response)[ 176 Chapter 2. APIymjax, Release 0.0.1 hamming ( M ) Return the Hamming window.LAX-backend implementation of hamming() . ADDITIONOriginal docstring below.The Hamming window is a taper formed by using a weighted cosine. Returns out – The window, with the maximum value normalized to one (the value one appears onlyif the number of samples is odd). Return type ndarray See also: bartlett() , blackman() , hanning() , kaiser() Notes The Hamming window is defined as 𝑤 ( 𝑛 ) = 0 . − . 𝑐𝑜𝑠 (︂ 𝜋𝑛𝑀 − )︂ ≤ 𝑛 ≤ 𝑀 − The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman andTukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Mostreferences to the Hamming window come from the signal processing literature, where it is used as one of manywindowing functions for smoothing values. It is also known as an apodization (which means “removing thefoot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. ReferencesExamples >>> np.hamming(12)array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, Plot the window and the frequency response: >>> import matplotlib.pyplot as plt>>> from numpy.fft import fft, fftshift >>> window = np.hamming(51) >>> plt.plot(window)[ A = fft(window, 2048) / 25.5 (continues on next page) (continued from previous page) >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response)[ Returns out – The window, with the maximum value normalized to one (the value one appears onlyif M is odd). Return type ndarray, shape(M,) See also: bartlett() , blackman() , hamming() , kaiser() Notes The Hanning window is defined as 𝑤 ( 𝑛 ) = 0 . − . 𝑐𝑜𝑠 (︂ 𝜋𝑛𝑀 − )︂ ≤ 𝑛 ≤ 𝑀 − The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as the Cosine Bell.Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hammingwindow.Most references to the Hanning window come from the signal processing literature, where it is used as one ofmany windowing functions for smoothing values. It is also known as an apodization (which means “removingthe foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. ReferencesExamples >>> np.hanning(12)array([0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037,0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,0.07937323, 0. ]) Plot the window and its frequency response: 178 Chapter 2. APIymjax, Release 0.0.1 >>> import matplotlib.pyplot as plt>>> from numpy.fft import fft, fftshift >>> window = np.hanning(51) >>> plt.plot(window)[ A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ...>>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response)[ Returns out – The window, with the maximum value normalized to one (the value one appears onlyif the number of samples is odd). Return type array See also: bartlett() , blackman() , hamming() , hanning() The Kaiser window is defined as 𝑤 ( 𝑛 ) = 𝐼 (︃ 𝛽 √︃ − 𝑛 ( 𝑀 − )︃ /𝐼 ( 𝛽 ) with − 𝑀 − ≤ 𝑛 ≤ 𝑀 − , where 𝐼 is the modified zeroth-order Bessel function.The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based onBessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence,or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relativeto total energy.The Kaiser can approximate many other windows by varying the beta parameter. beta Window shape ReferencesExamples >>> import matplotlib.pyplot as plt>>> np.kaiser(12, 14)array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window)[ 180 Chapter 2. APIymjax, Release 0.0.1 (continued from previous page) Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample")Text(0.5, 0, 'Sample') >>> plt.show() >>> plt.figure() A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response)[ Return type complex ndarray Raises IndexError – if axes is larger than the last axis of a . See also: numpy.fft() for definition of the DFT and conventions used. ifft() The inverse of fft . fft2() The two-dimensional FFT. fftn() The n -dimensional FFT. rfftn() The n -dimensional FFT of real input. fftfreq() Frequency bins for given FFT parameters. FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently,by using symmetries in the calculated terms. The symmetry is highest when n is a power of 2, and the transformis therefore most efficient for these sizes.The DFT is defined, with the conventions used in this implementation, in the documentation for the numpy.fft module. ReferencesExamples >>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,-1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j]) In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric inthe imaginary part, as described in the numpy.fft documentation: >>> import matplotlib.pyplot as plt>>> t = np.arange(256) >>> sp = np.fft.fft(np.sin(t)) >>> freq = np.fft.fftfreq(t.shape[-1]) >>> plt.plot(freq, sp.real, freq, sp.imag)[ Returns out – The truncated or zero-padded input, transformed along the axis indicated by axis , orthe last one if axis is not specified. Return type complex ndarray Raises IndexError – If axes is larger than the last axis of a . 182 Chapter 2. APIymjax, Release 0.0.1 See also: numpy.fft() An introduction, with definitions and general explanations. fft() The one-dimensional (forward) FFT, of which ifft is the inverse ifft2() The two-dimensional inverse FFT. ifftn() The n-dimensional inverse FFT. Notes If the input parameter n is larger than the size of the input, the input is padded by appending zeros at the end.Even though this is the common approach, it might lead to surprising results. If a different padding is desired, itmust be performed before calling ifft . Examples >>> np.fft.ifft([0, 4, 0, 0])array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) Create and plot a band-limited signal with random phases: >>> import matplotlib.pyplot as plt>>> t = np.arange(400) >>> n = np.zeros((400,), dtype=complex) >>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,))) >>> s = np.fft.ifft(n) >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')[ Return type complex ndarray Raises • ValueError – If s and axes have different length, or axes not given and len(s) != 2 .• IndexError – If an element of axes is larger than than the number of axes of a . See also: numpy.fft() Overall view of discrete Fourier transforms, with definitions and conventions used. ifft2() The inverse two-dimensional FFT. fft() The one-dimensional FFT. fftn() The n -dimensional FFT. fftshift() Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps firstand third quadrants, and second and fourth quadrants. Notes fft2 is just fftn with a different default for axes .The output, analogously to fft , contains the term for zero frequency in the low-order corner of the transformedaxes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middleof the axes and the negative frequency terms in the second half of the axes, in order of decreasingly negativefrequency.See fftn for details and a plotting example, and numpy.fft for definitions and conventions used. Examples >>> a = np.mgrid[:5, :5][0] >>> np.fft.fft2(a)array([[ 50. +0.j , 0. +0.j , 0. +0.j , ifft2 ( a , s=None , axes=- 2, - 1 , norm=None ) Compute the 2-dimensional inverse discrete Fourier Transform.LAX-backend implementation of ifft2() . ADDITIONOriginal docstring below.LAX-backend implementation of ifft2() . Original docstring below.This function computes the inverse of the 2-dimensional discrete Fourier Transform over any number of axesin an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, ifft2(fft2(a))== a to within numerical accuracy. By default, the inverse transform is computed over the last two axes of theinput array.The input, analogously to ifft , should be ordered in the same way as is returned by fft2 , i.e. it should have theterm for zero frequency in the low-order corner of the two axes, the positive frequency terms in the first half ofthese axes, the term for the Nyquist frequency in the middle of the axes and the negative frequency terms in thesecond half of both axes, in order of decreasingly negative frequency. Returns out – The truncated or zero-padded input, transformed along the axes indicated by axes , orthe last two axes if axes is not given. Return type complex ndarray Raises • ValueError – If s and axes have different length, or axes not given and len(s) != 2 . 184 Chapter 2. APIymjax, Release 0.0.1 • IndexError – If an element of axes is larger than than the number of axes of a . See also: numpy.fft() Overall view of discrete Fourier transforms, with definitions and conventions used. fft2() The forward 2-dimensional FFT, of which ifft2 is the inverse. ifftn() The inverse of the n -dimensional FFT. fft() The one-dimensional FFT. ifft() The one-dimensional inverse FFT. Notes ifft2 is just ifftn with a different default for axes .See ifftn for details and a plotting example, and numpy.fft for definition and conventions used.Zero-padding, analogously with ifft , is performed by appending zeros to the input along the specified dimension.Although this is the common approach, it might lead to surprising results. If another form of zero padding isdesired, it must be performed before ifft2 is called. Examples >>> a = 4 * np.eye(4) >>> np.fft.ifft2(a)array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], fftn ( a , s=None , axes=None , norm=None ) Compute the N-dimensional discrete Fourier Transform.LAX-backend implementation of fftn() . ADDITIONOriginal docstring below.LAX-backend implementation of fftn() . Original docstring below.This function computes the N -dimensional discrete Fourier Transform over any number of axes in an M -dimensional array by means of the Fast Fourier Transform (FFT). Returns out – The truncated or zero-padded input, transformed along the axes indicated by axes , orby a combination of s and a , as explained in the parameters section above. Return type complex ndarray Raises • ValueError – If s and axes have different length.• IndexError – If an element of axes is larger than than the number of axes of a . See also: numpy.fft() Overall view of discrete Fourier transforms, with definitions and conventions used. ifftn() The inverse of fftn , the inverse n -dimensional FFT. fft() The one-dimensional FFT, with definitions and conventions used. rfftn() The n -dimensional FFT of real input. fft2() The two-dimensional FFT. fftshift() Shifts zero-frequency terms to centre of array Notes The output, analogously to fft , contains the term for zero frequency in the low-order corner of all axes, thepositive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axesand the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.See numpy.fft for details, definitions and conventions used. Examples >>> a = np.mgrid[:3, :3, :3][0] >>> np.fft.fftn(a, axes=(1, 2))array([[[ 0.+0.j, 0.+0.j, 0.+0.j], >>> np.fft.fftn(a, (2, 2), axes=(0, 1))array([[[ 2.+0.j, 2.+0.j, 2.+0.j], >>> import matplotlib.pyplot as plt>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12, ... >>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape) >>> FS = np.fft.fftn(S) >>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2)) 186 Chapter 2. APIymjax, Release 0.0.1 Returns out – The truncated or zero-padded input, transformed along the axes indicated by axes , orby a combination of s or a , as explained in the parameters section above. Return type complex ndarray Raises • ValueError – If s and axes have different length.• IndexError – If an element of axes is larger than than the number of axes of a . See also: numpy.fft() Overall view of discrete Fourier transforms, with definitions and conventions used. fftn() The forward n -dimensional FFT, of which ifftn is the inverse. ifft() The one-dimensional inverse FFT. ifft2() The two-dimensional inverse FFT. ifftshift() Undoes fftshift , shifts zero-frequency terms to beginning of array. Notes See numpy.fft for definitions and conventions used.Zero-padding, analogously with ifft , is performed by appending zeros to the input along the specified dimension.Although this is the common approach, it might lead to surprising results. If another form of zero padding isdesired, it must be performed before ifftn is called. Examples >>> a = np.eye(4) >>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], Create and plot an image with band-limited frequency content: >>> import matplotlib.pyplot as plt>>> n = np.zeros((200,200), dtype=complex) >>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20))) >>> im = np.fft.ifftn(n).real >>> plt.imshow(im) Raises IndexError – If axis is larger than the last axis of a . See also: numpy.fft() For definition of the DFT and conventions used. irfft() The inverse of rfft . fft() The one-dimensional FFT of general (complex) input. fftn() The n -dimensional FFT. rfftn() The n -dimensional FFT of real input. Notes When the DFT is computed for purely real input, the output is Hermitian-symmetric, i.e. the negative frequencyterms are just the complex conjugates of the corresponding positive-frequency terms, and the negative-frequencyterms are therefore redundant. This function does not compute the negative frequency terms, and the length ofthe transformed axis of the output is therefore n//2 + 1 .When A = rfft(a) and fs is the sampling frequency, A[0] contains the zero-frequency term 0*fs, which isreal due to Hermitian symmetry.If n is even, A[-1] contains the term representing both positive and negative Nyquist frequency (+fs/2 and-fs/2), and must also be purely real. If n is odd, there is no term at fs/2; A[-1] contains the largest positivefrequency (fs/2*(n-1)/n), and is complex in the general case.If the input a contains an imaginary part, it is silently discarded. Examples >>> np.fft.fft([0, 1, 0, 0])array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) >>> np.fft.rfft([0, 1, 0, 0])array([ 1.+0.j, 0.-1.j, -1.+0.j]) Notice how the final element of the fft output is the complex conjugate of the second element, for real input. For rfft , this symmetry is exploited to compute only the non-negative frequency terms. irfft ( a , n=None , axis=- 1 , norm=None ) Compute the inverse of the n-point DFT for real input.LAX-backend implementation of irfft() . ADDITIONOriginal docstring below.LAX-backend implementation of irfft() . Original docstring below.This function computes the inverse of the one-dimensional n -point discrete Fourier Transform of real inputcomputed by rfft . In other words, irfft(rfft(a), len(a)) == a to within numerical accuracy. (SeeNotes below for why len(a) is necessary here.)The input is expected to be in the form returned by rfft , i.e. the real zero-frequency term followed by the complexpositive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is 188 Chapter 2. APIymjax, Release 0.0.1 Hermitian-symmetric, the negative frequency terms are taken to be the complex conjugates of the correspondingpositive frequency terms. Returns out – The truncated or zero-padded input, transformed along the axis indicated by axis , orthe last one if axis is not specified. The length of the transformed axis is n , or, if n is not given, where m is the length of the transformed axis of the input. To get an odd number ofoutput points, n must be specified. Return type ndarray Raises IndexError – If axis is larger than the last axis of a . See also: numpy.fft() For definition of the DFT and conventions used. rfft() The one-dimensional FFT of real input, of which irfft is inverse. fft() The one-dimensional FFT. irfft2() The inverse of the two-dimensional FFT of real input. irfftn() The inverse of the n -dimensional FFT of real input. Notes Returns the real valued n -point inverse discrete Fourier transform of a , where a contains the non-negative fre-quency terms of a Hermitian-symmetric sequence. n is the length of the result, not the input.If you specify an n such that a must be zero-padded or truncated, the extra/removed values will beadded/removed at high frequencies. One can thus resample a series to m points via Fourier interpolation by: a_resamp = irfft(rfft(a), m) .The correct interpretation of the hermitian input depends on the length of the original data, as given by n . Thisis because each input shape could correspond to either an odd or even length signal. By default, irfft assumes aneven output length which puts the last entry at the Nyquist frequency; aliasing with its symmetric counterpart.By Hermitian symmetry, the value is thus treated as purely real. To avoid losing information, the correct lengthof the real input must be given. Examples >>> np.fft.ifft([1, -1j, -1, 1j])array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) >>> np.fft.irfft([1, -1j, -1])array([0., 1., 0., 0.]) Notice how the last term in the input to the ordinary ifft is the complex conjugate of the second term, and theoutput has zero imaginary part everywhere. When calling irfft , the negative frequencies are not specified, andthe output array is purely real. rfft2 ( a , s=None , axes=- 2, - 1 , norm=None ) Compute the 2-dimensional FFT of a real array.LAX-backend implementation of rfft2() . ADDITIONOriginal docstring below.LAX-backend implementation of rfft2() . Original docstring below. Returns out – The result of the real 2-D FFT. Return type ndarray See also: rfftn() Compute the N-dimensional discrete Fourier Transform for real input. Notes This is really just rfftn with different default behavior. For more details see rfftn . irfft2 ( a , s=None , axes=- 2, - 1 , norm=None ) Compute the 2-dimensional inverse FFT of a real array.LAX-backend implementation of irfft2() . ADDITIONOriginal docstring below.LAX-backend implementation of irfft2() . Original docstring below. Returns out – The result of the inverse real 2-D FFT. Return type ndarray See also: irfftn() Compute the inverse of the N-dimensional FFT of real input. Notes This is really irfftn with different defaults. For more details see irfftn . rfftn ( a , s=None , axes=None , norm=None ) Compute the N-dimensional discrete Fourier Transform for real input.LAX-backend implementation of rfftn() . ADDITIONOriginal docstring below.LAX-backend implementation of rfftn() . Original docstring below.This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional real array by means of the Fast Fourier Transform (FFT). By default, all axes are transformed,with the real transform performed over the last axis, while the remaining transforms are complex. Returns out – The truncated or zero-padded input, transformed along the axes indicated by axes , orby a combination of s and a , as explained in the parameters section above. The length of the lastaxis transformed will be s[-1]//2+1 , while the remaining transformed axes will have lengthsaccording to s , or unchanged from the input. Return type complex ndarray Raises • ValueError – If s and axes have different length.• IndexError – If an element of axes is larger than than the number of axes of a . See also: irfftn() The inverse of rfftn , i.e. the inverse of the n-dimensional FFT of real input. fft() The one-dimensional FFT, with definitions and conventions used. rfft() The one-dimensional FFT of real input. fftn() The n-dimensional FFT. rfft2() The two-dimensional FFT of real input. 190 Chapter 2. APIymjax, Release 0.0.1Notes The transform for real input is performed over the last transformation axis, as by rfft , then the transform overthe remaining axes is performed as by fftn . The order of the output is as for rfft for the final transformation axis,and as for fftn for the remaining transformation axes.See fft for details, definitions and conventions used. Examples >>> a = np.ones((2, 2, 2)) >>> np.fft.rfftn(a)array([[[8.+0.j, 0.+0.j], >>> np.fft.rfftn(a, axes=(2, 0))array([[[4.+0.j, 0.+0.j], irfftn ( a , s=None , axes=None , norm=None ) Compute the inverse of the N-dimensional FFT of real input.LAX-backend implementation of irfftn() . ADDITIONOriginal docstring below.LAX-backend implementation of irfftn() . Original docstring below.This function computes the inverse of the N-dimensional discrete Fourier Transform for real input over anynumber of axes in an M-dimensional array by means of the Fast Fourier Transform (FFT). In other words, irfftn(rfftn(a), a.shape) == a to within numerical accuracy. (The a.shape is necessary like len(a) is for irfft , and for the same reason.)The input should be ordered in the same way as is returned by rfftn , i.e. as for irfft for the final transformationaxis, and as for ifftn along all the other axes. Returns out – The truncated or zero-padded input, transformed along the axes indicated by axes ,or by a combination of s or a , as explained in the parameters section above. The length of eachtransformed axis is as given by the corresponding element of s , or the length of the input in everyaxis except for the last one if s is not given. In the final transformed axis the length of the outputwhen s is not given is where m is the length of the final transformed axis of the input.To get an odd number of output points in the final axis, s must be specified. Return type ndarray Raises • ValueError – If s and axes have different length.• IndexError – If an element of axes is larger than than the number of axes of a . See also: rfftn() The forward n-dimensional FFT of real input, of which ifftn is the inverse. fft() The one-dimensional FFT, with definitions and conventions used. irfft() The inverse of the one-dimensional FFT of real input. irfft2() The inverse of the two-dimensional FFT of real input. Notes See fft for definitions and conventions used.See rfft for definitions and conventions used for real input.The correct interpretation of the hermitian input depends on the shape of the original data, as given by s . This isbecause each input shape could correspond to either an odd or even length signal. By default, irfftn assumes aneven output length which puts the last entry at the Nyquist frequency; aliasing with its symmetric counterpart.When performing the final complex to real transform, the last value is thus treated as purely real. To avoid losinginformation, the correct shape of the real input must be given. Examples >>> a = np.zeros((3, 2, 2)) >>> a[0, 0, 0] = 3 * 2 * 2 >>> np.fft.irfftn(a)array([[[1., 1.],[1., 1.]],[[1., 1.],[1., 1.]],[[1., 1.],[1., 1.]]]) fftfreq ( n , d=1.0 ) Return the Discrete Fourier Transform sample frequencies.LAX-backend implementation of fftfreq() . ADDITIONOriginal docstring below.LAX-backend implementation of fftfreq() . Original docstring below.The returned float array f contains the frequency bin centers in cycles per unit of the sample spacing (with zeroat the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second.Given a window length n and a sample spacing d : f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is evenf = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd Returns f – Array of length n containing the sample frequencies. Return type ndarray Examples >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) >>> fourier = np.fft.fft(signal) >>> n = signal.size >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freqarray([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25]) rfftfreq ( n , d=1.0 ) 192 Chapter 2. APIymjax, Release 0.0.1 Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft).LAX-backend implementation of rfftfreq() . ADDITIONOriginal docstring below.LAX-backend implementation of rfftfreq() . Original docstring below.The returned float array f contains the frequency bin centers in cycles per unit of the sample spacing (with zeroat the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second.Given a window length n and a sample spacing d : f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is evenf = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd Unlike fftfreq (but like scipy.fftpack.rfftfreq ) the Nyquist frequency component is considered to be positive. Returns f – Array of length n//2 + 1 containing the sample frequencies. Return type ndarray Examples >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) >>> fourier = np.fft.rfft(signal) >>> n = signal.size >>> sample_rate = 100 >>> freq = np.fft.fftfreq(n, d=1./sample_rate) >>> freqarray([ 0., 10., 20., ..., -30., -20., -10.]) >>> freq = np.fft.rfftfreq(n, d=1./sample_rate) >>> freqarray([ 0., 10., 20., 30., 40., 50.]) mfcc ( signal , window , hop , n_filter , low_freq , high_freq , nyquist , n_mfcc , nfft=None , mode='valid' , apod= Logit ufunc for ndarrays. multivariate_normal (key, mean, cov[, shape,. . . ]) Sample multivariate normal random values with givenmean and covariance. normal (key[, shape, dtype]) Sample standard normal random values with givenshape and float dtype. pareto (key, b[, shape, dtype]) Sample Pareto random values with given shape and floatdtype. randint (key, shape, minval, maxval[, dtype]) Sample uniform random values in [minval, maxval)with given shape/dtype. shuffle (key, x[, axis]) Shuffle the elements of an array uniformly at randomalong an axis. truncated_normal (key, lower, upper[, shape, . . . ]) Sample truncated standard normal random values withgiven shape and dtype. uniform (key[, shape, dtype, minval, maxval]) Sample uniform random values in [minval, maxval)with given shape/dtype. Detailed Description bernoulli ( key: jax.numpy.lax_numpy.ndarray , p: jax.numpy.lax_numpy.ndarray = 0.5 , shape: Op-tional[Sequence[int]] = None ) → jax.numpy.lax_numpy.ndarraySample Bernoulli random values with given shape and mean.LAX-backend implementation of bernoulli() . ADDITIONOriginal docstring below.Returns: A random array with boolean dtype and shape given by shape if shape is not None, orelse p.shape . beta ( key: jax.numpy.lax_numpy.ndarray, a: Union[float, jax.numpy.lax_numpy.ndarray], b: Union[float,jax.numpy.lax_numpy.ndarray], shape: Optional[Sequence[int]] = None, dtype: numpy.dtype = 194 Chapter 2. APIymjax, Release 0.0.1 gamma ( key , a , shape=None , dtype= Return type ndarray See also: expit() Notes As a ufunc logit takes a number of optional keyword arguments. For more information see ufuncsNew in version 0.10.0. Examples >>> from scipy.special import logit, expit >>> logit([0, 0.25, 0.5, 0.75, 1])array([ -inf, -1.09861229, 0. , 1.09861229, inf]) expit is the inverse of logit : >>> expit(logit([0.1, 0.75, 0.999]))array([ 0.1 , 0.75 , 0.999]) Plot logit(x) for x in [0, 1]: >>> import matplotlib.pyplot as plt>>> x = np.linspace(0, 1, 501) >>> y = logit(x) >>> plt.plot(x, y) >>> plt.grid() >>> plt.ylim(-6, 6) >>> plt.xlabel('x') >>> plt.title('logit(x)') >>> plt.show() multivariate_normal ( key: jax.numpy.lax_numpy.ndarray , mean: jax.numpy.lax_numpy.ndarray , cov:jax.numpy.lax_numpy.ndarray , shape: Optional[Sequence[int]] = None , dtype:numpy.dtype = 196 Chapter 2. APIymjax, Release 0.0.1 Sample truncated standard normal random values with given shape and dtype.LAX-backend implementation of truncated_normal() . ADDITIONOriginal docstring below.Returns: A random array with the specified dtype and shape given by shape if shape is not None,or else by broadcasting lower and upper . uniform ( key: jax.numpy.lax_numpy.ndarray , shape: Sequence[int] = () , dtype: numpy.dtype = Grayscale digit classification. symjax.datasets.fashionmnist Grayscale image classification symjax.datasets.dsprites greyscale image classification and disentanglement symjax.datasets.svhn Street number classification. symjax.datasets.cifar10 Image classification. symjax.datasets.cifar100 Image classification. symjax.datasets.ibeans Plant images classification. symjax.datasets.cassava Plant images classification. symjax.datasets.stl10 Image classification with extra unlabeled images. symjax.datasets.tinyimagenet Tiny Imagenet has 200 classes. Audio symjax.datasets.audiomnist digit recognition symjax.datasets.esc ESC-10/50: Environmental Sound Classification symjax.datasets.warblr Binary audio classification, presence or absence of abird. symjax.datasets.gtzan music genre classification symjax.datasets.dcldesymjax.datasets.irmas music instrument classification symjax.datasets.vocalset singer/technique/vowel of singing voices continues on next page Table 6 – continued from previous page symjax.datasets.freefield1010 Audio binary classification, presence or absence of birdsongs. symjax.datasets.birdvox_70k a dataset for avian flight call detection in half-secondclips symjax.datasets.birdvox_dcase_20k Binary bird detection classification Detailed description (Image) class mnist Grayscale digit classification.The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples,and a test set of 10,000 examples. It is a subset of a larger set available from NIST. The digits have beensize-normalized and centered in a fixed-size image. It is a good database for people who want to try learningtechniques and pattern recognition methods on real-world data while spending minimal efforts on preprocessingand formatting. static download ( path ) Download the MNIST dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. static load ( path=None ) Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • train_images ( array )• train_labels ( array )• valid_images ( array )• valid_labels ( array )• test_images ( array )• test_labels ( array ) class fashionmnist Grayscale image classificationZalando ‘s article image classification. Fashion-MNIST is a dataset of Zalando ‘s article images consisting ofa training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image,associated with a label from 10 classes. We intend Fashion-MNIST to serve as a direct drop-in replacement forthe original MNIST dataset for benchmarking machine learning algorithms. It shares the same image size andstructure of training and testing splits. download () Download the fashion-MNIST dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. load () Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present 198 Chapter 2. APIymjax, Release 0.0.1 Returns • train_images ( array )• train_labels ( array )• test_images ( array )• test_labels ( array ) class dsprites greyscale image classification and disentanglementThis dataset consists of 737,280 images of 2D shapes, procedurally generated from 5 ground truth independentlatent factors, controlling the shape, scale, rotation and position of a sprite. This data can be used to assess thedisentanglement properties of unsupervised learning methods.dSprites is a dataset of 2D shapes procedurally generated from 6 ground truth independent latent factors. Thesefactors are color, shape, scale, rotation, x and y positions of a sprite.All possible combinations of these latents are present exactly once, generating N = 737280 total images. download () Download the MNIST dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. load () Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • images ( array )• latent ( array )• classes ( array ) class svhn Street number classification.The SVHN dataset is a real-world image dataset for developing machine learning and object recognition algo-rithms with minimal requirement on data preprocessing and formatting. It can be seen as similar in flavor toMNIST (e.g., the images are of small cropped digits), but incorporates an order of magnitude more labeled data(over 600,000 digit images) and comes from a significantly harder, unsolved, real world problem (recognizingdigits and numbers in natural scene images). SVHN is obtained from house numbers in Google Street Viewimages. download () Download the SVHN dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. load () Parameters path ( str (optional) ) – default $DATASET_PATH, the path to look for thedata and where the data will be downloaded if not present Returns • train_images ( array ) • train_labels ( array )• test_images ( array )• test_labels ( array ) class cifar10 Image classification.The CIFAR-10 dataset was collected by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. It consists of 6000032x32 colour images in 10 classes, with 6000 images per class. There are 50000 training images and 10000 testimages. The dataset is divided into five training batches and one test batch, each with 10000 images. Thetest batch contains exactly 1000 randomly selected images from each class. The training batches contain theremaining images in random order, but some training batches may contain more images from one class thananother. Between them, the training batches contain exactly 5000 images from each class. download () Download the MNIST dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. load () Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • train_images ( array )• train_labels ( array )• test_images ( array )• test_labels ( array ) class cifar100 Image classification.The CIFAR-100 dataset is just like the CIFAR-10, except it has 100 classes containing 600 images each. Thereare 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into20 superclasses. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (thesuperclass to which it belongs). download () Download the CIFAR100 dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. class ibeans Plant images classification.This dataset is of leaf images taken in the field in different districts in Uganda by the Makerere AI lab incollaboration with the National Crops Resources Research Institute (NaCRRI), the national body in charge ofresearch in agriculture in Uganda.The goal is to build a robust machine learning model that is able to distinguish between diseases in the Beanplants. Beans are an important cereal food crop for Africa grown by many small-holder farmers - they are asignificant source of proteins for school-age going children in East Africa.The data is of leaf images representing 3 classes: the healthy class of images, and two disease classes includingAngular Leaf Spot and Bean Rust diseases. The model should be able to distinguish between these 3 classes 200 Chapter 2. APIymjax, Release 0.0.1 with high accuracy. The end goal is to build a robust, model that can be deployed on a mobile device and usedin the field by a farmer.The data includes leaf images taken in the field. The figure above depicts examples of the types of images perclass. Images were taken from the field/garden a basic smartphone.The images were then annotated by experts from NaCRRI who determined for each image which disease wasmanifested. The experts were part of the data collection team and images were annotated directly during thedata collection process in the field.Class Examples Healthy class 428 Angular Leaf Spot 432 Bean Rust 436 Total: 1,296Data Released 20-January-2020 License MIT Credits Makerere AI Lab static download ( path ) Download the ibeans dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. static load ( path=None ) Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • train_images ( array )• train_labels ( array )• valid_images ( array )• valid_labels ( array )• test_images ( array )• test_labels ( array ) class cassava Plant images classification.The data consists of two folders, a training folder that contains 5 subfolders that contain the respective imagesfor the different 5 classes and a test folder containing test images.Participants are to train their models using the images in the training folder and provide a submission file likethe sample provided which contains the image name exactly matching the image name in the test folder andthe corresponding class prediction with labels corresponding to the disease categories, cmd, healthy, cgm, cbsd,cbb.Please cite this paper if you use the dataset for your project: https://arxiv.org/pdf/1908.02900.pdf static download ( path ) Download the cassava dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. static load ( path=None ) Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • train_images ( array ) • train_labels ( array )• valid_images ( array )• valid_labels ( array )• test_images ( array )• test_labels ( array ) class stl10 Image classification with extra unlabeled images.The STL-10 dataset is an image recognition dataset for developing unsupervised feature learning, deep learning,self-taught learning algorithms. It is inspired by the CIFAR-10 dataset but with some modifications. In particu-lar, each class has fewer labeled training examples than in CIFAR-10, but a very large set of unlabeled examplesis provided to learn image models prior to supervised training. The primary challenge is to make use of theunlabeled data (which comes from a similar but different distribution from the labeled data) to build a usefulprior. We also expect that the higher resolution of this dataset (96x96) will make it a challenging benchmark fordeveloping more scalable unsupervised learning methods. static load ( path=None ) load the data Parameters path ( str (optional) ) – the path to look for the data and where it will bedownloaded if not present Returns • train_images ( array ) – the training images• train_labels ( array ) – the training labels• test_images ( array ) – the test images• test_labels ( array ) – the test labels• extra_images ( array ) – the unlabeled additional images class tinyimagenet Tiny Imagenet has 200 classes. Each class has 500 training images, 50 validation images, and 50 test images.We have released the training and validation sets with images and annotations. We provide both class labels anbounding boxes as annotations; however, you are asked only to predict the class label of each image withoutlocalizing the objects. The test set is released without labels. You can download the whole tiny ImageNet datasethere. Detailed description (Audio) class audiomnist digit recognition https://github.com/soerenab/AudioMNISTA simple audio/speech dataset consisting of recordings of spoken digits in wav files at 8kHz. The recordingsare trimmed so that they have near minimal silence at the beginnings and ends.FSDD is an open dataset, which means it will grow over time as data is contributed. In order to enable repro-ducibility and accurate citation the dataset is versioned using Zenodo DOI as well as git tags.Current status4 speakers 2,000 recordings (50 of each digit per speaker) English pronunciations 202 Chapter 2. APIymjax, Release 0.0.1 class esc ESC-10/50: Environmental Sound Classificationhttps://github.com/karolpiczak/ESC-50 load () ESC 50.https://github.com/karolpiczak/ESC-50 Parameters path ( str (optional) ) – default $DATASET_path), the path to look for thedata and where the data will be downloaded if not present Returns • wavs ( array ) – the wavs as a numpy array (matrix) with first dimension the data and seconddimension time• fine_labels ( array ) – the labels of the final classes (50 different ones) as a integer vector• coarse_labels ( array ) – the labels of the classes big cateogry (5 of them)• folds ( array ) – the fold as an integer from 1 to 5 specifying how to split the data oneshould not split a fold into train and set as it would make the same recording (but differentsubparts) be present in train and test, biasing optimistically the results.• esc10 ( array ) – the boolean vector specifying if the corresponding datum (wav, label, . . . )is in the ESC-10 dataset or not. That is, to load the ESC-10 dataset simply load ESC-50and use this boolean vector to extract only the ESC-10 data. class warblr Binary audio classification, presence or absence of a bird.Warblr comes from a UK bird-sound crowdsourcing research spinout called Warblr. From this initiative we have10,000 ten-second smartphone audio recordings from around the UK. The audio totals around 44 hours duration.The audio will be published by Warblr under a Creative Commons licence. The audio covers a wide distributionof UK locations and environments, and includes weather noise, traffic noise, human speech and even humanbird imitations. It is directly representative of the data that is collected from a mobile crowdsourcing initiative. download () Download the data load () Load the data given a path class gtzan music genre classificationThis dataset was used for the well known paper in genre classification “Musical genre classification of audiosignals” by G. Tzanetakis and P. Cook in IEEE Transactions on Audio and Speech Processing 2002. Unfortunately the database was collected gradually and very early on in my research so I have no titles (and ob-viously no copyright permission etc). The files were collected in 2000-2001 from a variety of sources includingpersonal CDs, radio, microphone recordings, in order to represent a variety of recording conditions. NevethelessI have been providing it to researchers upon request mainly for comparison purposes etc. Please contact GeorgeTzanetakis ([email protected]) if you intend to publish experimental results using this dataset.There are some practical and conceptual issues with this dataset, described in “The GTZAN dataset: Its contents,its faults, their effects on evaluation, and its future use” by B. Sturm on arXiv 2013. dclde alias of symjax.datasets.dclde class irmas music instrument classificationref https://zenodo.org/record/1290750 class vocalset singer/technique/vowel of singing voicessource: https://zenodo.org/record/1442513 load () Parameters path ( str (optional) ) – a string where to load the data and download if notpresent Returns • singers ( list ) – the list of singers as strings, 11 males and 9 females as in male1, male2,. . .• genders ( list ) – the list of genders of the singers as in male, male, female, . . .• vowels ( list ) – the vowels being pronunced• data ( list ) – the list of waveforms, not all equal length class freefield1010 Audio binary classification, presence or absence of bird songs. freefield1010. is a collection of over 7,000 204 Chapter 2. APIymjax, Release 0.0.1 excerpts from field recordings around the world, gathered by the FreeSound project, and then standardised forresearch. This collection is very diverse in location and environment, and for the BAD Challenge we have newlyannotated it for the presence/absence of birds. class birdvox_70k a dataset for avian flight call detection in half-second clipsVersion 1.0, April 2018.Created ByVincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and Juan PabloBello (2, 3).(1): Cornell Lab of Ornithology (CLO) (2): Center for Urban Science and Progress, New York University (3):Music and Audio Research Lab, New York Universityhttps://wp.nyu.edu/birdvoxDescriptionThe BirdVox-70k dataset contains 70k half-second clips from 6 audio recordings in the BirdVox-full-nightdataset, each about ten hours in duration. These recordings come from ROBIN autonomous recording units,placed near Ithaca, NY, USA during the fall 2015. They were captured on the night of September 23rd, 2015,by six different sensors, originally numbered 1, 2, 3, 5, 7, and 10.Andrew Farnsworth used the Raven software to pinpoint every avian flight call in time and frequency. He found35402 flight calls in total. He estimates that about 25 different species of passerines (thrushes, warblers, andsparrows) are present in this recording. Species are not labeled in BirdVox-70k, but it is possible to tell apartthrushes from warblers and sparrows by looking at the center frequencies of their calls. The annotation processtook 102 hours.The dataset can be used, among other things, for the research,development and testing of bioacoustic classifica-tion models, including the reproduction of the results reported in [1].For details on the hardware of ROBIN recording units, we refer the reader to [2].[1] V. Lostanlen, J. Salamon, A. Farnsworth, S. Kelling, J. Bello. BirdVox-full-night: a dataset and benchmarkfor avian flight call detection. Proc. IEEE ICASSP, 2018.[2] J. Salamon, J. P. Bello, A. Farnsworth, M. Robbins, S. Keen, H. Klinck, and S. Kelling. Towards theAutomatic Classification of Avian Flight Calls for Bioacoustic Monitoring. PLoS One, 2016.@inproceedings{lostanlen2018icassp, title = {BirdVox-full-night: a dataset and benchmark for avian flight calldetection}, author = {Lostanlen, Vincent and Salamon, Justin and Farnsworth, Andrew and Kelling, Steve andBello, Juan Pablo}, booktitle = {Proc. IEEE ICASSP}, year = {2018}, published = {IEEE}, venue = {Calgary,Canada}, month = {April}, } static download ( path ) Download the Birdvox dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. static load ( path=None ) Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • wavs ( array(70804, 12000) ) – the waveforms in the time amplitude domain• labels ( array(70804,) ) – binary values representing the presence or not of an avian • recording ( array(70804,) ) – the file number from which the sample has been extracted class birdvox_dcase_20k Binary bird detection classificationDataset is 16.5Go compressed.BirdVox-DCASE-20k: a dataset for bird audio detection in 10-second clipsVersion 2.0, March 2018.Created ByVincent Lostanlen (1, 2, 3), Justin Salamon (2, 3), Andrew Farnsworth (1), Steve Kelling (1), and Juan PabloBello (2, 3).(1): Cornell Lab of Ornithology (CLO) (2): Center for Urban Science and Progress, New York University (3):Music and Audio Research Lab, New York Universityhttps://wp.nyu.edu/birdvoxDescriptionThe BirdVox-DCASE-20k dataset contains 20,000 ten-second audio recordings. These recordings come fromROBIN autonomous recording units, placed near Ithaca, NY, USA during the fall 2015. They were captured onthe night of September 23rd, 2015, by six different sensors, originally numbered 1, 2, 3, 5, 7, and 10.Out of these 20,000 recording, 10,017 (50.09%) contain at least one bird vocalization (either song, call, orchatter).The dataset is a derivative work of the BirdVox-full-night dataset [1], containing almost as much data but for-matted into ten-second excerpts rather than ten-hour full night recordings.In addition, the BirdVox-DCASE-20k dataset is provided as a development set in the context of the “Bird AudioDetection” challenge, organized by DCASE (Detection and Classification of Acoustic Scenes and Events) andthe IEEE Signal Processing Society.The dataset can be used, among other things, for the development and evaluation of bioacoustic classificationmodels.We refer the reader to [1] for details on the distribution of the data and [2] for details on the hardware of ROBINrecording units.[1] V. Lostanlen, J. Salamon, A. Farnsworth, S. Kelling, J.P. Bello. “BirdVox-full-night: a dataset and bench-mark for avian flight call detection”, Proc. IEEE ICASSP, 2018.[2] J. Salamon, J. P. Bello, A. Farnsworth, M. Robbins, S. Keen, H. Klinck, and S. Kelling. Towards theAutomatic Classification of Avian Flight Calls for Bioacoustic Monitoring. PLoS One, 2016.Data FilesThe wav folder contains the recordings as WAV files, sampled at 44,1 kHz, with a single channel (mono). Theoriginal sample rate was 24 kHz.The name of each wav file is a random 128-bit UUID (Universal Unique IDentifier) string, which is randomizedwith respect to the origin of the recording in BirdVox-full-night, both in terms of time (UTC hour at the start ofthe excerpt) and space (location of the sensor).The origin of each 10-second excerpt is known by the challenge organizers, but not disclosed to the participants.Please Acknowledge BirdVox-DCASE-20k in Academic ResearchWhen BirdVox-70k is used for academic research, we would highly appreciate it if scientific publications ofworks partly based on this dataset cite the following publication: 206 Chapter 2. APIymjax, Release 0.0.1 V. Lostanlen, J. Salamon, A. Farnsworth, S. Kelling, J. Bello. “BirdVox-full-night: a dataset and benchmark foravian flight call detection”, Proc. IEEE ICASSP, 2018.@inproceedings{lostanlen2018icassp, title = {BirdVox-full-night: a dataset and benchmark for avian flight calldetection}, author = {Lostanlen, Vincent and Salamon, Justin and Farnsworth, Andrew and Kelling, Steve andBello, Juan Pablo}, booktitle = {Proc. IEEE ICASSP}, year = {2018}, published = {IEEE}, venue = {Calgary,Canada}, month = {April}, }The creation of this dataset was supported by NSF grants 1125098 (BIRDCAST) and 1633259 (BIRDVOX), aGoogle Faculty Award, the Leon Levy Foundation, and two anonymous donors. static download ( path ) Download the Birdvox dataset and store the result into the given path Parameters path ( str ) – the path where the downloaded files will be stored. If the directorydoes not exist, it is created. static load ( path=None ) Parameters path ( str (optional) ) – default ($DATASET_PATH), the path to look forthe data and where the data will be downloaded if not present Returns • wavs ( array ) – the waveforms in the time amplitude domain• labels ( array ) – binary values representing the presence or not of an avian• recording ( array ) – the file number from which the sample has been extracted symjax.initializers initializers alias of symjax.initializers glorot ( shape , gain=1 , distribution= For a DenseLayer , if gain='relu' and initializer=Uniform , the weights are initialized as .. math: a &= \sqrt{\frac{12}{fan_{ in }+fan_{out}}}\\W &\sim U[-a, a] If gain=1 and initializer=Normal , the weights are initialized as .. math: \sigma &= \sqrt{\frac{2}{fan_{ in }+fan_{out}}}\\W &\sim N(0, \sigma) he ( shape , gain=1.4142135623730951 , distribution= References See also: HeNormal() Shortcut with Gaussian initializer. HeUniform() Shortcut with uniform initializer. normal ( shape , mean=0.0 , std=1.0 ) Sample initial weights from the Gaussian distribution. Initial weight parameters are sampled from N(mean, std). Parameters • std ( float ) – Std of initial parameters.• mean ( float ) – Mean of initial parameters. uniform ( shape , range=0.01 , std=None , mean=0.0 ) Sample initial weights from the uniform distribution. Parameters are sampled from U(a, b). Parameters • range ( float or tuple ) – When std is None then range determines a, b. If range isa float the weights are sampled from U(-range, range). If range is a tuple the weights aresampled from U(range[0], range[1]). 208 Chapter 2. APIymjax, Release 0.0.1 • std ( float or None ) – If std is a float then the weights are sampled from U(mean -numpy.sqrt(3) * std, mean + numpy.sqrt(3) * std).• mean ( float ) – see std for description. symjax.layers Renormalization BatchNormalization (input_or_shape, axis, . . . ) batch-normalization layer Data Augmentation RandomCrop (input_or_shape, crop_shape, . . . ) random crop selection form the input RandomFlip (input_or_shape, p, axis, . . . [, seed]) random axis flip on the input Dropout (input_or_shape, p, deterministic[, seed]) binary mask onto the input Convolution Conv1D (input_or_shape, n_filters, filter_length) 1-D (time) convolution Conv2D (input_or_shape, n_filters, filter_shape) 2-D (spatial) convolution Pooling Pool1D (input_or_shape, pool_shape[, . . . ]) 2-D (spatial) pooling Pool2D (input_or_shape, pool_shape[, . . . ]) 2-D (spatial) pooling Utilities forward (input, layers) perform a forward path in the layers given an input symjax.optimizers optimizers alias of symjax.optimizers class Adam ( grads_or_loss , learning_rate , beta1=0.9 , beta2=0.999 , epsilon=1e-06 , params=None ) Adaptive Gradient Based Optimization with renormalization Parameters • grads_or_loss ( scalar tensor or list of gradients ) – either the loss(scalar of Tensor type) to be differentied or the list of gradients already computed and pos-sibly altered manually (such as clipping)• params ( list of parameters to update ) – if grads_or_loss is al list then it should be ordered w.r.t. the given parameters• learning_rate ( constant or Tensor ) – the learning rate use to update the pa-rameters• beta1 ( constant or Tensor ) – the value of the exponential moving average of theaverage of the gradients through time (updates)• beta2 ( constant or Tensor ) – the value of the exponential moving average of thevariance of the gradients through time updates Type list of updates variables Type list of variables class NesterovMomentum ( grads_or_loss , learning_rate , momentum , params=None ) Nesterov momentum Optimization Parameters • grads_or_loss ( scalar tensor or list of gradients ) – either the loss(scalar of Tensor type) to be differentied or the list of gradients already computed and pos-sibly altered manually (such as clipping)• params ( list of parameters to update ) – if grads_or_loss is al list then itshould be ordered w.r.t. the given parameters• learning_rate ( constant or Tensor ) – the learning rate use to update the pa-rameters updates Type list of updates variables Type list of variables class SGD ( grads_or_loss , learning_rate , params=None ) Gradient Descent Optimization Parameters • grads_or_loss ( scalar tensor or list of gradients ) – either the loss(scalar of Tensor type) to be differentied or the list of gradients already computed and pos-sibly altered manually (such as clipping)• params ( list of parameters to update ) – if grads_or_loss is al list then itshould be ordered w.r.t. the given parameters• learning_rate ( constant or Tensor ) – the learning rate use to update the pa-rameters updates Type list of updates variables Type list of variables 210 Chapter 2. APIHAPTER THREEINDICES AND TABLES • genindex• modindex• search IBLIOGRAPHY [CT] Cooley, James W., and John W. Tukey, 1965, “An algorithm for the machine calculation of complex Fourierseries,” Math. Comput. 19: 297-301. YTHON MODULE INDEX s symjax , 10 symjax.initializers , 207 symjax.layers , 209 symjax.optimizers , 209 symjax.tensor , 10 symjax.tensor.control_flow , 11 symjax.tensor.index_ops , 12 symjax.tensor.ops_math , 14 symjax.tensor.pdfs , 172 symjax.tensor.random , 193 symjax.tensor.signal , 173 symjax.utils , 197, 197