Home > database >  Numpy: Compute dot product of 2d arrays with a condition before summation
Numpy: Compute dot product of 2d arrays with a condition before summation

Time:10-14

I have a problem where I have two arrays with dimensions n x d and d x h, where n, d, and h are positive integers that may or may not be the same. I am trying to find the dot product of the two matrices but with the condition that for each multiplication, I apply a function g to the term.

For example, in a case where n=2, d=3, and h=3 If I had the following matrices:

a = [[1, 2, 3], 
     [4, 5, 6]]

b = [[1, 2, 3],
     [4, 5, 6],
     [1, 1, 1]]

I would want to find c such that

c = [[g(1*1) g(2*4) g(3*1), g(1*2) g(2*5) g(3*1), g(1*3) g(2*6) g(3*1)],
     [g(4*1) g(5*4) g(6*1), g(4*2) g(5*5) g(6*1), g(4*3) g(5*6) g(6*1)]]

Any help would be appreciated

CodePudding user response:

I was able to do this by first doing the multiplications with broadcasting, applying g(), and then summing across the correct axis:

import numpy as np


def g(x):
    return 1 / (1   np.exp(-x))


a = np.array([[1, 2, 3], 
              [4, 5, 6]])


b = np.array([[1, 2, 3],
              [4, 5, 6],
              [1, 1, 1]])

First, the multiplication a[:, None] * b.T (probably a nicer way to do this), then evaluate g(x), then sum across axis 2:

>>> g(a[:, None] * b.T).sum(axis=2)
array([[2.68329736, 2.83332581, 2.90514211],
       [2.97954116, 2.99719203, 2.99752123]])

Verifying that the first row indeed matches your desired result:

>>> g(1*1)   g(2*4)   g(3*1)
2.683297355321972

>>> g(1*2)   g(2*5)   g(3*1)
2.8333258069316134

>>> g(1*3)   g(2*6)   g(3*1)
2.9051421094702645
  • Related