bundles / numpy latest / numpy / _core / _multiarray_umath / c_einsum
built-in
numpy._core._multiarray_umath:c_einsum
Signature
c_einsum ( subscripts , * operands , out = None , dtype = None , order = K , casting = safe ) Summary
This documentation shadows that of the native python implementation of the `einsum` function, except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.
Extended Summary
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional, linear algebraic 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 that might not be considered classical Einstein summation operations, by disabling, or forcing summation over specified subscript labels.
See the notes and examples for clarification.
Parameters
subscripts: strSpecifies the subscripts for summation as comma separated list of subscript labels. An implicit (classical Einstein summation) calculation is performed unless the explicit indicator '->' is included as well as subscript labels of the precise output form.
operands: list of array_likeThese are the arrays for the operation.
out: ndarray, optionalIf provided, the calculation is done into this array.
dtype: {data-type, None}, optionalIf provided, forces the calculation to use the data type specified. Note that you may have to also give a more liberal
castingparameter to allow the conversions. Default is None.order: {'C', 'F', 'A', 'K'}, optionalControls the memory layout of the output. 'C' means it should be C contiguous. 'F' means it should be Fortran contiguous, 'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise. 'K' means it should be as close to the layout of the inputs as is possible, including arbitrarily permuted axes. Default is 'K'.
casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optionalControls what kind of data casting may occur. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations.
'no' means the data types should not be cast at all.
'equiv' means only byte-order changes are allowed.
'safe' means only casts which can preserve values are allowed.
'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.
'unsafe' means any data conversions may be done.
Default is 'safe'.
optimize: {False, True, 'greedy', 'optimal'}, optionalControls if intermediate optimization should occur. No optimization will occur if False and True will default to the 'greedy' algorithm. Also accepts an explicit contraction list from the
np.einsum_pathfunction. Seenp.einsum_pathfor more details. Defaults to False.
Returns
output: ndarrayThe calculation based on the Einstein summation convention.
Notes
The Einstein summation convention can be used to compute many multi-dimensional, linear algebraic 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 below along 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 a dimension 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 further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent 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 reordered alphabetically. 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) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript 'h' precedes subscript 'i'.
In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier '->' as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a) if a is a 1-D array, and np.einsum('ii->i', a) is like np.diag(a) if a is a square 2-D array. 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 output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). np.einsum('...i->...', a) is like np.sum(a, axis=-1) for array a of any shape. To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do 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 output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly. The examples below have corresponding einsum calls with the two parameter methods.
Views returned from einsum are now writeable whenever the input array is writeable. For example, 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 of the diagonal of a 2D array.
Examples
import numpy as np 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) np.einsum(a, [0,0]) np.trace(a)Extract the diagonal (requires explicit form):
np.einsum('ii->i', a) np.einsum(a, [0,0], [0]) np.diag(a)Sum over an axis (requires explicit form):
np.einsum('ij->i', a) np.einsum(a, [0,1], [0]) np.sum(a, axis=1)For higher dimensional arrays summing a single axis can be done with ellipsis:
np.einsum('...j->...', a) np.einsum(a, [Ellipsis,1], [Ellipsis])Compute a matrix transpose, or reorder any number of axes:
np.einsum('ji', c) np.einsum('ij->ji', c) np.einsum(c, [1,0]) np.transpose(c)Vector inner products:
np.einsum('i,i', b, b) np.einsum(b, [0], b, [0]) np.inner(b,b)Matrix vector multiplication:
np.einsum('ij,j', a, b) np.einsum(a, [0,1], b, [1]) np.dot(a, b) np.einsum('...j,j', a, b)Broadcasting and scalar multiplication:
np.einsum('..., ...', 3, c) np.einsum(',ij', 3, c) np.einsum(3, [Ellipsis], c, [Ellipsis]) np.multiply(3, c)Vector outer product:
np.einsum('i,j', np.arange(2)+1, b) np.einsum(np.arange(2)+1, [0], b, [1]) np.outer(np.arange(2)+1, b)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) np.einsum(a, [0,1,2], b, [1,0,3], [2,3]) np.tensordot(a,b, axes=([1,0],[0,1]))Writeable returned arrays (since version 1.10.0):
a = np.zeros((3, 3)) np.einsum('ii->i', a)[:] = 1 aExample of ellipsis use:
a = np.arange(6).reshape((3,2)) b = np.arange(12).reshape((4,3)) np.einsum('ki,jk->ij', a, b) np.einsum('ki,...k->i...', a, b) np.einsum('k...,jk', a, b)
See also
Aliases
-
numpy._core._multiarray_umath.c_einsum