Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Matrix outer product

Given two matrices

A: m * r
B: n * r

I want to generate another matrix C: m * n, with each entry C_ij being a matrix calculated by the outer product of A_i and B_j.

For example,

A: [[1, 2],
    [3, 4]]

B: [[3, 1],
    [1, 2]]

gives

C: [[[3, 1],  [[1 ,2],
     [6, 2]],  [2 ,4]],
     [9, 3],  [[3, 6],
     [12,4]],  [4, 8]]]

I can do it using for loops, like

    for i in range (A.shape(0)):
      for j in range (B.shape(0)):
         C_ij = np.outer(A_i, B_j)

I wonder If there is a vectorised way of doing this calculation to speed it up?

like image 594
Lei Yu Avatar asked Jul 19 '14 10:07

Lei Yu


People also ask

What is outer product in Python?

Numpy outer() is the function in the numpy module in the python language. It is used to compute the outer level of products like vectors, arrays, etc. If we try to combine the two vectors of the array's outer level, the numpy outer() function requires more than two levels of arguments that are passed into the function.

What is inner and outer product of matrix?

Inner and Outer Product. Definition: Inner and Outer Product. If u and v are column vectors with the same size, then uT v is the inner product of u and v; if u and v are column vectors of any size, then uvT is the outer product of u and v.

How do you calculate outer product?

If the two vectors have dimensions n and m, then their outer product is an n × m matrix.


2 Answers

The Einstein notation expresses this problem nicely

In [85]: np.einsum('ac,bd->abcd',A,B)
Out[85]: 
array([[[[ 3,  1],
         [ 6,  2]],

        [[ 1,  2],
         [ 2,  4]]],


       [[[ 9,  3],
         [12,  4]],

        [[ 3,  6],
         [ 4,  8]]]])
like image 86
hpaulj Avatar answered Sep 18 '22 06:09

hpaulj


temp = numpy.multiply.outer(A, B)
C = numpy.swapaxes(temp, 1, 2)

NumPy ufuncs, such as multiply, have an outer method that almost does what you want. The following:

temp = numpy.multiply.outer(A, B)

produces a result such that temp[a, b, c, d] == A[a, b] * B[c, d]. You want C[a, b, c, d] == A[a, c] * B[b, d]. The swapaxes call rearranges temp to put it in the order you want.

like image 40
user2357112 supports Monica Avatar answered Sep 21 '22 06:09

user2357112 supports Monica