Home > Blockchain >  Numpy vectorization of mathematical equation
Numpy vectorization of mathematical equation

Time:10-10

I wrote equation https://img.codepudding.com/202110/8f8a0cc817224e4cbc6242206172cb7e.png with for loops:

A = np.random.rand(10, 100)
B = np.random.rand(100, 100)
c = np.random.rand(100)

@timeit
def operate_loops(X, W, b):
  y1 = 0
  y2 = 0
  y3 = 0
  l1 = 0
  l2 = 0
  for j in range(np.shape(X)[0]):
      for n in range(np.shape(W)[1]):
          for m in range(np.shape(W)[0]):
              y1=y1 X[j][m] * W[m][n]
          y2=y2 y1 b[n]
      y3=y3 y2

  return y3

Now I want to write this equation as numpy vectorized code, without use of loops. I do first summation https://img.codepudding.com/202110/0746e5d8fb224936bda99cfb0e6eb7e3.png like:

np.sum(x[0,:]*w[:,0])

but I don't have a clue how to other sigma summations without looping

CodePudding user response:

your equation translates to following

y = np.sum(X@W)   X.shape[0]*np.sum(b)

CodePudding user response:

Murali's answer is correct but a little bit overcomplicated (please everyone, trust broadcasting)

My simpler proposal is

y = np.sum(X@W b)

and here it's a small example of its application

In [20]: import numpy as np
    ...: X, W, b = np.ones((3,7)), np.ones((7,4)), np.arange(1,5)
    ...: print(b)
    ...: print(X@W)
    ...: print(X@W b)
    ...: print((8 9 10 11)*3)
    ...: print(np.sum(X@W)   X.shape[0]*np.sum(b)) # Murali's proposal
[1 2 3 4]
[[7. 7. 7. 7.]
 [7. 7. 7. 7.]
 [7. 7. 7. 7.]]
[[ 8.  9. 10. 11.]
 [ 8.  9. 10. 11.]
 [ 8.  9. 10. 11.]]
114
114.0

In [21]: print(y:=np.sum(X@W b))
114.0

CodePudding user response:

Proper answer was : y = np.sum(X@W) X.shape[0]*np.sum(b) (more clear for me) or : y = np.sum(X@W b)

My operate_loops function was bad because I misunderstood the equation meaning. Comment of gboffi helped me understand it:

the meaning of A_mn B_n is a matrix where each row, of length N, is summed term by term with the vector B also of length N.

My new proper operate_loops function is:

 def operate_loops(X, W, b):
    y1 = 0
    for j in range(np.shape(X)[0]):
        for n in range(np.shape(W)[1]):
            for m in range(np.shape(W)[0]):
                y1 = y1   X[j][m] * W[m][n]
            y1=y1 b[n]
    return y1
  • Related