Robin
Robin

Reputation: 1609

Computing a slightly different matrix multiplication

I'm trying to find the best way to compute the minimum element wise products between two sets of vectors. The usual matrix multiplication C=A@B computes Cij as the sum of the pairwise products of the elements of the vectors Ai and B^Tj. I would like to perform instead the minimum of the pairwise products. I can't find an efficient way to do this between two matrices with numpy.

One way to achieve this would be to generate the 3D matrix of the pairwise products between A and B (before the sum) and then take the minimum over the third dimension. But this would lead to a huge memory footprint (and I actually dn't know how to do this).

Do you have any idea how I could achieve this operation ?

Example:

A = [[1,1],[1,1]]
B = [[0,2],[2,1]]

matrix matmul:

C = [[1*0+1*2,1*2+1*1][1*0+1*2,1*2+1*1]] = [[2,3],[2,3]]

minimum matmul:

C = [[min(1*0,1*2),min(1*2,1*1)][min(1*0,1*2),min(1*2,1*1)]] = [[0,1],[0,1]]

Upvotes: 1

Views: 260

Answers (2)

max9111
max9111

Reputation: 6492

Numba can be also an option

I was a bit surprised of the not particularly good Numexpr Timings, so I tried a Numba Version. For large Arrays this can be optimized further. (Quite the same principles like for a dgemm can be applied)

import numpy as np
import numba as nb
import numexpr as ne

@nb.njit(fastmath=True,parallel=True)
def min_pairwise_prod(A,B):
    assert A.shape[1]==B.shape[1]
    res=np.empty((A.shape[0],B.shape[0]))

    for i in nb.prange(A.shape[0]):
        for j in range(B.shape[0]):
            min_prod=A[i,0]*B[j,0]
            for k in range(B.shape[1]):
                prod=A[i,k]*B[j,k]
                if prod<min_prod:
                    min_prod=prod
            res[i,j]=min_prod
    return res

Timings

A=np.random.rand(300,300)
B=np.random.rand(300,300)

%timeit res_1=min_pairwise_prod(A,B) #parallel=True
5.56 ms ± 1.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit res_1=min_pairwise_prod(A,B) #parallel=False
26 ms ± 163 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit res_2 = ne.evaluate('min(A3D*B,2)',{'A3D':A[:,None]})
87.7 ms ± 265 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit res_3=np.min(A[:,None]*B,axis=2)
110 ms ± 214 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

A=np.random.rand(1000,300)
B=np.random.rand(1000,300)
%timeit res_1=min_pairwise_prod(A,B) #parallel=True
50.6 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit res_1=min_pairwise_prod(A,B) #parallel=False
296 ms ± 5.02 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit res_2 = ne.evaluate('min(A3D*B,2)',{'A3D':A[:,None]})
992 ms ± 7.59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit res_3=np.min(A[:,None]*B,axis=2)
1.27 s ± 15.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Upvotes: 1

Divakar
Divakar

Reputation: 221754

Use broadcasting after extending A to 3D -

A = np.asarray(A)
B = np.asarray(B)
C_out = np.min(A[:,None]*B,axis=2)

If you care about memory footprint, use numexpr module to be efficient about it -

import numexpr as ne

C_out = ne.evaluate('min(A3D*B,2)',{'A3D':A[:,None]})

Timings on large arrays -

In [12]: A = np.random.rand(200,200)

In [13]: B = np.random.rand(200,200)

In [14]: %timeit np.min(A[:,None]*B,axis=2)
34.4 ms ± 614 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [15]: %timeit ne.evaluate('min(A3D*B,2)',{'A3D':A[:,None]})
29.3 ms ± 316 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [16]: A = np.random.rand(300,300)

In [17]: B = np.random.rand(300,300)

In [18]: %timeit np.min(A[:,None]*B,axis=2)
113 ms ± 2.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [19]: %timeit ne.evaluate('min(A3D*B,2)',{'A3D':A[:,None]})
102 ms ± 691 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

So, there's some improvement with numexpr, but maybe not as much I was expecting it to be.

Upvotes: 1

Related Questions