Assume normal dot product:
M3[i,k] = sum_j(M1[i,j] * M2[j,k])
Now I would like to replace the sum by sum other operation, say the maximum:
M3[i,k] = max_j(M1[i,j] * M2[j,k])
This question is parallel to Numpy: Dot product with max instead of sum
Only now consider that the solutions
M3 = np.sum(M1[:,:,None]*M2[None,:,:], axis=1)
or
M3 = np.max(M1[:,:,None]*M2[None,:,:], axis=1)
should refer to a dense matrix M1
and a sparse matrix M2
. Unfortunately, 3d sparse matrices are not available in SciPy.
Basically, this would mean that in
M3[i,k] = max_j(M1[i,j] * M2[j,k])
we iterate only over j
such that M2[j,k]!=0
.
What is the most efficient way to solve this problem?
Here's an approach using one loop that iterated through the common axis of reduction -
Sample run for verification -
Specifically for dot-product, we have a built-in dot method and as such is straight-forward with it. Thus, we can convert the first input which is dense array to a sparse matrix and then use sparse matrix's
.dot
method, like so -Let's verify this too -