Questions tagged [numpy-einsum]
NumPy's `einsum` function implements the Einstein summation convention for multidimensional array objects. Use this tag for questions about how `einsum` can be applied to a particular problem in NumPy, or more questions about how the function works.
243
questions
1
vote
1
answer
32
views
Vectorizing Mahalanobis distance - numpy
I have been looking at the answer from @Danita's answer (Vectorizing code to calculate (squared) Mahalanobis Distiance), which uses np.einsum to calculate the squared Mahalanobis distance. In that ...
0
votes
0
answers
51
views
Python - How to optimize einsum?
I am trying to optimize my code and I don't know if I am already at the limit.
Here is my problem: I am solving the equation of motion for multiple trajectories. What this means is that I have an ...
1
vote
1
answer
49
views
Optimizing np.einsum calls in Python
I have two numpy arrays: X of dimension (N,N,N,N) and Y of dimension (N,N). My goal is to evaluate the following einsum call as fast as possible:
Z = np.einsum('iiii,ij,ik,il,im->jklm', X, Y, Y, Y, ...
0
votes
1
answer
85
views
Cupy Code Optimization: How to speed up nested for loops
I would like to optimize the python code between the 2 perf_counter functions.
By using cupy I already obtained substantial improvement compared to numpy.
I was asking myself if there is some ...
0
votes
1
answer
41
views
How to use numpy.einsum to add redundant indices
Suppose I have an N x N x N dimensional numpy array X with entries X[i,j,k]. I want to use X to define an N x N x N x N dimensional numpy array Y defined as follows:
Y[i,j,k,k] = X[i,j,k]
Y[i,j,k,l] = ...
0
votes
2
answers
39
views
Is it possible to invert this numpy einsum operation?
Is it possible to invert this einsum operation so I get back the input psi4d from it's output psi1 and psi2?
psi1 = np.einsum('jqik->ij', psi4d)
psi2= np.einsum('kiqj->ij', psi4d)...
1
vote
1
answer
63
views
How can I flip matrix elements in triple-wise rows in numpy?
I have a matrix with the shape (3*k, 3*l) (e.g.: k=2, l=1):
A = np.arange(18).reshape(6, 3)
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[12, 13, 14],
...
0
votes
0
answers
22
views
rewrite einsum("bhwHW,bHWc->bhwc") without einstein notation
The example code of DDPM works well in python. But after I convert it into tensorflowjs model, and run it in web browser, this line failed with error.
tf.einsum("bhwHW,bHWc->bhwc", ...
1
vote
1
answer
66
views
In PyTorch, how can I avoid an expensive broadcast when adding two tensors then immediately collapsing?
I have two 2-d tensors, which align via broadcasting, so if I add/subtract them, I incur a huge 3-d tensor. I don't really need that though, since I'll be performing a mean on one dimension. In this ...
5
votes
2
answers
338
views
Write numpy einsum operation as eigen tensors
I want to write the following numpy einsum as a an Eigen Tensor op
import numpy as np
L = np.random.rand(2, 2, 136)
U = np.random.rand(2, 2, 136)
result = np.einsum('ijl,jkl->ikl', U, L)
I can ...
0
votes
1
answer
42
views
How to perform the MaxSim operator leveraging torch procedures?
Let T and L be two batches of matrices (MxN) and a function f(ti,lj) that calculates a score for matrices ti and lj. For instance, if
T, L= torch.rand(4,3,2), torch.rand(4,3,2)
# T = tensor([[[0.0017,...
0
votes
1
answer
40
views
Mapping timeseries sequence input shape to desired output shape using EinsumDense
Can anyone help me understand how to handle compressing/expanding the dimension of a tensor using EinsumDense?
I have a timeseries (not NLP) input tensor of the shape (batch, horizon, features) ...
1
vote
0
answers
48
views
Einsum matrix multiplication with missing dimensions
I want to modify this einsum to be more flexible. Right now it's doing a matrix multiplication of the last two dimensions of A against the last 3 of B:
tf.einsum("...xp,...pyz->...xyz", A,...
-1
votes
1
answer
61
views
Einsum multiply each row with every one for 3X3X3 array
Hello could someone please help me figure out how to use np.einsum to produce the below code's result. I have a (3,3,3) tensor and I will like to get this results which I got from using two for loops. ...
0
votes
0
answers
87
views
convert python Einsum to fast C++
I have converted this python eimsum expression
psi_p = np.einsum('ij...,j...->i...', exp_p, psi_p)
to c++ like this:
int io=0;
`for (i=0; i < 4; i++){
ikauxop=i*nd;
for (j=...
0
votes
0
answers
50
views
Multiplication of 3d array using np.einsum
Hello I have just recently started working with python 3d arrays and I am not too familiar with how to multiply each block in the 3d array with all other blocks in the 3d array. I am working with a np ...
2
votes
2
answers
84
views
Translating np.einsum to something more performant
Using python/numpy, I have the following np.einsum:
np.einsum('abde,abc->bcde', X, Y)
Y is sparse: for each [a,b], only one c == 1; all others := 0.
For an example of relative size of the axes, X....
1
vote
0
answers
175
views
How to get numpy einsum to ignore nan's?
Let's say you use einsum to calculate the slope and intercept in a simple regression as follows:
slope = (np.einsum('ij,ij->i', y_norm, x_norm) /
np.einsum('ij,ij->i', x_norm, x_norm))...
0
votes
2
answers
69
views
numpy.einsum with ellipses of different dimensionality
I often find that I'd like like to do an operation between the last few dimensions of two arrays, where the first dimensions don't necessarily match. As an example I'd like to do something like:
a = ...
1
vote
1
answer
217
views
Einsum for shapes of different sizes or ranks
I have two PyTorch tensors. One is rank three and the other is rank four. Is there a way to get it so that it produce the rank and shape of the first tensor? For instance in this cross-attention bit:
...
1
vote
1
answer
47
views
How to multiply Tensorflow arrays across specified indicies
I would like to multiply two Tensorflow Arrays in a certain way as shown in the code below:
import tensorflow as tf
from tensorflow.keras import mixed_precision
policy = mixed_precision.Policy('...
0
votes
1
answer
110
views
More efficient nested sum in numpy
I am trying to calculate a vectorised nested sum
(so effectively doing a separate calculation for each row k)
The fastest way I have come up with is to define a lower triangular matrix of ones to ...
0
votes
1
answer
46
views
numpy einsum for multiplication looped along axis
I have an 2 x 2 matrix yy
yy = np.array([[0.5, 0], [0, 2]])
print(yy)
array([[0.5, 0. ],
[0. , 2. ]])
and n=3 x 4 x 2 matrix xy
xy = np.array([
[[1, 0.1], [2, 0.2], [3, 0.3], [4, 0.4]],
...
0
votes
0
answers
22
views
Improving the time for summing a stack of inverse matrices
I'm hoping to speed up a Python script that inverts a large number of small matrices (a 2D array of matrices basically) and then performs a matrix sum over one of the axes of the outer array. So far, ...
1
vote
1
answer
48
views
Standard operations equivalent of einsum expression
I have the following einsum expressions:
np.einsum("abc,ab->ac",a,b)
np.einsum("abc,abd->dc", a, b)
That I would need to convert to standard numpy operations. Can anyone help ...
-1
votes
1
answer
231
views
What does np.einsum('mk,nk', D, D) do?
I'm reading over someone else's code and am unsure what np.einsum does in this case.
print(np.einsum('mk,nk', D, D)) # D is an np array with shape (3, 100)
This code outputs an array with shape (3, 3)...
3
votes
1
answer
273
views
Einsum is slow for tensor multiplication
I'm trying to optimize a particular piece of code to calculate the mahalanobis distance in a vectorized manner. I have a standard implementation which used traditional python multiplication, and ...
1
vote
0
answers
46
views
Can a numpy.prod array reduction be replaced by numpy.einsum?
I have an huge 8D array view that i want to reduce to 2D by multiplying the elements together over 4 axes and summing them over 2 axes. I didn´t find any example in the numpy.einsum documentation ...
0
votes
0
answers
54
views
Proving Properties of Matrices (Associativity) using np.einsum
I'm experimenting with np.einsum and I was wondering if there's a way to prove Associativity just using np.einsum.
Here's the data:
A = np.array([[1, 1, 1],
[2, 2, 2],
[5, ...
0
votes
2
answers
282
views
How to compute the outer sum (similar to outer product
Given tensors x and y, each with shape (num_batches, d), how can I use PyTorch to compute the sum of every combination of x and y within a batch?
This is similar to outer product, except we don't want ...
2
votes
2
answers
93
views
numpy.einsum substantially speeds up computation - but numpy.einsum_path shows no speedup, what am I missing?
I have an odd case where I can see numpy.einsum speeding up a computation but can't see the same in einsum_path. I'd like to quantify/explain this possible speed-up but am missing something somewhere.....
2
votes
0
answers
70
views
NumPy einsum explicit mode with programmatic interface
NumPy's einsum lets you explicitly choose which axes are contracted with the so-called explicit mode, using ->:
>>> a = np.arange(9).reshape((3, 3))
>>> np.einsum('ij,ij->j', a,...
2
votes
1
answer
181
views
Efficient contractions with NumPy einsum paths
I have a set of contractions that I would like to optimize; for the contractions I am using np.einsum() from the NumPy module. The minimal reproducible example is here:
import numpy as np
from time ...
0
votes
0
answers
48
views
What does np.einsum act on? [duplicate]
I am facing with a problem!
How does np.einsum act on these tensors?
a = np.random.rand(2, 2, 5, 5)
b = np.random.rand(4, 5, 5, 1)
c = np.einsum('aijb,qwei->qweaj', b, a)
the output shape is: (2, ...
0
votes
1
answer
49
views
einsum not giving overflow error when applied to int arrays
I just had a bug which was based on np.sum and an equivalent (or at least I thought so...) np.einsum command not giving the same result. Here is an example:
import numpy.random
array = np.random....
5
votes
1
answer
136
views
Determining the validity of a multi-hot encoding
Suppose I have N items and a multi-hot vector of values {0, 1} that represents inclusion of these items in a result:
N = 4
# items 1 and 3 will be included in the result
vector = [0, 1, 0, 1]
# item ...
0
votes
1
answer
36
views
einsum equivalent for ndarray multiplication
I have the following multiplication routine:
import numpy as np
a = np.random.rand(3,3)
b = np.random.rand(3,50,50)
res = np.zeros((3, 50, 50))
for i in range(50):
for j in range(50):
res[:...
0
votes
1
answer
56
views
Matrix Vector Product across Multiple Dimensions
I have two arrays:
A = torch.rand((64, 128, 10, 10))
B = torch.rand((64, 128, 10))
I would like to compute the product, represented by C, where we do a matrix-vector multiplication across the first ...
3
votes
2
answers
229
views
Speeding up einsum for specific matrix and vector size
I have 2 arrays, one is of size:
A = np.random.uniform(size=(48, 1000000, 2))
and the other is
B = np.random.uniform(size=(48))
I want to do the following summation:
np.einsum("i, ijk -> jk&...
-1
votes
1
answer
69
views
Parallelize a matmul-like matrix computation (tensor product) in Numpy
I want to implement a tensor Tucker product s.t.,
Input: B in shape (m, n), C in shape (n, n, n) (cube).
Output: Y in shape (m, m, m), s.t. Y_ijk = ∑_{0≤a,b,c<n} B_ia * B_jb * B_kc * C_abc.
The ...
0
votes
1
answer
62
views
fastest way to stack ndarrays
Gist
Basically I want to perform an increase in dimension of two axes on a n-dimensonal tensor.
For some reason this operation seems very slow on bigger tensors.
If someone can give me a reason or ...
2
votes
1
answer
64
views
Einsum in python for a complex loop
I have complex loops in python that I'm trying to "vectorize" to improve computation time. I found the function np.einsum allowing it, I managed to use it, but I'm stuck with another loop.
...
1
vote
1
answer
139
views
Efficient way to "broadcast" the sum of elements of two 1D arrays to a 2D array
Is there a more efficient way (without loops) to do this with Numpy ?:
for i, x in enumerate(array1):
for j, y in enumerate(array2):
result[i, j] = x + y
I was trying to use einsum ...
2
votes
2
answers
350
views
Einsum formula for repeating dimensions
I have this piece of code:
other = np.random.rand((m,n,o))
prev = np.random.rand((m,n,o,m,n,o))
mu = np.zeros((m,n,o,m,n,o))
for c in range(m):
for i in range(n):
for j in range(o):
...
1
vote
1
answer
216
views
numpy einsum/tensordot with shared non-contracted axis
Suppose I have two arrays:
import numpy as np
a = np.random.randn(32, 6, 6, 20, 64, 3, 3)
b = np.random.randn(20, 128, 64, 3, 3)
and want to sum over the last 3 axes, and keep the shared axis. The ...
0
votes
0
answers
187
views
Vectorize this matmul like operation in Numpy, Numba, Cupy manner
Say I have an vector v(ij) and matrix M(jk).
v = np.array([1.0, 1.0, 0.0, 0.0], dtype=np.float32)
M = np.array([[0.0, 0.0, 0.2, 0.0],
[0.0, 0.0, 0.0, -0.1],
[0.0, 0.0, 0.0,...
0
votes
0
answers
50
views
Is there any DGEMM-type einsum in python?
In DGEMM http://www.netlib.org/lapack/explore-html/d1/d54/group__double__blas__level3_gaeda3cbd99c8fb834a60a6412878226e1.html#gaeda3cbd99c8fb834a60a6412878226e1
one can do C = alpha * A.B + beta*C
In ...
1
vote
1
answer
126
views
Why optimize in the einsum can accelerate binary contraction?
In https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
optimize{False, True, ‘greedy’, ‘optimal’}, optional
Controls if intermediate optimization should occur. No optimization will ...
1
vote
1
answer
100
views
Performing simple custom operations with Einsum
I am new to Einsum and wanted a particular case - using einsum for multiplying all elements of a matrix with each other; say given a 2D matrix:-
np.random.rand((16,2))
Multiplying elements across an ...
1
vote
1
answer
77
views
Simplify pytorch einsum
Consider the following pytorch snippet:
X = torch.einsum("rij, sij -> rs", A, A)
Y = torch.einsum("rij, sij -> rs", B, B)
Z = torch.einsum("rij, sij -> rs", C, C)...